WordPress作為全球最流行的內(nèi)容管理系統(tǒng),通常用戶都是在后臺發(fā)布文章。但有時我們需要在前臺實現(xiàn)發(fā)文功能,比如創(chuàng)建投稿系統(tǒng)或簡化發(fā)布流程。本文將介紹幾種實現(xiàn)WordPress前臺發(fā)文的代碼方法。
方法一:使用wp_insert_post函數(shù)
最基礎(chǔ)的方法是直接調(diào)用WordPress的核心函數(shù)wp_insert_post()
:
if(isset($_POST['submit_post'])){
$new_post = array(
'post_title' => sanitize_text_field($_POST['post_title']),
'post_content' => wp_kses_post($_POST['post_content']),
'post_status' => 'pending', // 設(shè)置為待審核
'post_author' => get_current_user_id(),
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
if($post_id){
// 成功插入文章后的操作
echo '文章已提交,等待審核!';
}
}
方法二:使用前端表單結(jié)合AJAX
更安全的方式是使用AJAX提交:
// 前端表單
<form id="frontend-post-form">
<input type="text" name="post_title" required>
<textarea name="post_content" required></textarea>
<input type="submit" value="提交文章">
</form>
// JavaScript
jQuery('#frontend-post-form').submit(function(e){
e.preventDefault();
jQuery.ajax({
url: frontend_ajax.ajaxurl,
type: 'POST',
data: {
action: 'frontend_post_submit',
title: jQuery('input[name="post_title"]').val(),
content: jQuery('textarea[name="post_content"]').val(),
security: frontend_ajax.security
},
success: function(response){
alert(response.data.message);
}
});
});
// PHP處理
add_action('wp_ajax_frontend_post_submit', 'handle_frontend_post_submit');
function handle_frontend_post_submit(){
check_ajax_referer('frontend_post_nonce', 'security');
$post_id = wp_insert_post(array(
'post_title' => sanitize_text_field($_POST['title']),
'post_content' => wp_kses_post($_POST['content']),
'post_status' => 'draft',
'post_author' => get_current_user_id()
));
if(!is_wp_error($post_id)){
wp_send_json_success(array('message' => '文章已保存為草稿'));
}else{
wp_send_json_error(array('message' => '發(fā)布失敗'));
}
}
方法三:使用插件簡化流程
如果不想寫代碼,可以考慮使用現(xiàn)成插件:
- User Submitted Posts - 簡單的前臺投稿插件
- Gravity Forms - 強大的表單構(gòu)建器,可與文章發(fā)布集成
- Frontend Publishing Pro - 專業(yè)的前臺發(fā)布解決方案
安全注意事項
- 始終對用戶輸入進行驗證和清理(sanitize_text_field, wp_kses_post等)
- 使用nonce防止CSRF攻擊
- 限制未登錄用戶或特定用戶角色的訪問權(quán)限
- 考慮設(shè)置默認狀態(tài)為”pending”或”draft”而非直接發(fā)布
通過以上方法,你可以根據(jù)項目需求靈活實現(xiàn)WordPress前臺發(fā)文功能,既可以是簡單的投稿系統(tǒng),也可以是復(fù)雜的內(nèi)容創(chuàng)作平臺。