Unfortunately we cannot use attachments for obvious reasons, an image can be attached to one post/page only, it does not have to be attached, at all, in order to be displayed as part of your post/page. Where all tags can be found? In a content of post/page. We can use the_content
hook to have access to those tags. Add this code to functions.php
of your theme (preferably child theme):
function fpw_show_images( $content ) {
global $wp_query;
if ( isset( $wp_query->query_vars['images'] ) ) {
preg_match_all( "/<img[^>]+\>/i", $content, $matches );
$numberOfImages = count( $matches[0] );
if ( 0 == $numberOfImages ) {
$out = '<h3>No images</h3>';
} else {
$out = '<h3>Number of images: ' . $numberOfImages . '</h3>';
$out .= '<table style="width:100%">';
$i = 0;
foreach ( $matches[0] as $img ) {
if ( 0 == $i )
$out .= '<tr>';
$out .= '<td style="width:25%">' . $img . '</td>';
$i++;
if ( 4 == $i ) {
$i = 0;
$out .= '</tr>';
}
}
if ( 0 < $i )
$out .= '</tr>';
$out .= '</table>';
}
return $out;
}
return $content;
}
add_filter( 'the_content', 'fpw_show_images' );
We do not want to add extracted images to the content. It would be redundant, and it will display them to any viewer. Please look at the first if
block of the code above. It will be executed, if post/page url
has the parameter images
added to it:
.../?images
To detect a presence of this parameter we have to define it, first. For this we will create another filter. Add this code to functions.php
of your theme:
function fpw_images_parameter( $qvars ) {
$qvars[] = 'images';
return $qvars;
}
add_filter( 'query_vars', 'fpw_images_parameter' );
If the parameter images
is being used then we will create, and return the new content. The extraction of all <img>
tags is done by one statement of fpw_show_images
function:
preg_match_all( "/<img[^>]+\>/i", $content, $matches );
which will, conveniently, create two dimensional array holding all img
tags. The rest is just a presentation.