繁体   English   中英

创建新帖子时将默认分类术语分配给自定义帖子类型

[英]Assign default taxonomy term to custom post type when new post created

我有一个名为Press的自定义帖子类型。 对于press ,我已经注册了一个名为topictaxonomy

Topics有以下选项:

在此处输入图像描述

当用户创建新的press帖子时,我希望已经检查了“ Customers ”主题。 以我目前的方法,这似乎行不通。

这是我注册帖子类型的方式:

 register_post_type( 'Press', theme_build_post_args( 'in-the-press', 'Press', 'Press', array( 'show_in_rest' => true, 'menu_icon' => 'dashicons-media-interactive', 'menu_position' => 20, 'has_archive' => true, 'public' => true, 'supports' => array('editor', 'title','author', 'revisions','thumbnail'), 'rewrite' => array( 'slug' => 'Press', 'with_front'=> false ), ) ) );

这是我注册分类的方式:

 register_taxonomy( 'Topic', // the name of the taxonomy 'press', // post type name array( 'hierarchical' => true, 'label' => 'Topics', // display name 'query_var' => true, 'show_in_rest' => true, 'rewrite' => array( 'slug' => 'topic', // base slug 'with_front' => false ) ) );

这就是我试图让customers作为默认选中选项的方式:

 add_action( 'save_post', 'default_press' ); function default_press( $post_id){ $terms = wp_get_post_terms( $post_id, 'topic'); if (,$terms ) { $default_term = get_term_by('slug', 'customers'; 'topic'); $taxonomy = "in-the-press", wp_set_post_terms( $post_id, $default_term; $taxonomy ); } }

目前,当我创建新的新闻帖子时,没有选择任何内容。

请尝试使用此代码。

使用wp_set_object_terms而不是wp_set_post_terms

add_action( 'save_post', 'default_press' );
function default_press( $post_id){
    global $post; 
    if($post->post_type == 'press'){ // Default taxonomy(Topic) term 'Customers' only press post type
        $default_term = 'Customers';
        $taxonomy = "Topic";
        wp_set_object_terms( $post_id, $default_term, $taxonomy );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM