2016-05-13 157 views
0

我想從類別描述中獲取類別標識。我以編程方式添加類別和帖子。如果類別不存在,我的腳本添加類別。我更改面板的類別名稱和slu g。所以我的腳本每次都會添加類別。 enter image description hereWordpress從描述中獲取類別


像這樣:

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

你到目前爲止嘗試過什麼?請查看帖子[我如何提出一個好問題?](http://stackoverflow.com/help/how-to-ask) – GrumpyCrouton

回答

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; 
+0

感謝人爲我們提供了堅實的例子 –