The problem is the shortcode (just like any other shortcode) is displayed when
the_content()
is used to display the post content, and normally themes do this in single template.
In themes, normally, insted of print the content is used the_excerpt()
that strips out html and shortcodes.
Sure you can edit your category archive to use the_content()
instead of the_excerpt()
, but in this case all the post content is printed in the archive.
But it seems to me that you want to use the gallery as excerpt (show the gallery shortcode instead of the standard the_excerpt()
).
Now, your category template (category.php
) should contain something like that (semplified):
while( have_posts() ) : the_posts();
the_title();
the_excerpt();
endwhile;
So you can use 'the_excerpt'
filter to output the shortcode when in galleries archive and when some other codition is reached (e.g. for first X number of posts).
add_filter('the_excerpt', 'maybe_excerpt_gallery');
function maybe_excerpt_gallery($excerpt) {
global $post, $wp_query;
if ( is_category() && in_category('galleries', $post) && $wp_query->current_post < 5 ) {
$gallery = get_the_post_gallery_shortcode($post);
return $gallery ? $gallery : $excerpt;
}
}
Some themes, use something like the_content( 'Continue reading...' )
in archives, in this case add the same filter to the_content
: once the function check if we are on ‘galleries’ category archive, the_content
function in other parts in theme will not be affected.
Before you go searching codex for get_the_post_gallery_shortcode
function, I have to advice you that… this function does not exists in WordPress, but let’s write it:
function get_the_post_gallery_shortcode( $post ) {
if ( empty($post) ) global $post;
if ( empty($post) || ! isset($post->post_content) ) return false;
if (
preg_match_all( "https://wordpress.stackexchange.com/". get_shortcode_regex() .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches ) && in_array( 'gallery', $matches[2] )
) {
foreach ( $matches[2] as $i => $sc ) {
if ( $sc == 'gallery' ) return do_shortcode( $matches[0][$i] );
}
}
return false;
}
I’ve used the get_shortcode_regex to check and extract the shortcode (code for great part stolen from codex) and output it if found.
Now when you visit your galleries category archive, the first 5 posts will have the gallery (if exists) as excerpt .