开发者

Wordpress API question

How can I check if a category exists, and if exists, retur开发者_运维技巧n the ID; if not, create the category?


Use Wordpress is_category(), get_cat_ID() and wp_create_category() method.

<?php
  $CategoryName = "books";
  if(is_category($CategoryName))
        $categoryID = get_cat_ID($CategoryName);
  else
        $categoryID = wp_create_category($CategoryName);
?>


See wp_create_category().

include( "../../wordpress/wp-config.php" );
include( "../../wordpress/wp-admin/includes/taxonomy.php" );

$cat_id = wp_create_category( "TESTINGLOL" );
echo "created = {$cat_id}\n";
echo "returned = " . get_cat_ID( "TESTINGLOL" );

Output should go like:

created = 37450 returned = 37450

Note that this isn't very efficient, but, does the job.


create_category_if_not_exist($category_name, $echo = true) {
    $id = wp_insert_term( $category_name, 'category');
    if ( $echo ) return $id;
    return $id;
}

Nice all in one function for doing the trick. $category_name would need to be the category slug though.

wp_insert_term() takes care of checking if the category already exists in the database. It will return the $id of the category if it exists and will return the $id of the newly created category if it doesn't pre-exist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜