Support » Fixing WordPress » Running the loop inside a PHP function

  • Resolved ixwa


    I’ve seen various questions asked in this vein but nothing definitively about just having the loop accessible from a function. I have a very good reason to want the loop in a function–essentially as a lookup from a posted form. Simple.

    This is what I have:

    global $post;
    global $the_query;
    function myFunction(){
    $args = array(
    	'category_name' => 'my-category-name',
    	'orderby' => 'title',
    	'order' => 'ASC',
    	'posts_per_page' => '-1'
    $the_query = new WP_Query( $args );
    	//Show posts
    	if ( $the_query->have_posts() ) {
    		while ( $the_query->have_posts() ) : $the_query->the_post();
    		$myPosts .= get_post_meta($post->ID, 'mycustomfieldname', true);
    return $myPosts;

    This is before I’ve even added any vars to the function call; all I get right now is one line of all the titles of each record (seemingly concatenated) and then a bunch of empty lines.

    Do I have a glaring syntax error or am I going about the function all wrong?

Viewing 4 replies - 1 through 4 (of 4 total)
  • I think you need to bring your global variables inside the function.

    $the_query is also not a valid global variable. Try $wp_query instead. That said, unless you are trying to override the default query, there’s no reason to bring in the global variables at all.


    OK, thanks. Here’s what I learned…although I still have one remaining issue, see below. Hopefully this helps someone.

    My $wp_query was originally called $the_query…not sure why (I think I had copied it), but I changed this to use “wp”. $post must be global WITHIN the function. Not necessary to make $wp_query global.


    the_title() does not appear to work inside the loop. All it does is print out every post title in a single line, without spaces, and then proceeds to complete the loop normally (without titles). I have no idea why; everything else in the loop works. I tried instead referencing the post title using $post->name but this didn’t work.

    Any ideas? Any other way to reference the title of a post inside a loop?

    Solved. The answer is to use the_title(”,”,false) in this loop as the_title() by itself just spits out all post titles at once, for some reason.

    FYI: get_the_title() did not work in this function loop.

    For those wanting to understand the setup: I’m running this function in a Page that calls the posts from a specific category (so yes, in some experiments I was getting the Page’s title, not the individual Post titles).

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Running the loop inside a PHP function’ is closed to new replies.