我正在开发一个带有几个模板的WordPress主题。一个模板叫做"Tabs“。如果分配了此模板的页有子页,则其部分内容将显示在父页的选项卡中。因此,我只希望允许子页面的某些模板。
是否可以在某些条件下修改可用模板的列表(下拉)?是否有一个钩子来实现这一点?
我的过滤器/操作应该如下所示(伪代码):
if(parent_page->template == 'tabs')
remove template != 'tab-content'发布于 2018-05-03 10:33:12
可用模板的列表由get_page_templates生成。在此函数结束时,您将看到一个允许修改输出的筛选器。您可以使用它在特定条件下更改它,如下所示:
add_filter ('theme_page_templates','wpse302574_conditional_templates', 10, 4);
function wpse302574_conditional_templates ($post_templates, $this, $post, $post_type) {
$parent_id = wp_get_post_parent_id ($post->ID);
if (get_page_template_slug ($parent_id) == 'slug_of_your_parent_template') {
// remove unwanted templates from $post_templates
}
return $post_templates;
}(我没有测试这段代码,可能需要进行一些调试)
发布于 2018-05-03 10:54:29
你可以做这样的事
function wpdocs_filter_theme_page_templates( $page_templates, $this, $post ) {
$parent_id = wp_get_post_parent_id( $post->ID );
$parent_template = get_page_template_slug( $parent_id );
if( 'template-parent.php' === $parent_template ){ // compare parent template
foreach ($page_templates as $key => $value) {
if( 'template-child.php' != $key ){ // compare child template
unset( $page_templates[$key] ); // This will unset all the template except default template and child template
}
}
}
return $page_templates;
}
add_filter( 'theme_page_templates', 'wpdocs_filter_theme_page_templates', 20, 3 );请参阅https://developer.wordpress.org/reference/hooks/theme_页面_模板/模板
https://wordpress.stackexchange.com/questions/302574
复制相似问题