[resolved] Running the loop inside a PHP function (5 posts)

  1. ixwa
    Posted 4 years ago #

    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?

  2. SpankMarvin
    Posted 4 years ago #

    I think you need to bring your global variables inside the function.

  3. SpankMarvin
    Posted 4 years ago #

    $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.


  4. ixwa
    Posted 4 years ago #

    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?

  5. ixwa
    Posted 4 years ago #

    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).

Topic Closed

This topic has been closed to new replies.

About this Topic