G
G
grenline1231232021-08-10 15:39:26
WordPress
grenline123123, 2021-08-10 15:39:26

Need to replace an image with another one?

public function check_post_is_has_thumbnail($has_thumbnail, $post, $thumbnail_id)
    {      
        if($has_thumbnail == false ) {
            return set_post_thubmnail($post, 0);
        }
    }


I need to set a picture on a post where there is none, with what function can I replace the picture in a post?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Zolin, 2021-08-10
@artzolin

return set_post_thubmnail( $post, $thumbnail_id );
Of course, all the data $has_thumbnail, $post, $thumbnail_id should fall into this
function

if ( has_post_thumbnail() ) {
  $image = get_the_post_thumbnail_url( get_the_ID(), 'large' );
} else {
  $image = get_stylesheet_directory_uri() . '/assets/img/default-cover.jpg';
}

K
kapitansen, 2021-08-10
@kapitansen

An example of checking for thumbnail existence:

<?php 
//должно находится внутри цикла
if( has_post_thumbnail() ) {
  the_post_thumbnail();
}
else {
  echo '<img src="'.get_bloginfo("template_url").'/images/img-default.png" />';
}
?>

If not inside the loop, then like this: Next, you can 1) use the default image 2) or take the first image from the list of post images:<?php if has_post_thumbnail( $post_id ) { } ?>
$media = get_attached_media( 'image', 2018 );
$media = array_shift( $media );

// ссылка на картинку
$image_url = $media->guid;

// выведем картинку в браузере
echo '<img src="'. $image_url .'" />';

In both cases, the thumbnail is set using set_post_thumbnail( $post, $thumbnail_id );
  1. $post(number/object) (required) - ID of the post to set the thumbnail to. You can pass a record object.
  2. $thumbnail_id(number) (required) - ID of the attachment to attach.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question