问题
我正在创建我的第一个插件,在该插件中,用户可以(除其他外)通过wordpress后端的自定义表单创建新帖子。此帖子使用自定义帖子类型和自定义分类法。表单创建新帖子,但无法设置自定义taxomony。
定期创建帖子(不是通过我的自定义表单)效果很好,即允许我向其添加自定义taxomony。
自定义帖子类型和自定义分类由该书注册,术语已插入数据库。
*分类法不是用于调试目的的变量
add_action(\'plugins_loaded\', \'newpost\');
function newpost() {
if (isset($_POST[\'new_post\']) == \'1\') {
$post_title = $_POST[\'posttitle\'];
$post_content = $_POST[\'postcontent\'];
$new_post = array(
\'ID\' => \'\',
\'post_author\' => 1,
\'post_type\' => \'cars\',
\'post_content\' => $post_content,
\'post_title\' => $post_title,
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_status\' => \'publish\',
\'tax_input\' => array(\'cars\' => array(\'bmw\', \'audi\'))
);
$post_id = wp_insert_post($new_post);
}
}
我甚至试着移除
\'tax_input\' 和使用
wp_set_post_terms 和
wp_set_object_terms 但结果是一样的。两天来我一直在做这件事,所以非常感谢您的帮助。。。
解决方案plugins_loaded 到init 优先级较低。
add_action( \'init\', \'newpost\', 200 );
所以问题是,在启动插件时,用户权限尚未设置。
最合适的回答,由SO网友:Adam 整理而成
你试过了吗wp_set_object_terms?
...需要放置在您呼叫wp_insert_post
因为它需要post ID才能将正确的术语附加到具有正确post的正确分类中。
//add_action(\'plugins_loaded\', \'newpost\'); # will not work, user not authenticated
add_action(\'init\', \'newpost\'); // will work, user authenticated
function newpost() {
if (isset($_POST[\'new_post\']) == \'1\') {
$post_title = $_POST[\'posttitle\'];
$post_content = $_POST[\'postcontent\'];
$taxonomy = \'cars\'; //change accordingly...
$terms = $_POST[\'tax_terms\']; //change accordingly...
$new_post = array(
\'ID\' => \'\',
\'post_author\' => 1,
\'post_type\' => \'cars\',
\'post_content\' => $post_content,
\'post_title\' => $post_title,
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_status\' => \'publish\',
);
$post_id = wp_insert_post($new_post);
//$terms can be an array of term IDs/slugs
//$taxonomy is your taxonomy name, e.g. cars
wp_set_object_terms( $post_id, $terms, $taxonomy );
}
}