問題描述
我有一個名為”Products” 的自定義帖子型別和名為”Usage” 的分類。在我的”Products” 著陸頁上,我想要透過客戶端透過所見即所得編輯的自定義內容。分類學著陸頁也是一樣。我的想法是建立假頁面,只需將內容透過 ID 拖入我的 archive-products.php 和 taxonomy-usage.php 模板,但我很好奇,如果有一個更好的方法來處理它。
最佳解決方案
第一個解決方案可以使用 Settings API 並建立 2 個欄位”Products Description” 和”Usage Description”,之後在模板中顯示欄位很容易像:
$options = get_option('my_theme_options');
echo $options['prod_description'];
// echo $options['usage_description'];
但是,設定 API 不是 WP 核心的最好的部分,並且可能建立一個設定頁面,只有這些欄位不值得。
另一種方法是使用頁面 (使用 custom page template) 作為存檔。
建立頁面並呼叫它”Product Archive”
在它裡面就是這樣的:
<?php
/*
Template Name: Products Archive
*/
get_header();
if ( have_posts() ) the post();
the_content(); // this will output the page content
$p_query = new WP_Query('post_type=products');
if ( $p_query->have_posts() ) { while( $p_query->have_posts() ) {
$p_query->the_post();
// this will require a 'entry-product.php' where you can put all your product markup
get_template_part('entry', 'product');
} }
wp_reset_postdata();
get_footer();
之後,在後端,建立一個頁面並將其分配給剛建立的模板。在頁面內容中填寫所需內容,當您開啟頁面時,您將看到頁面內容和產品。
對於分類頁面也可以這樣做。只需更改頁面模板和查詢。
如果由於任何原因需要使用 archive-products.php 作為產品存檔,另一種方法是建立自定義模板,但僅使用它來檢索頁面內容。
在您的主題中建立一個 php 檔案,並將其命名為’page-prod-description.php’ 。在這個檔案只放:
<?php
/*
Template Name: Products Description
*/
wp_safe_redirect( home_url() );
exit();
該檔案的作用是建立自定義頁面模板。該模板可以附加到頁面,但是這些頁面無法直接呼叫,因為如果您嘗試,那麼您將被重定向到主頁。
現在登入您的後端並建立一個頁面,標題為”Products Description” 並分配剛建立的頁面模板。如果您嘗試訪問 http://example.com/product-description 頁面,您將被重定向到主頁。
在您的產品歸檔模板 archive-products.php 中,可以使用該頁面中插入的內容:
$desc = get_pages('meta_key=_wp_page_template&meta_value=page-prod-description.php');
if ( ! empty($desc) ) {
$page = array_shift($desc);
echo apply_filters('the_content', $page->post_content );
}
現在您的客戶端可以登入後端並編輯頁面”Products Description”,並且頁面內容中的所有內容都將顯示在存檔頁面中。
相同的,當然可以做分類歸檔。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。