简体   繁体   中英

Foreach loop not looping through

I have a foreach loop which is only returning the title of the latest post. For example, I have the post test as the latest post in products and in the loop defined below, when doing var_dump , it only dumps the title for the latest post called "test".

Why is this?

Approach:

<?php
    $args = array(
        'post_type'        => 'products',
        'post_parent'       => 0,
        'posts_per_page'  => 15,
    );
    $products = get_posts( $args );

    if ($products){
      foreach ($products as $product) : setup_postdata( $product ); 
        var_dump(get_the_title());
      endforeach;
      wp_reset_postdata();

    }
?>
      foreach ($products as &$product) : setup_postdata( $product ); 

Please try this in your foreach loop.

Use this one

if ($products){
      foreach ($products as $product) : setup_postdata( $product ); 
        echo get_the_title($product->ID));
       // or echo $product->post_title;
      endforeach;
      wp_reset_postdata();

    }

It's strange but when you're wanting to use template tags along with setup_postdata() you need to use the global $post variable. setup_postdata() doesn't actually set that variable it sets some related global variables and runs the the_post action. You can see what happens here

To do what you want to do with out passing ids etc for every template function call you would need to setup your loop like this.

global $post;
foreach ( $products as $post ) {
    setup_postdata( $post );
    // Your code here.
}
wp_reset_postdata();// Reset the global $post variable and re-setup postdata.

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