Skip to content

Tyssen Design — Brisbane Tyssen Design logo

[email protected] (07) 3300 3303

Calling a Wordpress loop from inside a Wordpress loop

By /

Recently I came across a sitution whereby I wanted to call a list of Wordpress posts from inside the body of another post, i.e., not coding it into a template, but embedding into the body of the post itself. Not a big drama, I thought to myself: I already have the exec-php plugin installed to enable the execution of PHP from within Wordpress posts, so all I needed to do was call the Wordpress loop from the point inside the post where I wanted my list of links to appear, e.g.:


<ul>
<?php $my_query = new WP_Query('cat=XX');
  while ($my_query->have_posts()) : $my_query->the_post(); ?>
	<li><a href="<php the_permalink(); ?>"><php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
								

The code above follows a similar format to that as described in the Wordpress Codex for working with multiple loops.

This worked fine for outputting the title of the post and its permalink. The problem was that I then wanted to the replace the permalink to a link to an external site that was attached to the posts using a custom field.


<ul>
<?php $my_query = new WP_Query('cat=XX');
  while ($my_query->have_posts()) : $my_query->the_post();
	$link = get_post_meta($post->ID, 'site-url', true); ?>
	<li><a href="http://<php echo $link; ?>"><php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
								

Unfortunately, this wouldn’t work; no link was output. But after some help from people on the WordPress Support forum, I found that using get_posts instead of WP_Query did the trick:


<ul>
<?php global $post;
	$my_query = get_posts('numberposts=100&cat=XX');
  // numberposts is required with get_posts so I just set it to a large number
	foreach($my_query as $post) :
		setup_postdata($post);
		$link = get_post_meta($post->ID, 'site-url', true); ?>
		<li><a href="<php echo $link; ?>"><php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
								

Problem solved! 😊

Like to say hello? Give us a call on (07) 3300 3303, send us an email to enquiries@tyssendesign.com.au, or a message by filling in the form below.