Guest User

Change Image Alt Attribute to Post Title / Post Category

a guest
Dec 1st, 2015
107
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Register callback function for post_thumbnail_html filter hook */
  2. add_filter( 'the_content', 'post_image_alt_change', 10, 5 );
  3.  
  4. /* Function which will replace alt atribute to post title */
  5. function post_image_alt_change( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
  6.  
  7.     $post_title = get_the_title();
  8.     $postcategories = get_the_category();
  9.         $post_category='';
  10.         if ($postcategories) {
  11.           foreach($postcategories as $category) {
  12.             $post_category .= $category->name .' ';
  13.           }
  14.         }
  15.     $post_alt = $post_title . ' ' . $post_category;
  16.     $html = preg_replace( '/(alt=")(.*?)(")/i', '$1'.esc_attr( $post_alt ).'$3', $html );
  17.     return $html;
  18. }
RAW Paste Data