Freddy
Freddy

Reputation: 857

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

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

Topics has the following options:

enter image description here

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

Here is how I registered the taxonomy:

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

And here is how I'm trying to get customers as the default checked option:

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

Currently, nothing is selected when I create a new press post.

Upvotes: 1

Views: 1096

Answers (2)

Lynk Neo
Lynk Neo

Reputation: 21

Use 'default_term' argument in register_taxonomy.

register_taxonomy(
  'Topic',  // the name of the taxonomy
  'press', // post type name
  array(
    ...
    'default_term' => array(
        'name' => 'Default term',
        'slug' => 'default-term',
        'description' => 'This is default term'
    )
  )
);

Upvotes: 2

Team Dolphin
Team Dolphin

Reputation: 273

Please try with this code.

Use wp_set_object_terms instead of 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 );
    }
}

Upvotes: 0

Related Questions