問題描述
這似乎是愚蠢的問題。但是,我不能弄清楚:()
我需要在家裏顯示按鈕到自定義 post_type 的存檔 URL(archive- {post_type} .php) 。我怎麼做?
最佳解決方案
嗨 @Silent:
事實證明 WordPress 3.1 中有一個功能完全符合你的要求,它被命名為 get_post_type_archive_link(); 以下是您稱之為 (假定自定義帖子類型名為'product'):
<a href="<?php%20echo%20get_post_type_archive_link('product');%20?>">Products</a>
以下是我之前的答案,之前我發現 WordPress 確實有一個功能 built-in 為這種用例。
以前的答案:
除非我忽略了 WordPress 3.1 的核心源代碼中的某些東西,我想你正在尋找一個像 get_archive_link()這樣的函數,你可能會這樣稱呼 (假定自定義後綴類型為'product'):
<a href="<?php%20echo%20get_archive_link('product');%20?>">Products</a>
這裏是您可以將其放入主題的 function.php 文件或.php 文件中的源代碼,用於您可能正在編寫的插件:
if (!function_exists('get_archive_link')) {
function get_archive_link( $post_type ) {
global $wp_post_types;
$archive_link = false;
if (isset($wp_post_types[$post_type])) {
$wp_post_type = $wp_post_types[$post_type];
if ($wp_post_type->publicly_queryable)
if ($wp_post_type->has_archive && $wp_post_type->has_archive!==true)
$slug = $wp_post_type->has_archive;
else if (isset($wp_post_type->rewrite['slug']))
$slug = $wp_post_type->rewrite['slug'];
else
$slug = $post_type;
$archive_link = get_option( 'siteurl' ) . "/{$slug}/";
}
return apply_filters( 'archive_link', $archive_link, $post_type );
}
}
我實際上是在週末的這個確切的邏輯上,儘管我還沒有百分之百地肯定,所有的 use-cases 邏輯的順序是一般正確的,WordPress 可能會看到,雖然它可能適用於任何特定的網站。
這也是一個很好的事情,建議通過 trac 添加到 WordPress,我想我晚上會做。
次佳解決方案
當您註冊帖子類型時,您可以使用”has_archive” 參數傳遞一個字符串作為 slug,並確保您還將重寫設置為 true 或數組,但不是 false,那麼您的 CPT 歸檔 URL 將是 http://www.YOURDOMAIN.com/has_archive_slug 例如
如果你設置在你的 register_post_type 例如:
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => 'product',
'capability_type' => 'post',
'has_archive' => 'products',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','author','thumbnail','excerpt','comments')
);
register_post_type('product',$args);
那麼你的單個 URL 是:http://www.YOURDOMAIN.com/product/postName,你的歸檔 URL 是:http://www.YOURDOMAIN.com/products/
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。