创建 post 时,将分类术语动态添加到自定义 post 类型
Dynamically add taxonomy term to custom post type when post is created
我使用自定义 Post 类型 UI 插件创建了自定义 post 类型和分类法。前端有一个表单,填写后会在自定义 post 类型调查中创建一个新的 post。我希望 post 的标题(这是基于另一个 post 动态添加的)作为分类术语,自定义分类是 survey_category。我发现了这个:
add_action('publish_survey', 'add_survey_term');
function add_survey_term($post_ID) {
global $post;
$survey_post_name = $post->post_name;
wp_insert_term( $survey_post_name, 'survey_category');
}
但是好像不行。我需要它来插入术语,如果该术语已经存在,我需要它来更新与该术语关联的 post 的数量。
您可以使用 wp_set_object_terms()
将分类法动态添加到您的 post。此函数将插入术语,如果该术语已存在,它将更新与该术语关联的 post 的数量。我用 post 名称和分类名称做了一个小例子,你可以试试下面的代码:
$name = $_POST['value']['post_name'];
$tax_name = $_POST['value']['tax_name'];
$args = array(
'post_title' => $name,
'post_type' => 'your_post_type',
'post_status' => 'publish',
'comment_status' => 'close',
'ping_status' => 'closed'
);
$pid = wp_insert_post($args);
wp_set_object_terms($pid, $tax_name, 'your_tax_slug', false);
有关 wp_set_object_terms()
的更多参考,您可以查看 this link。
希望对您有所帮助。
我使用自定义 Post 类型 UI 插件创建了自定义 post 类型和分类法。前端有一个表单,填写后会在自定义 post 类型调查中创建一个新的 post。我希望 post 的标题(这是基于另一个 post 动态添加的)作为分类术语,自定义分类是 survey_category。我发现了这个:
add_action('publish_survey', 'add_survey_term');
function add_survey_term($post_ID) {
global $post;
$survey_post_name = $post->post_name;
wp_insert_term( $survey_post_name, 'survey_category');
}
但是好像不行。我需要它来插入术语,如果该术语已经存在,我需要它来更新与该术语关联的 post 的数量。
您可以使用 wp_set_object_terms()
将分类法动态添加到您的 post。此函数将插入术语,如果该术语已存在,它将更新与该术语关联的 post 的数量。我用 post 名称和分类名称做了一个小例子,你可以试试下面的代码:
$name = $_POST['value']['post_name'];
$tax_name = $_POST['value']['tax_name'];
$args = array(
'post_title' => $name,
'post_type' => 'your_post_type',
'post_status' => 'publish',
'comment_status' => 'close',
'ping_status' => 'closed'
);
$pid = wp_insert_post($args);
wp_set_object_terms($pid, $tax_name, 'your_tax_slug', false);
有关 wp_set_object_terms()
的更多参考,您可以查看 this link。
希望对您有所帮助。