I am trying to output a bunch of images after each post but I can only output one.
add_filter( 'the_content', 'image_posts' );
function image_posts( $content ) {
global $post;
if ( ! $post instanceof WP_Post ) {
return $content;
}
$all_images = get_images(); // array of images
switch ( $post->post_type ) {
case 'page':
// return $content; // this only return content
foreach ($all_images as $image){
echo '<img src="'.$image.'" />';
}
// return $content; // this returns all images on top of the content
default:
return $content;
}
}
and if I modify the loop to this:
foreach ($all_images as $image){
return content . '<img src="'.$image.'" />';
}
I only get the content with one image. How can I output all the images after the content?
Assuming that we hit the switch statement and the page case and assuming that $all_images does indeed contain image urls:
In your switch statement, try storing all the images in a variable first and then concatenate them with $content
in your return statement.
add_filter( 'the_content', 'image_posts' );
function image_posts( $content ) {
global $post;
if ( ! $post instanceof WP_Post ) {
return $content; // If this is true, we return $content and the rest of the code doesn't run.
}
$all_images = get_images(); // array of images
$images = ""; // We'll store all our image tag strings here here. Assuming, of course, we make it to this section of code.
switch ( $post->post_type ) {
case 'page':
foreach ($all_images as $image){
$images .= '<img src="'.$image.'" />';
}
return $content . $images; // Concatenate $images after $content
default:
return $content;
}
}
Part of the problem you are likely running into is that once you return $content
no other code in the filter will run.
For added bonus, you can add a class to your image tag or wrap it with a div or some other wrapper to do some css magic later 🙂
A point of clarification on WordPress filters and actions: WP filters and actions work best with return
statements in order to function properly. While you could echo
something, that echo
actually takes place at the point of code execution. This means that you often end up with your code showing up at the head of the page.