user3550879 user3550879 - 29 days ago 6
PHP Question

Adding new parameter to wordpress loop

I have the following code which is missing a part in order to determine which '

post
' to use.

html

<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
$postAlign = get_post_meta( get_the_ID(), 'postType', true );

if ( $postAlign == 'Lsection' ) {
get_template_part( 'article' , 'Lsection' );
}
else {
get_template_part( 'article' , 'Rsection' );
}
else {
get_template_part( 'article' , 'Fsection' );
}
?>
<?php endwhile; ?>
<?php endif; ?>


What I want is
if the post has postAlign of 'Lsection' use
article-Lsection.php
,
if the post has postAlign of 'Rsection' use
article-Rsection.php
,
if the post has postAlign of 'Fsection' use
article-Fsection.php


I know I there must be a else if or some similar function invloved

Answer

You should not have two consecutive else blocks...

if ( $postAlign == 'Lsection' ) {
    get_template_part( 'article' , 'Lsection' );     
}
else if ($postAlign == 'Rsection') {
    get_template_part( 'article' , 'Rsection' );   
}
else {
    get_template_part( 'article' , 'Fsection' );   
}

You could also use a switch statement - e.g.:

switch($postAlign) {
    case 'Lsection':
    case 'Rsection':
        get_template_part( 'article' , $postAlign );     
        break;
    default:
        get_template_part( 'article' , 'Fsection' );   
        break;
}

Or just simplify it even more:

if ( $postAlign == 'Lsection' || $postAlign == 'Rsection') {
    get_template_part( 'article' , $postAlign );     
}
else {
    get_template_part( 'article' , 'Fsection' );   
}

Also, is there a reason you are using the alternate syntax for control structures and excess closing/opening php tags? You should be able to simplify it, like this:

<?php 
if ( have_posts() ) {
   while ( have_posts() ) {
         the_post();
         $postAlign = get_post_meta( get_the_ID(), 'postType', true );

        if ( $postAlign == 'Lsection' || $postAlign == 'Rsection') {
            get_template_part( 'article' , $postAlign );     
        }
        else {
            get_template_part( 'article' , 'Fsection' );   
        }
    }//end while
}//end if
 //only need one closing php tag down here:
?>
Comments