2017-06-05 26 views
1

在我的應用程序中,我需要在管理控制檯中創建一個小部件,它將顯示所有post_types的部分, 。WordPress:post_type-> rewrite ['slug']返回post_type,而不是slu 012

爲了實現上述我在functions.php文件添加以下代碼塊:

add_action('wp_dashboard_setup', 'tp_post_counts_reference'); 

    function tp_post_counts_reference() { 
     global $wp_meta_boxes; 
     wp_add_dashboard_widget('custom_help_widget', 'Posts in all post types', 'custom_dashboard_help'); 
    } 

    function custom_dashboard_help() { 
     $types = get_post_types(); 
     foreach($types as $type) 
     { 
      if($type != 'travelog' && $type != 'package_tour' && $type != 'hotel-info') continue; 
      $typeobj = get_post_type_object($type); 

      echo '<a href="/' . $typeobj->rewrite['slug'] . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts($type)->publish . '<br />'; 
     } 
    } 

但是$typeobj->rewrite['slug']實際輸出post_type而不是其對應的段塞。

例如: 我有以下的自定義文章類型

封氏(名稱:封氏,post_type:封氏,毛坯:travelogs)
酒店信息(名稱:酒店信息,post_type:酒店式信息,蛞蝓:酒店)

'<a href="/' . $typeobj->rewrite['slug'] . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts($type)->publish 

實際輸出是

<a href="/travelog">Travelog</a>: 6 

<a href="/hotel-info">Hotel</a>: 11 

時,我希望他們能輸出:

<a href="/travelogs">Travelog</a>: 6 

<a href="/hotels">Hotel</a>: 11 

請告訴我,我做錯了什麼:(

NB :我的WP v ersion是4.7.5

+0

感謝您的答覆。我試過你的解決方案,但它爲所有的帖子類型返回'home_url()'。好像根據https://wordpress.stackexchange.com/a/210545/109082,它返回false!我在我的CPT中添加了'has_archive => true;'(http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-post-types-archive-page-in-wordpress/) 。然後停用並重新激活插件。但是仍然所有的帖子類型都指向'home_url()'。出了什麼問題? –

+0

嗨,請忽略我以前的信息。我的CPT聲明中有一個錯字。你的解決方案實際上有效謝謝:) –

+0

我把它變成了一個答案,以幫助未來的訪客。如果它解決了您的問題,請考慮接受答案。 –

回答

1

與其嘗試手動構建您的帖子類型URL,我建議您改用內置WordPress功能get_post_type_archive_link

這將是這樣的:

function custom_dashboard_help() { 
    $types = get_post_types(); 

    // Alternate method for testing if custom type. 
    $custom_types = array('travelog', 'package_tour', 'hotel-info'); 
    foreach($types as $type) { 
     // If not a custom post type, don't render the link 
     if(! in_array($type, $custom_types)) { 
      continue; 
     } 

     $typeobj = get_post_type_object($type); 

     // Use get_post_type_archive_link function to get URL 
     echo '<a href="' . get_post_type_archive_link($type) . '">' . $typeobj->labels->name . '</a>: ' . wp_count_posts($type)->publish . '<br />'; 
    } 
}