John Davidson

php - Assign default taxonomy term to custom post type when new post created

0 comments
Message:


I have a custom post type called Press. For press, I have registered a taxonomy called topic.


Topics has the following options:



When a user creates a new press post, I want the Customers topic to already be checked. With my current approach, that doesn't seem to work.


Here is how I registered the post type:




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 ),
)
)
);


My Answer:
> true,
'taxonomies' => array('topic'),
'supports' => array('title', 'editor', 'thumbnail'),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'press'),
'menu_icon' => 'dashicons-megaphone',
)
)
);

And here is how I registered the taxonomy:

register_taxonomy(
'topic',
'press',
array(
'label' => 'Topics',
'hierarchical' => true,
'show_in_rest' => true,
)
);

To assign the default taxonomy term to the custom post type when a new post is created, you can use the `save_post` hook to check if the post is a Press post type and if it is a new post. If it is a new post, you can set the default taxonomy term for the topic taxonomy.

Here is an example code snippet to achieve this:

php
function set_default_topic_term($post_id, $post, $update) {
if ($post->post_type === 'press' && $update === false) {
$default_term = 'customers'; // Default term to be assigned
$term = term_exists($default_term, 'topic');

if ($term !== 0 && $term !== null) {
wp_set_object_terms($post_id, $default_term, 'topic');
}
}
}
add_action('save_post', 'set_default_topic_term', 10, 3);


In this code snippet, we check if the post type is 'press' and if it is a new post (not an update). If both conditions are met, we set the default term 'customers' for the topic taxonomy.

Make sure to replace 'customers' with the actual term you want to set as the default.

Rate this post

3 of 5 based on 7829 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us