0

I'm trying to create an option on edit posts screen (backend) to select different post template based the selection and I need your opinions guys if that is the proper way.

Here is what I've tried so far and is working:

First I create meta box using 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' ),

    ),
) );

}

Then in single.php:

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

                            } 

Now when I choose Version 1 the template change to single-video.

So is that the proper way to do this or is better to use post formats?

Also is better (speed) to implement the plugin code n the theme code or just install the plugin?

Thank you

0

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() );
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.