以正确的方式更改帖子模板

时间:2015-07-27 作者:LinekereDe

我正在尝试在编辑帖子屏幕(后端)上创建一个选项,根据选择选择选择不同的帖子模板,如果这是正确的方式,我需要你们的意见。

以下是我迄今为止所尝试并正在发挥的作用:

首先,我使用CMB2 Custom Fields

add_action( \'cmb2_init\', \'select_template\' );

function select_template() {

// Start with an underscore to hide fields from custom fields list
$prefix = \'_templatever_\';


 /* Initiate the metabox */
$tempver = new_cmb2_box( array(
    \'id\'            => \'template_options\',
    \'title\'         => __( \'Template Options\', \'idver\' ),
    \'object_types\'  => array( \'post\', ), // Post type
    \'context\'       => \'side\',
    \'priority\'      => \'high\',
    \'show_names\'    => true, // Show field names on the left
) );

$tempver->add_field( array(
    \'name\'             => \'Select Version\',
    \'id\'               => \'temp_ver\',
    \'type\'             => \'select\',
    \'show_option_none\' => true,
    \'options\'          => array(
        \'v1\' => __( \'Version 1\', \'cmb\' ),

    ),
) );
}

然后是单曲。php:

$version = get_post_meta( get_the_ID(), \'temp_ver\', true );
                            if ($version == \'v1\') {
                                get_template_part(\'single-video\'); 
                            } else {

                            } 
现在当我选择Version 1 模板更改为single-video.

那么,这是正确的方法还是使用post格式更好?

在主题代码中实现插件代码还是只安装插件(速度)更好?

非常感谢。

1 个回复
SO网友:Justin Sternberg

I think it\'s generally better to include the CMB2 plugin. As far as your question, there are a lot of ways to go about this, but I think your way is a solid one. I would make a couple changes. I\'d update your option values to be the name of your template-parts:

\'options\' => array(
    \'single-video\' => \'Single Video\',
),

Then I would add a helper function to your theme\'s functions.php:

function idver_get_post_template_part( $post_id ) {
    $template = get_post_meta( $post_id, \'temp_ver\', 1 );
    if ( ! $template ) {
        $template = \'default\'; // Whatever your fallback template part is
    }

    get_template_part( $template ); 
}

(obviously, update \'default\' to whatever your default/fallback template part should be. If NO default, that helper function should be updated a bit)

Then in your single.php, just call:

idver_get_post_template_part( get_the_ID() );
结束