Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Return Loop/Query WordPress

  • SOLVED

I am trying to make some custom emails that will send out the entire output of a query, but I am not sure how to return an entire loop.

$query = new WP_Query( array(
//Stuff
));

$loop = while ( $query->have_posts() ): $query->the_post( );

setup_postdata($events);
$var1 = get_post_meta();
return 'Stuff about each queried post'.$var1;

endwhile; wp_reset_query();

wp_mail($customer, $subject, $loop);

Is there someway to return an entire loop in this way?

Answers (2)

2013-03-08

Kailey Lampert answers:

try this

$loop = '';
$query = new WP_Query( array(
//Stuff
));

while ( $query->have_posts() ): $query->the_post( );

setup_postdata($events);
$var1 = get_post_meta();
$loop .= 'Stuff about each queried post'.$var1;

endwhile; wp_reset_postdata();

wp_mail($customer, $subject, $loop);


Kailey Lampert comments:

In case you are using functions like the_title() or the_content() which echo instead of return, you can either change them to get_the_title() and get_the_content() or use output buffering


$query = new WP_Query( array(
//Stuff
));

ob_start();

while ( $query->have_posts() ): $query->the_post( );

setup_postdata($events);

$var1 = get_post_meta();

echo 'Stuff about each queried post'.$var1;

endwhile; wp_reset_postdata();

$loop = ob_get_contents();
ob_end_clean();

wp_mail($customer, $subject, $loop);


Kyle comments:

Perfect :) thank you

2013-03-08

Christianto answers:

Do you need to save entire query object and email it?

You could [[LINK href="http://php.net/serialize"]]serialize[[/LINK]] $loop so it become string, for example:
$query = new WP_Query( array(
//Stuff
));
$my_string_query = serialize($query);

wp_mail($customer, $subject, $my_string_query);


and if you need to convert it to object again, use unserialize()