How to add classes to images based on their categories?

This should hopefully do the trick: /** * Append the image categories to the current image class. * * @see http://wordpress.stackexchange.com/a/156576/26350 */ add_filter( ‘get_image_tag_class’, function( $class, $id, $align, $size ) { foreach( (array) get_the_category( $id ) as $cat ) { $class .= ‘ category-‘ . $cat->slug; } return $class; } , 10, 4 ); Testing … Read more

How to wrap WordPress image captions inside H2, H3 tags?

You can hook into the filter img_caption_shortcode and replace the whole captioned image. Here I’ve copied the caption shortcode function from WP4.5, left the version used if your theme declares HTML5 support as it is (using figcaption) and modified the non-HTML5 version to use h2. function wpse_233354_img_caption_shortcode( $empty, $attr, $content = null ) { // … Read more

Insert an image into a post by API

You can set the uploaded image as the post thumbnail via, update_post_meta($post_id,’_thumbnail_id’,$attach_id); Example… if ($_FILES) { foreach ($_FILES as $file => $array) { if ($_FILES[$file][‘error’] !== UPLOAD_ERR_OK) { return “upload error : ” . $_FILES[$file][‘error’]; } $attach_id = media_handle_upload( $file, $post_id ); } } update_post_meta($post_id,’_thumbnail_id’,$attach_id); If you are uploading an array of images, then you … Read more

Which action hook can I use when a featured image has been selected

The set_post_thumbnail function uses the metadata functions to set the featured image. You have two actions to hook into that process: EDIT: The action hooks are now defined different Thanks @dalbaeb! update_postmeta, before the data is written into the database. Previously update_post_meta updated_postmeta, after the data is written into the database. Previously updated_post_meta SECOND EDIT: … Read more

Change wp_get_attachment_image attributes (src and srcset) on specific custom field

You won’t be really able to tell which context the image is being used in in the wp_get_attachment_image_attributes filter, but you can pass custom attributes to wp_get_attachment_image() in the template directly with the 4th argument. Then you can use wp_get_attachment_image_url() and wp_get_attachment_image_srcset() to get the values for those attributes: $image = get_field(‘image’); $size=”gallery”; echo wp_get_attachment_image( … Read more

Showing a placeholder/default img, if no featured image is set

Misspelling of thumbnail (thumnail) in the if statement. Also get_the_post_thumbnail does echo the thumbnail, but just returns the html. You need to echo it. Also, for checking if a post has a thumbnail, you can use has_post_thumbnail. if ( has_post_thumbnail($r->ID)) { echo get_the_post_thumbnail($r->ID, array(50,50)); }else{ echo ‘<img src=”https://wordpress.stackexchange.com/questions/44208/image_url”/>’; }