我在创作上有点挣扎&;根据自定义帖子类型的发布和销毁时间删除术语。理想情况下,当发布自定义帖子类型时,我希望在自定义分类法中创建一个新术语。然后,当自定义帖子类型中的帖子被丢弃时,我需要检查并确保该术语的计数为0,如果是,则自动删除相应的术语。以下是我到目前为止的情况。创建函数工作正常,但我无法找出被破坏的函数。非常感谢您的专业知识!!
<?php
/**
* Automatically creates terms in \'custom_taxonomy\' when a new post is added to its \'custom_post_type\'
*/
function add_cpt_term($post_ID) {
$post = get_post($post_ID);
if (!term_exists($post->post_name, \'custom_taxonomy\'))
wp_insert_term($post->post_title, \'custom_taxonomy\', array(\'slug\' => $post->post_name));
}
add_action(\'publish_{custom_post_type}\', \'add_cpt_term\');
?>
。。。现在对于函数,我很难按照我想要的方式工作:
/**
* Automatically removes term in \'custom_taxonomy\' when the post of \'custom_post_type\' is trashed
*/
function remove_cpt_term($post_ID) {
$post = get_post($post_ID);
$term = get_term_by(\'name\', $post->post_name, \'custom_taxonomy\', \'ARRAY_A\');
if ($post->post_type == \'custom_post_type\' && $term[\'count\'] == 0)
wp_delete_term($term[\'term_id\'], \'custom_taxonomy\');
}
add_action(\'wp_trash_post\', \'remove_cpt_term\');
?>
SO网友:kaffolder
好的,我想我已经找到了一个可行的解决方案。有点失望,到目前为止,我还没有找到直接trash_{custom_post_type}
就像我能在publish_{custom_post_type}
钩这里有一个解决方案,可供其他正在与此问题作斗争的人使用。如果有人有更好的建议,请随时分享!
/**
* Automatically removes term in \'custom_taxonomy\' when the post of \'custom_post_type\' is trashed
*/
function remove_cpt_term($post_ID) {
$post = get_post($post_ID);
$term = get_term_by(\'slug\', $post->post_name, \'custom_taxonomy\');
// target only our custom post type && if no posts are assigned to the term
if (\'custom_post_type\' == $post->post_type && $term->count == 0)
wp_delete_term($term->term_id, \'custom_taxonomy\');
}
add_action(\'wp_trash_post\', \'remove_cpt_term\');