简体   繁体   中英

Nest a while loop in an if else statement in WordPress

I have a while loop that gets all pages of a certain category on index.php which is my posts page.

However, I want to change the code below, so if it is the homepage , it does not run this loop but displays some text .

This code the loop works:

<?php 
$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

$loop = new WP_Query( array( 
    'post_type' => 'story', 
    'cat' => $cat_id, 
    'posts_per_page' => 10,
    'orderby' => 'date', 
    'order' => 'DESC'
) );

while ( $loop->have_posts() ) : $loop->the_post(); 
?> <a href="<?php echo the_permalink(); ?>"><?php the_title();?></a>
endwhile;
?>

In this code, nothing loads on any page except the homepage :

 <?php
    $category = get_category( get_query_var( 'cat' ) );
    $cat_id = $category->cat_ID;

    $loop = array(
      'post_type' => 'story', 
        'cat' => $cat_id,
        'posts_per_page' => 10,
        'orderby' => 'date',
        'order' => 'DESC' ,
    'paged'=>$paged
    );
        if ( is_home() ) {      


        echo 'Welcome!';


    } else if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

                <h2><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h2>              

    <?php endwhile; endif; ?>

You need to wrap your query and loop in your is_home() condition

if ( !is_home() ) { // This is not the home page
    // Add your query and loop here
    $category = get_category( get_query_var( 'cat' ) );
    $cat_id = $category->cat_ID;

    $loop = new WP_Query( array( 
        'post_type' => 'story', 
        'cat' => $cat_id, 
        'posts_per_page' => 10,
        'orderby' => 'date', 
        'order' => 'DESC'
    ) );

    while ( $loop->have_posts() ) : $loop->the_post(); 
    ?> <a href="<?php echo the_permalink(); ?>"><?php the_title();?></a>
    endwhile;

} else { // This is the homepage
    echo 'Some text here';
}
<?php
    $category = get_category( get_query_var( 'cat' ) );
    $cat_id = $category->cat_ID;

    $loop = new WP_Query( array( 
    'post_type' => 'story', 
    'cat' => $cat_id, 
    'posts_per_page' => 10,
    'orderby' => 'date', 
    'order' => 'DESC'
) );
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $the_query->the_post(); 
    if ( is_home() ) {      
        echo 'Welcome!';
    } 
    else{?>
                <h2><a href="<?php echo get_permalink(); ?>"><?php the_title();              
     }

    <?php endwhile; endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM