Note that there are some explanatory texts on larger screens.

plurals
  1. POLoop through array and return values and HTML
    primarykey
    data
    text
    <p>I store post IDs in an array. I would like to loop through the array and display the IDs within a <code>&lt;div&gt;</code> containing <code>&lt;p&gt;</code> and <code>&lt;ul&gt;</code> tags, but only when at least one ID is in the array. If the array is empty no html can be returned. This implies that I should use some kind of if statement before the loop. Needless to say, my php skills are pretty basic and after two days of trying hard I am getting nowhere. Grateful for help! </p> <p>My code (using Wordpress)</p> <pre><code>$postids = array(); ... $postids [] = $post-&gt;ID; //stores the post IDs in the array </code></pre> <p>Here is an update. I apologize for posting all this code as its quite messy with many things going on. It's the second loop of three (or more). The IDs displayed in a near identical first loop have been passed on. Only those IDs which have not been retrieved by the previous loop are displayed in order not to show any duplicate posts. </p> <p>I have tried to remove all HTML markup and query the $postids with a new WP_Query after but that retrieves all posts I have ever created. I am pretty sure that's the right way to continue although I am obviously doing something wrong.</p> <pre><code>&lt;?php $tags = wp_get_post_tags($post-&gt;ID); if ($tags) { $first_tag = $tags[1]-&gt;term_id; $args=array( 'tag__in' =&gt; array($first_tag), 'post__not_in' =&gt; array($post-&gt;ID), 'showposts'=&gt;5, //Display this number of related posts 'ignore_sticky_posts'=&gt;1 ); $postids = array(); $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { echo '&lt;ul id="relatedposts"&gt;'; while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); if (!in_array($post-&gt;ID, $ids)) {; $postids [] = $post-&gt;ID; ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } $ids[]= $post-&gt;ID; endwhile; } } ?&gt; &lt;/ul&gt; &lt;?php if ($postids){ //$postids has at least one value set echo '&lt;div&gt;Related posts&lt;/div&gt;'; //Outputting the header text. This works! If there are no IDs in the array nothing is shown. }; ?&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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