WordPress bringing in template_part based on custom field

I have a WordPress loop on my index.php which brings in a specific template-part.

<?php if ( have_posts() ) : ?>

  <?php /* Start the Loop */ ?>
    <?php while ( have_posts() ) : the_post(); ?>

            <?php
                get_template_part( 'content' );
            ?>

        <?php endwhile; ?>

        <div class="clearfix"></div>

    <?php else : ?>

        <?php get_template_part( 'no-results', 'index' ); ?>

<?php endif; ?>

content.php has an article with the blog post information (title, featured image, etc) with specific html.

Read More

I have a custom-field, ExtraCSS, applied to each post through the content.php with values ‘post-right’ or ‘post-left’ (so I can change css of individual posts).

content.php code

<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);

<article class="<?php echo $ExtraCSS?>"> 

I want to have 2 different template_parts which can get called with the loop depending on the custom-field or value applied to the post.

EX. so if the post has the ExtraCSS custom-field value ‘post-right’ applied to it, the loop will bring in

get_template_part( 'content' , 'right' );

if the post has the ExtraCSS custom-field value ‘post-left’ it will bring in

get_template_part( 'content' , 'left' );

This may not be the right way to do it, and I’m open to other suggestions, but thats the overall idea. Wanting two different post-templates for one loop There will be numerous posts that have either one, and I want them all brought in one after the other.

Related posts

Leave a Reply

1 comment

  1. As you said it’s either one or the other template:

    <?php 
    $extraCSS = get_post_meta( get_the_ID(), 'ExtraCSS', true );
    if ( $extraCSS == 'post-right' ) {
        get_template_part( 'content' , 'right' );     
    }
    else {
         get_template_part( 'content' , 'left' );   
    }
    ?>