最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

archives - Automatically Give All Custom Post Types a Pre-Set Category

programmeradmin6浏览0评论
This question already has answers here: How to add a default item to a custom taxonomy? (5 answers) Closed 5 years ago.

I am building a site with 5 different custom post types on and would like to create an archive page that pulls in all of these posts and then sorts them by the standard WP date order.

Instead of adding this 'all' category manually each time I add a custom post type post, is there anyway of giving a custom post type a custom taxonomy that is created / assigned each time a new post is created? I would then add any additional custom taxonomies manually when I do a post.

To show this 'all' taxonomy I would add a custom taxonomy archive page that would then show all of the custom post types.

Any help would be wonderful.

This question already has answers here: How to add a default item to a custom taxonomy? (5 answers) Closed 5 years ago.

I am building a site with 5 different custom post types on and would like to create an archive page that pulls in all of these posts and then sorts them by the standard WP date order.

Instead of adding this 'all' category manually each time I add a custom post type post, is there anyway of giving a custom post type a custom taxonomy that is created / assigned each time a new post is created? I would then add any additional custom taxonomies manually when I do a post.

To show this 'all' taxonomy I would add a custom taxonomy archive page that would then show all of the custom post types.

Any help would be wonderful.

Share Improve this question asked Feb 7, 2020 at 18:12 pjk_okpjk_ok 9082 gold badges15 silver badges36 bronze badges 1
  • 1 Does this answer your question? How to add a default item to a custom taxonomy? – Michael Commented Feb 7, 2020 at 18:54
Add a comment  | 

1 Answer 1

Reset to default 0

You can force default terms for a post by using the save_post hook. Here's an example from the Developer resources originallly by the user Aurovrata Venet.

add_action( 'save_post', 'set_post_default_category', 10,3 );

function set_post_default_category( $post_id, $post, $update ) {
    // Only want to set if this is a new post!
    if ( $update ){
        return;
    }

    // Only set for post_type = post!
    if ( 'post' !== $post->post_type ) {
        return;
    }

    // Get the default term using the slug, its more portable!
    $term = get_term_by( 'slug', 'my-custom-term', 'category' );

    wp_set_post_terms( $post_id, $term->term_id, 'category', true );
}

For checking post types you can also use in_array() as you have multiple post types.

! in_array( $post->post_type, array( 'my_post_type_a', 'my_post_type_b', 'my_post_type_n' ) )

Another option is to use the post type specific save_post_{$post->post_type} hook and attach the same callback function to each of your post types save actions.

发布评论

评论列表(0)

  1. 暂无评论