簡體   English   中英

Wordpress:即使術語有對象,get_terms() 也不返回任何內容

[英]Wordpress: get_terms() not returning anything even if terms have objects

如果沒有分配給任何職位,get_terms 的正常行為是不返回術語。 但事實並非如此,我可以看到 admin 中分配的術語並檢查了數據庫,一切似乎都很好。 還要檢查此代碼:

$p = get_post(5018); // correctly returns the post

// works: returns the assigned term
$post_terms = wp_get_post_terms($p->ID, 'solutions_sectors', array("fields" => "all"));

// now the opposite:
$first = $post_terms[0];
$tid = $first->term_id;
// works: gives a list of post ids
$term_posts = get_objects_in_term($tid, 'solutions_sectors');

// still, this will output an empty array:
$terms = get_terms(array('taxonomy' => 'solutions_sectors');

// while this will output the right array (obviously):
$terms = get_terms(array('taxonomy' => 'solutions_sectors', 'hide_empty' => false));

所以,我的帖子確實有條款,但 get_terms 似乎沒有意識到這一點。 為什么?

請注意以下事項:

  • 我正在使用帶有自定義分類法的自定義帖子類型

  • 我使用 polylang 作為語言插件(但所有帖子和術語似乎都正確翻譯和分配)

發現問題:term_taxonomy 表的count 字段為空,這是因為我在自定義導入期間使用wp_insert_post()批量保存了我的帖子。

wp_insert_post()似乎有一個錯誤:它正確地將指定的術語應用於新帖子,但不更新 term_taxonomy 計數。

這里的解決方案是對 wp_update_term_count_now()` 的一次性調用。

由於我必須檢索在創建分類法之前執行的文件上的所有術語 ID,因此我必須將代碼包裝在 init 操作中。

add_action('init','reset_counts', 11, 0);
function reset_counts(){
  // I'm currently using polylang so first I get all the languages
  $lang_slugs = pll_languages_list(array('fields' => 'slug'));

  foreach($lang_slugs as $lang){
    $terms_ids = get_terms(array(
      'taxonomy' => 'solutions_sectors'
      ,'fields' => 'ids'
      ,'lang' => $lang
      ,'hide_empty' => false
    ));

    // it's important to perform the is_array check 
    if(is_array($terms_ids)) wp_update_term_count_now($terms_ids, 'solutions_sectors');
  }
}

這就是訣竅。 運行后,注釋掉 init 操作調用很重要。

如果get_terms由於某種奇怪的原因get_terms ,自定義分類法未顯示已注冊,請嘗試使用WP_Term_Query

$term_query = new WP_Term_Query( array( 
    'taxonomy' => 'regions', // <-- Custom Taxonomy name..
    'orderby'                => 'name',
    'order'                  => 'ASC',
    'child_of'               => 0,
    'parent' => 0,
    'fields'                 => 'all',
    'hide_empty'             => false,
    ) );


// Show Array info
echo "<pre>";
print_r($term_query->terms);
echo "</pre>";


//Render html
if ( ! empty( $term_query->terms ) ) {
foreach ( $term_query ->terms as $term ) {
echo $term->name .", ";
echo $term->term_id .", ";
echo $term->slug .", ";
echo "<br>";
}
} else {
echo '‘No term found.’';
}

從這里獲取所有參數: https : //developer.wordpress.org/reference/classes/WP_Term_Query/__construct/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM