Wordpress从描述中获取类别

时间:2016-05-13 13:02:07

标签: php wordpress categories posts

我想从类别说明中获取类别ID。我以编程方式添加类别和帖子。如果类别不存在,我的脚本会添加类别。我从面板更改类别名称和slug。所以我的脚本每次都添加类别。 enter image description here


像这样:

$categoryDescription = 'bla bla';
$category = get_category_by_description($categoryDescription);
echo $category['name'];

1 个答案:

答案 0 :(得分:3)

没有对此进行测试,但尝试将以下函数添加到主题中的functions.php中:

function get_category_by_description($categoryDescription) {
    global $wpdb;

    $res = $wpdb->get_results("
        select 
            t.slug 
        from 
            {$wpdb->prefix}terms t, 
            {$wpdb->prefix}term_taxonomy tx 
        where 
            t.term_id = tx.term_id and 
            tx.description = '{$categoryDescription}'
    ");

    if (!empty($res)) {
        return get_category_by_slug($res[0]->slug);
    }

    return null;
}

然后你应该能够做到:

$categoryDescription = 'bla bla';
$category = get_category_by_description($categoryDescription);
echo $category->name;