2010-06-09 29 views
7

Mi objetivo es simplemente utilizar algún tipo de método predeterminado para verificar si existe una categoría en Wordpress, y si no, agregue la categoría. Lo mismo con las etiquetas.Wordpress: ¿Insertar categoría y etiquetas automáticamente si no existen?

Aquí es un desastre 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 añadir esto como un plugin. ¡Cualquier idea o ayuda sería genial!

+0

Sory, no puso en el código de declaración:? user351297

Respuesta

9

Puede simplemente ejecutar;

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!

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

ACTUALIZACIÓN

Para obtener el ID de un término por slug, el uso;

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

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

+0

Hombre, ¿hay alguna posibilidad de usar la babosa para los padres? ¿O cambiando el código que utiliza el atributo slug? Porque tendría que configurar manualmente el código para asumir el ID e insertar los términos principales al principio (en lugar de simplemente conocer el nombre del slug). – user351297

+0

Sin problemas - verifique la respuesta actualizada :) – TheDeadMedic

0

Aquí es 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); 
Cuestiones relacionadas