WordPress custom post loop – echo variable once

I have a loop that gets all the posts that are “custom_post”. It works perfectly – apart from that when I echo a variable it duplicates the variable when there are more than one post.

Its hard to explain – but basically if I have one post it works perfectly. I get a Div with the class name that is assigned to that custom post.

When I add another post – again that works, but displays two divs with the second post. I would imagine that it has something to do with echo $variable in the loop.

Any ideas? Thanks


$ids = array();
$args = array( 'post_type' => 'custom_post');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
array_push( $ids, get_the_ID() );
foreach (array_unique($ids) as $key => $value) {

$variable .='<div class"'.$classname.;">;
echo $variable;


Read more here: WordPress custom post loop – echo variable once

Leave a Reply

Your email address will not be published. Required fields are marked *