如何根据自定义字段值动态更改WordPress页面模板?

问题描述 投票:0回答:1

`我正在开发一个 WordPress 项目,我需要根据自定义字段值动态更改帖子的页面模板。例如,如果将某个帖子的名为“page_template”的自定义字段设置为“template-1.php”,我希望该帖子使用“template-1.php”作为其页面模板,而不是分配给该帖子的默认模板。帖子类型。

wordpress wordpress-theming custom-wordpress-pages wordpress-shortcode
1个回答
0
投票

有一个 WP 过滤器钩子,它基本上决定要加载哪个模板文件。

add_filter( 'template_include', function( $template ) {
    if ( is_single()  ) {
        global $post;
        $meta_value = get_post_meta( $post->ID, 'page_template', true);
        if( $meta_value == "template-1.php" ) {
            return locate_template( array( 'template-1.php' ) );
        }   
    }
    return $template;
},99);
© www.soinside.com 2019 - 2024. All rights reserved.