Categories
WordPress

Useful WordPress Snippets

Automatically Wrap Feature Images In The Permalink

Some themes, such as TwentyTwenty, don’t wrap feature images in the permalink. However, since this is such a standard web idiom, you might want to consider implementing it in your own themes or child theme.

The following code will accomplish that task, as long as you are not on a single view of a page, since that would create a link to the user is already on.

How this works: the code uses a filter hook. These allow you to intercept content before it is output to the screen.

Here we are taking the HTML that would normally be generated by a call to the_post_thumbnail(), testing to see if we’re not on a single post or page ( is_singular() ), then wrapping that HTML inside an <a> tag with href and title attributes being added with calls to get_permalink() and get_post_field, respectively.

The else part of the condition will apply if we are on a single post or pageā€”in which case, we return the html produced by the_post_thumbnail() unmodified.

Be sure to change the word THEMENAME to your own themename.

// FILTER POST THUMBNAIL HTML so that it is wrapped in a 
// link as long as the page is a SINGLE view.

function THEMENAME_post_thumbnail( $html, $post_id, $post_image_id ) {
    if ( !is_singular() ) :
        $html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_post_field( 'post_title', $post_id ) ) . '">' . $html . '</a>';
        return $html;
    else :
        return $html;
    endif;
    }

add_filter( 'post_thumbnail_html', 'THEMENAME_post_thumbnail', 10, 3 );

Automatically Remove Archive Title Prefixes

When the user clicks on a category, tag, date, author or other archive links, they are taken to an archive page that typically will have a prefix in the page title heading. An example could be Category: Art, for example.

If you are using a specific category.php file to output categories, you can remove that prefix by using single_cat_title( ).

However, if you are using the more generic archive.php to generate all your archives (categories, tags, dates, author, etc), you need to use the more general the_archive_title(). This function includes the prefix category:, tag:, author:, etc.

To remove that prefix from archive page titles, we can again use a filter as in the code below.

Once again, be sure to replace THEMENAME with your theme’s name.

function THEMENAME_archive_title( $title ) {
  if ( is_category() ) {
    $title = single_cat_title( '', false );
  } 
  elseif ( is_tag() ) {
     $title = single_tag_title( '', false );
  } 
  elseif ( is_author() ) {
     $title =  get_the_author();
  } 
  elseif ( is_post_type_archive() ) {
      $title = post_type_archive_title( '', false );
   } 

   return $title;
}

add_filter( 'get_the_archive_title', 'THEMENAME_archive_title' );