So the answer depends on what you mean by "when the category is 429". This could mean either:
- You are currently viewing the archive for category 429, and want this to be added to any posts that are listed.
- You are currently viewing the blog, date archive, or search results, and want to add this text to any individual post that belongs to category 429.
These are different things, and the solution is different for each.
For #1 you want to use is_category()
. This will tell you if the current page being viewed is the archive for category 429, and will apply the filter to all excerpts displayed on this page:
function mywiki_trim_excerpt( $excerpt ) {
if ( is_category( 429 ) ) {
$excerpt = substr( $excerpt, 0, -10 );
$excerpt = $excerpt . '...<a class="bigger" href="' . get_permalink() . '" title="' . __( 'read more...', 'mywiki' ) . '">' . __( 'Read more', 'mywiki' ) . '</a>';
}
return $excerpt;
}
add_filter( 'get_the_excerpt', 'mywiki_trim_excerpt' );
For #2 it's slightly more complicated, because you need to check the category against the post the excerpt is for. You can do this by accepting 2 arguments in the filter (set the 4th argument of add_filter()
to 2
), and using the 2nd argument ($post
, the current post) with has_category()
:
function mywiki_trim_excerpt( $excerpt, $post ) {
if ( has_category( 429, $post ) ) {
$excerpt = substr( $excerpt, 0, -10 );
$excerpt = $excerpt . '...<a class="bigger" href="' . get_permalink() . '" title="' . __( 'read more...', 'mywiki' ) . '">' . __( 'Read more', 'mywiki' ) . '</a>';
}
return $excerpt;
}
add_filter( 'get_the_excerpt', 'mywiki_trim_excerpt', 10, 2 );
Technically has_category()
will work without passing $post
. If you leave that out then it will check the category of the 'current post'. 99% of the time this is the same as the post that the excerpt is for, but in rare edge cases the 'current' post might not be the same post as the post who's excerpt is being filtered. By using the $post
value passed to the filter we can guarantee that the post we are checking the category of is the same post that the excerpt is for.