How can I save the HTML output of the WP_Query function below as a variable?
I.e., save the example generated HTML <a href="https://example.com/my-post/">Example.com</a> as a variable, i.e. $saved_html
The reason I want to save the output as a variable is that I want to be able to save the variable to a custom field, but that's another step.
This is a very old answer that gave me some clues, but is not enough help: WP_Query results stored in variables
<?php $args = array(
'date_query' => array(
'post_parent' => '',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'column' => 'post_date',
'before' => '1 year ago',
),
'posts_per_page' => 1,
);
$query = new WP_Query( $args ); ?>
<?php while($query->have_posts()) : $query->the_post(); ?>
<a href="<?php the_permalink() ?>">
<?php the_title(); ?></a>
<?php endwhile; wp_reset_postdata();?>
// save as variable?
// $saved_html = ??
Here's an attempt using output buffering, which doesn't work:
function echoquery() {
ob_start();
$args = array(
// simpified for example
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'posts_per_page' => 1,
);
$query = new WP_Query( $args );
while($query->have_posts()) : $query->the_post();
the_permalink();
echo '<br />';
the_title();
endwhile;
$theoutput = ob_get_contents();
ob_end_clean();
return $theoutput;
echo $theoutput;
}
Edit 1/8/25 This works:
$args = array(
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'posts_per_page' => 1,
);
$query = new WP_Query( $args );
ob_start();
while($query->have_posts()) : $query->the_post();
the_permalink(); echo'<br />';
the_title();
endwhile; wp_reset_postdata();
$out = ob_get_clean();
echo $out;