0

I am building nested loop query.I have meta box that capture post id (sorter and repeater).so far my code

while ( have_posts() ) : the_post();
    ?>
<div id="<?php echo $post->post_name; ?>">
    <h1><?php the_title(); ?></h1>
    <?php
    the_content();


    $urls = get_post_meta( get_the_ID(), 'mymeta_url_group', false );

    foreach ( $urls as $url ) {
        //echo $url["mymeta_url"];
        foreach ( $url['mymeta_slider'] as $u ) {
            //echo "$u<br> "; shows post id like 67 68 56 etc

            $my_query = new WP_Query( array( 'post_type' => 'slider', 'p' => "'.$u  .'" ) );
            if ( $my_query->have_posts() ) {
                while ( $my_query->have_posts() ) {
                    $my_query->the_post();
                    the_title();
                }
            }
            wp_reset_postdata();
        }

but my output result got duplicated.that is post type slider has 3 posts query shows 6 posts duplicating twice.

  • 1
    it helps to properly indent your code to make it readable. – Milo Jun 27 '14 at 20:38
0

Do I see that right, that you are doing a WP_Query for every single post, you want to retrieve? That is highly inefficient, you can use the post__in argument supplied by WP_Query. (http://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters)

foreach ( $urls as $url ) {
    //echo $url["mymeta_url"];
    foreach ( $url['mymeta_slider'] as $u ) {
        //echo "$u<br> "; shows post id like 67 68 56 etc
        $posts_to_recive[] = $u;
    }
    $my_query = new WP_Query( array( 'post_type' => 'slider', 'post__in' => $posts_to_recive ) );

    if ( $my_query->have_posts() ) {
       while ( $my_query->have_posts() ) {
            $my_query->the_post();
            the_title();
       }
    }

    wp_reset_postdata();
}

And yet this is highly inefficient. Keep the amount of WP_Querys as low as possible.

  • Thank you for your answer.Since the post ids are sortable but query did not do that.The result is the latest post first but I am using sorting functionality. – ashraf Jun 27 '14 at 21:31
  • You can use the "post__in" value with the orderby argument, to enforce sorting, as it is in the $posts_to_recive array. That actually works pretty well, I use that all the time. – Hendrik Luehrsen Jun 27 '14 at 21:37
  • Well didn't work though – ashraf Jun 27 '14 at 22:28

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.