問題描述
我有一個名為”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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。