php - 如何在 WordPress 中将 submit_button() 连接到 wp_insert_post()?
问题描述
我正在尝试在 WordPress 的管理区域中创建一个提交按钮,当我单击该按钮时,它会自动创建一个新帖子。
这是我的代码;
submit_button();
function programmatically_create_post() {
wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 'steve',
'post_title' => 'bronco',
'post_type' => 'post'
)
);
}
我已经测试了这个wp_insert_post
功能,它确实有效。
因此,这在管理区域中添加了一个非工作按钮,我无法弄清楚如何将 submit_button 连接到该wp_insert_post()
功能。如何将按钮连接到单击时创建新帖子的功能?
解决方案
您可以通过表单或 AJAX 执行此操作,具体取决于您更方便的方式。
非 AJAX 方式
首先创建一个 HTML 表单:
<form action="<?php echo admin_url( 'admin-post.php' ); ?>">
<input type="hidden" name="action" value="create_post">
<?php submit_button('Create post'); ?>
</form>
或者您可以简单地在链接中添加一个带有_GET
参数的按钮,如下所示:
<a href="http://www.example.com/wp-admin/admin-post.php?action=create_post">Create post</a>
然后你只需在你的函数 PHP 中创建一个钩子并将其绑定到你的函数,如下所示:
add_action('admin_post_create_post', 'programmatically_create_post');
function programmatically_create_post() {
wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 'steve',
'post_title' => 'bronco',
'post_type' => 'post'
)
);
}
AJAX方式
一个链接甚至一个 div 就足够了:
<a href="#" class="create-post">Create post</a>
在 JS 中,我们创建一个点击事件并向我们的服务器发送创建帖子的请求:
jQuery(document).ready(function($) {
$('.create-post').click(function(e) {
e.preventDefault();
$.post(
'/wp-admin/admin-ajax.php', // Change this accordingly
{ action: 'create-post'},
function(resp) {
console.log('Request sent. Result: ' + resp);
}
);
});
});
最后在 PHP 中,我们将函数添加到由 AJAX 请求触发的钩子中:
add_action('wp_ajax_create-post', 'programmatically_create_post');
function programmatically_create_post() {
wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 'steve',
'post_title' => 'bronco',
'post_type' => 'post'
)
);
}
这是一个非常基本的设置,但我想这足以让你继续前进:)
这是关于 AJAX 如何在 Wordpress中工作的官方文档的链接。您可以使用不同类型的输入(帖子类型、帖子状态等)增强您的请求,但更重要的是使用wp_nonce和其他安全措施使其更安全。不过,这超出了问题的范围。