本篇文章更新時間:2019/06/27
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣 或 新台幣 贊助支持。
其實這篇也算誤打誤撞,原本想要用樣板結構的變數做法來取代 WooCommerce My Account 我的帳號頁面的訂單頁功能。(結果不能這樣)無奈機制不同, 在半路先被「我的帳號」給攔截走。
不過如果是其他頁面還是可以用 page-{$id}.php
或 page-{$slug}.php
去覆蓋。但這樣不太好管理這些檔案,全部都在子主題目錄下,所以有人寫了一段程式來改變這個樣板檔案架構。
add_filter(
'page_template',
function ($template) {
global $post;
if ($post->post_parent) {
// 取得最上層頁面
$parent = get_post(
reset(array_reverse(get_post_ancestors($post->ID)))
);
// 或
// 只需要抓到上一層
// $parent = get_post($post->post_parent);
$child_template = locate_template(
[
$parent->post_name . '/page-' . $post->post_name . '.php',
$parent->post_name . '/page-' . $post->ID . '.php',
$parent->post_name . '/page.php',
]
);
if ($child_template) {
return $child_template;
}
}
return $template;
}
);
參考:Is there a default template file for child pages / subpages?
這個程式碼片段加上去的話,還可以把子頁面使用上層目錄包覆的做法來掛樣板。
例如:
- [parent-page-slug]/page.php
- [parent-page-slug]/page-[child-page-slug].php
- [parent-page-slug]/page-[child-post-id].php
使用上還不錯,真是意外找到的方式!