Home › Forums › Front-end Issues › Problem with repeated objects assigned to posts › Reply To: Problem with repeated objects assigned to posts
okay, whether or not you are doing another loop, there is a query that happens before yours. Any time you do a reset WP will reset to this query and not to the previous query and post whatever that may be. In essence what you have here is a loop that’s 3 deep of posts.
I’ve boiled down your code here to the important bits.
<?php
// main WP query happens before here
// Call it: Query #1
// your query: Query #2
$args = array(
'post_type' => 'kanaly_premium',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
);
$fullnewsloop = new WP_Query($args);
if ($fullnewsloop->have_posts()):
while($fullnewsloop->have_posts()): $fullnewsloop->the_post();
if( have_rows('programy_lista') ):
while ( have_rows('programy_lista') ) : the_row();
$post_objects = get_sub_field('kanal');
if( $post_objects ):
foreach( $post_objects as $post):
setup_postdata($post);
endforeach;
// this resets WP to main query: Query #1
// and not to your query: Query #2
wp_reset_postdata();
endif;
endwhile;
endif;
endwhile;
endif;
?>
What you need to do instead of resetting is to store your post and then restore it after the your loop over $post_objects
<?php
// main WP query happens before here
// Call it: Query #1
// your query: Query #2
$args = array(
'post_type' => 'kanaly_premium',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
);
$fullnewsloop = new WP_Query($args);
if ($fullnewsloop->have_posts()):
while($fullnewsloop->have_posts()): $fullnewsloop->the_post();
if( have_rows('programy_lista') ):
// temporarily store post from Query #2
$post_hold = $post;
while ( have_rows('programy_lista') ) : the_row();
$post_objects = get_sub_field('kanal');
if( $post_objects ):
foreach( $post_objects as $post):
setup_postdata($post);
endforeach;
endif;
endwhile;
// restore post from Query #2
$post = $post_hold;
endif;
endwhile;
endif;
?>
However, after saying all of that, there isn’t any reason for your second query in the first place. Since this template is archive-kanaly_premium.php
, that query is already being done by WP. What you should be doing is using a pre_get_posts filter https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts to modify the post_per_page parameter of the main query. If you did this then your loops and reset would work correctly.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.