WordPress: ¿Insertar categoría y etiquetas automáticamente si no existen?

1 minuto de lectura

avatar de usuario
usuario351297

Mi objetivo es solo usar algún tipo de método predeterminado para verificar si existe una categoría en WordPress y, si no es así, agregar la categoría. Lo mismo con las etiquetas.

Aquí hay un lío que hice tratando de hacer que suceda:

<?php 
    if (is_term('football', 'category')) {
    } 
    else (
        $new_cat = array('cat_name' => 'Football', 'category_description' => 'Football Blogs', 'category_nicename' => 'category-slug', 'category_parent' => 'sports');
        $my_cat_id = wp_insert_category($new_cat);
    ) 

Planeo agregar esto como un complemento. ¡Cualquier pensamiento o ayuda sería genial!

  • Lo sentimos, no introduje el código para la declaración:

    – usuario351297

    9 de junio de 2010 a las 21:35

avatar de usuario
elmedicomuerto

Puedes simplemente correr;

wp_insert_term('football', 'category', array(
    'description' => 'Football Blogs',
    'slug' => 'category-slug',
    'parent' => 4 // must be the ID, not name
));

¡La función no agregará el término si ya existe para esa taxonomía!

Por interés, ¿cuándo llamará a este tipo de código en su complemento? ¡Asegúrese de registrarlo dentro de una función de enlace de activación, de lo contrario, se ejecutará en cada carga!

ACTUALIZAR

Para obtener la identificación de un término por slug, use;

$term_ID = 0;
if ($term = get_term_by('slug', 'term_slug_name', 'taxonomy'))
    $term_ID = $term->term_id;

Reemplace ‘taxonomía’ con la taxonomía del término, en su caso, ‘categoría’.

  • Hombre, ¿existe la posibilidad de usar la babosa como padre? ¿O cambiar el código que usa el atributo slug? Porque tendría que configurar manualmente el código para asumir la ID e insertar los términos principales al principio (en lugar de solo saber el nombre de la babosa).

    – usuario351297

    10 de junio de 2010 a las 20:29

Aquí se explica cómo asignar y crear la categoría si no existe

$pid = 168; // post we will set it's categories
$cat_name="lova"; // category name we want to assign the post to 
$taxonomy = 'category'; // category by default for posts for other custom post types like woo-commerce it is product_cat
$append = true ;// true means it will add the cateogry beside already set categories. false will overwrite

//get the category to check if exists
$cat  = get_term_by('name', $cat_name , $taxonomy);

//check existence
if($cat == false){

    //cateogry not exist create it 
    $cat = wp_insert_term($cat_name, $taxonomy);

    //category id of inserted cat
    $cat_id = $cat['term_id'] ;

}else{

    //category already exists let's get it's id
    $cat_id = $cat->term_id ;
}

//setting post category 
$res=wp_set_post_terms($pid,array($cat_id),$taxonomy ,$append);

var_dump( $res );

Hola. También puedes ir con esto si la categoría no existe.

//Get the categories names for every post in archive page using 'get_the_terms( ID, 'taxnomoy')'.
// Write your HTML Code/term name that you want to show if the category/term does not exist for the CPT (Custom Post Type) post

<?php $categories_name  = get_the_terms( $post->ID, "postino-happening-state" );

if( $categories_name == false ) :  // if caterory/term not exist ?>
// Write something...
<?php else: // if category exist ?>
// Write something...
<?php endif; ?>

¿Ha sido útil esta solución?