Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding Duplicate item in loop
    text
    copied!<p>I wrote a query to show related posts in Wordpress, A brief explanation: First it checks what categories current post belongs to, then puts "slug" name of that categories inside an array ("$cats") Then using foreach, I query the posts with same taxonomies. This code works great except for when current post belongs to more than one category and there is another post which belongs to these categories too, in this situation the other post gets displayed twice or even more depending on how many categories they share, </p> <p><strong>So the question is, How do I check if a post is repeating and how to prevent it?</strong> Code:</p> <pre><code>&lt;?php $terms = get_the_terms( $currentid, 'taxonomy' ); $cats = array_map(function($a){ return $a-&gt;slug; }, $terms); foreach ($cats as $cat) { $args=array( 'taxonomy' =&gt; $cat , 'post_type' =&gt; 'apps', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 4, ); global $wp_query; $wp_query = new WP_Query($args); while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); if($currentid !== get_the_ID()){ ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;?php if ( has_post_thumbnail() ){ $appfetured = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() )); $appfeturedimage = $appfetured[0]; }else{ $appfeturedimage = '../img/defaultappicon.png'; } ?&gt; &lt;img class="appfeatured" src="&lt;?php echo $appfeturedimage; ?&gt;" alt="&lt;?php the_title_attribute(); ?&gt;" /&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php } endwhile; wp_reset_query(); // Restore global post data stomped by the_post(). }//end foreach ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload