【发布时间】:2018-06-25 14:24:34
【问题描述】:
我在 Wordpress 中有一篇自定义帖子,当用户在添加帖子时未选择任何类别时,我想为类别(我的自定义帖子的分类)添加一个默认值。
请帮助我,可用的答案对我没有帮助。 提前致谢!
【问题讨论】:
标签: wordpress custom-post-type custom-taxonomy
我在 Wordpress 中有一篇自定义帖子,当用户在添加帖子时未选择任何类别时,我想为类别(我的自定义帖子的分类)添加一个默认值。
请帮助我,可用的答案对我没有帮助。 提前致谢!
【问题讨论】:
标签: wordpress custom-post-type custom-taxonomy
法典上的对象术语:https://codex.wordpress.org/Function_Reference/wp_set_object_terms
此解决方案将在他们以自定义帖子类型发布帖子时设置默认类别。
function save_book_meta( $post_id, $post, $update ) {
$slug = 'book'; //Slug of CPT
// If this isn't a 'book' post, don't update it.
if ( $slug != $post->post_type ) {
return;
}
wp_set_object_terms( get_the_ID(), $term_id, $taxonomy );
}
add_action( 'save_post', 'save_book_meta', 10, 3 );
将来,请先浏览 Stack Exchange 并进行广泛的研究,然后再发布已经有数千个答案的问题:)
【讨论】:
您需要在 functions.php 中添加以下代码,确保使用您希望每个帖子保存的默认类别更改自定义分类和值。
未经测试,但这应该可以。
add_action('pre_post_update', 'saving_custom_single_post');
if( !function_exists('saving_custom_single_post') ){
function saving_custom_single_post( $post_id ){
if( get_post_type($post_id) == 'custom-post' ){
$term_list = wp_get_post_terms($post_id, 'custom-taxonomy', array("fields" => "all"));
if(empty($term_list)){
wp_set_object_terms( $post_id, 'custom-taxonomy', 'value', false );
}
}
}
}
【讨论】: