Ajouter la catégorie à la publication personnalisée Type automatiquement, en utilisant la catégorie SLUG

wordpress.stackexchange https://wordpress.stackexchange.com/questions/26416

  •  30-10-2019
  •  | 
  •  

Question

j'utilise Cette excellente fonction Pour ajouter automatiquement une catégorie à mon type de message personnalisé "Videos" sur Publish, s'il n'y a pas de catégorie déjà choisie. Cela fonctionne très bien:

function add_video_category_automatically($post_ID) {
    global $wpdb;
    if(!has_term('','category',$post_ID)){
        $cat = array(394);
        wp_set_object_terms($post_ID, $cat, 'category');
    }
}
add_action('publish_videos', 'add_video_category_automatically');

Mais, j'aimerais vraiment obtenir l'identifiant de catégorie via la limace, afin que je n'aie pas à le changer manuellement lorsque je teste sur LocalHost vs le site en direct (qui peut avoir un identifiant différent pour cette catégorie en tant que localhost Et le site en direct n'est pas synchronisé).

J'ai essayé un certain nombre d'options, mais toutes entraînent une catégorie de "394" affectée à de nouveaux articles, plutôt que des "vidéos". Voici ma dernière tentative. Pouvez-vous me dire où je vais mal?

function add_video_category_automatically($post_ID) {
    global $wpdb;
    if(!has_term('','category',$post_ID)){
        $category = get_term_by( 'slug', 'videos', 'category' );
        $cat = array($category->term_id);
        wp_set_object_terms($post_ID, $cat, 'category');
    }
}
add_action('publish_videos', 'add_video_category_automatically');

Merci!

Pas de solution correcte

Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top