問題描述

乾草,我正在玩 WordPress 3.0 和兩個新功能,自定義帖子型別和選單編輯器。

我已經開始建立一個名為 「products」 的新的帖子型別,就像你猜到的,這個列表的產品。

我使用沼澤標準模板,我正在建立一個新的選單來替換頂級導航。據我看到,我只能新增一些”products”,我不能新增一個”archive” 的產品。我想要做的是新增一個選單連結去一個列出所有產品的頁面。

有什麼想法怎麼辦?

最佳解決方案

@dotty 你可以看到這個 trac 門票:應該有自定義帖子型別的索引頁面,所以顯然需要在 WordPress 核心尚未解決。

@John P Bloch 和 @Chris_O 都給你很好的選擇; 我要給你一個第三。

“Products” 頁

首先為您的自定義帖子型別建立一個頁面,並將其稱為”Products” 。這將給它以下 URL:

http://example.php/products/

“Products List” 短碼

接下來建立一個可以嵌入到”Products” 頁面中的 Shortcode 。在我的例子中,我稱之為 [product-list]。以下是使用它的螢幕截圖:

請注意,這樣的短程式碼將是新增大量可選功能的一個很好的候選者,並使其能夠處理許多不同的後期型別,但為了清晰起見,我幾乎都是硬編碼的一切。你當然可以用它作為你自己的短碼的起點:

<?php
add_shortcode('product-list', 'my_product_list');
function my_product_list($args) {
  $save_post = $GLOBALS['post'];  // Save state so you can restore later
  $post_type = 'product';
  $template_file = get_stylesheet_directory() . "/post-{$post_type}.php";
  if (!file_exists($template_file)) {
    return "<p>Missing template [$template_file].</p>";
  } else {
    global $post;
    $q = new WP_Query("showposts=10&post_type={$post_type}&orderby=title&order=ASC");
    $rows = array();
    $rows[] = '<div class="post-list ' . $post_type . '-post-list">';
    global $post_list_data;
    $post_list_data = array();
    $post_list_data['post_count'] = $post_count = count($q->posts);
    foreach ($q->posts as $post) {
      $q->the_post();
      ob_start();
      include($template_file);
      $rows[] = ob_get_clean();
    }
    $rows[] = '</div>';
    $GLOBALS['post'] = $save_post;
    return implode("n",$rows);
  }
}

post-product.php 主題模板檔案

接下來,您將需要建立一個僅顯示一個產品的主題模板檔案。實現短程式碼的功能命名為模板檔案 post-product.php,這裡是一個很好的起點:

<?php
/**
 * post-product.php - File to display only one product within a list of products.
 */
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  <h2 class="entry-title"><?php the_title(); ?></h2>
  <div class="entry-content">
    <?php the_content(); ?>
  </div>
</div>

新增選單選項

最後,您需要新增選單選項。這是非常簡單的,你可以從這個螢幕截圖中看到 (以下假設您之前對 WordPress 3.0 選單什麼也沒做,而且您使用的是支援 WordPress 3.0 選單的主題,例如 Twenty Ten):

  1. 在管理選單中選擇選單選項。

  2. 單擊”+” 新增一個新選單。

  3. 輸入你的選單名稱,無論你喜歡什麼。

  4. 點選”Create Menu” 按鈕 (螢幕截圖顯示”Save Menu”,但新增時它將是”Create Menu” 。)

  5. 選擇您的新選單作為您的”Primary Navigation” 。

  6. 選擇您的”Products” 頁面。

  7. 點選 「新增到選單」

  8. 點選”Save Menu”

最後,輸出

以下是一個基本的產品列表:

次佳解決方案

這不是 WordPress 的本機支援。但是,您可以將其新增到您的 functions.php 檔案中,並且它將工作:

function give_me_a_list_of_products(){
  add_rewrite_rule( 'products/?$', 'index.php?post_type=products', 'top' );
}

add_action( 'init', 'give_me_a_list_of_products' );

這將給你 example.com/products/作為產品列表。從那裡,您只需新增一個自定義連結到您的選單。

但是,如果您希望使用 Feed 進行真正歸檔 (按月,年等),則需要更詳細的程式碼。如果你的’products’ 是一個 non-hierarchical 的帖子型別 (好像應該是),你可以使用我的外掛:

http://www.wordpress.org/extend/plugins/custom-post-permalinks/

這給您額外的領域來定製您的永久連結 (像您可以使用部落格帖子),並將為您提供根據類別,作者,月,年,職位類別等自定義固定連結的能力。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。