1

I have a custom post type name session and a tag name post_tag.

This is the declaration of my custom post type :

function create_posttype()
{

  register_post_type(
    'session',
    array(
      'labels' => array(
        'name'                => __('Sessions'),
        'singular_name'       => __('Session'),
        'menu_name'           => __('Sessions'),
        'all_items'           => __('Toutes les sessions'),
        'view_item'           => __('Voir sessions'),
        'add_new'             => __('Ajouter'),
        'edit_item'           => __('Modifier'),
      ),
      'hierarchical'            => true,
      'public'                  => true,
      'show_in_rest'            => true,
      'supports'                => array('title', 'thumbnail', 'revisions, custom-fields'),
      'taxonomies'              => array('category', 'post_tag'),
      'menu_position'           => 20,
      'menu_icon'               => 'dashicons-groups',
    )
  );

}
add_action('init', 'create_posttype');

I need to add a tag, so i do this :

wp_set_post_tags($session->ID, "annule", false);

It works. But then i have a problem with my total of post type for this tags in the backend. So i do this :

$update_taxonomy = 'post_tag';
$get_terms_args = array('taxonomy' => $update_taxonomy,'hide_empty' => false);                      
$update_terms = get_terms($get_terms_args);
wp_update_term_count_now($update_terms,  $update_taxonomy);

But this doesn't work.

I suppose i'm doing something wrong. But i don't see what ?

Thanks

1
  • You shouldn't need to manually update the term count if WordPress is loaded correctly. So, when and where do you call wp_set_post_tags()? In a hook - what hook, if so?
    – Sally CJ
    Commented Jan 22, 2022 at 8:02

1 Answer 1

0

You pass the array of WP_Term objects instead of the array of term_id to the wp_update_term_count_now().

Pass the fields argument to get_terms() to specify it's output:

<?php
$update_taxonomy = 'post_tag';

$get_terms_args = array(
    'taxonomy'   => $update_taxonomy,
    'hide_empty' => false,
    'fields'     => 'ids', // nota bene.
);

$update_terms = get_terms( $get_terms_args ); // get the array of term IDs.

wp_update_term_count_now( $update_terms, $update_taxonomy );

See WP_Term_Query::__construct() parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.