X

Definir automaticamente a imagem em destaque

Snippets by IsItWP

Às vezes, você não tem uma imagem em destaque para uma publicação e deseja que a primeira imagem do seu artigo seja usada como imagem em destaque automaticamente.

Instruções: Adicione o código a seguir ao arquivo functions.php do seu tema do WordPress para definir automaticamente a imagem em destaque para suas publicações. Se você adicionar uma imagem em destaque a uma postagem, ela substituirá esse código e exibirá sua imagem em destaque.


function autoset_featured() {
    global $post;
    $already_has_thumb = has_post_thumbnail($post->ID);
        if (!$already_has_thumb)  {
        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
            if ($attached_image) {
                foreach ($attached_image as $attachment_id => $attachment) {
                    set_post_thumbnail($post->ID, $attachment_id);
                }
            }
        }
}
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

Você também pode gostar de remover a meta box da imagem em destaque.

Comentários   Deixe uma resposta

  1. One question, and if I need to exclude some pages? what could I do… thank you very much

  2. Why does it only work when uploading a new image and not when choosing one from the library even though it is not used in any other post?

    1. It uses the attachments, which will get the image based on the image being assigned, or attached, to the post.

  3. Thanks a lot, this is working like a charm <3

  4. I am not familiar with php. I am using astra theme. After adding this code, a random image from the post is set as the featured image instead of the first image. Can you fix this?

  5. So, first off thank you for this piece of code. As a photographer, I was running into a slightly different problem in that I needed the attachment page to have more features. After setting up the attachment page to show thumbnails, I modified your code to automatically set the attachment page thumbnail to be the attachment image. This was a real pain, so here is the code for anyone else who might be looking to do the same thing.

    function set_attachment_thumbnail() {
    global $post;
    if( get_post_type($post) === ‘attachment’) {
    $attachment_thumb = has_post_thumbnail($post->ID);
    if( !$attachment_thumb ) {
    set_post_thumbnail($post->ID, $post->ID );
    }
    }
    }
    … same as above with the function name changed.

    I hope this helps someone else. 🙂

    1. Thank you for sharing your snippet with us, Chris 🙂

  6. I’ve just tried applying this code – thanks for sharing – but find right off the bat that it’s only finding any image about 2/3rd of the time, and it’s also not reliably the first image from the post. Any thoughts?

  7. When I put the code at the end of functions.php, it shows the code at the top of my website instead. Do you know why or how to fix it?

    1. Chances are the code was added incorrectly. I think you should check out our article on adding the code snippets properly.

      You might also want to check out troubleshooting WordPress errors and fixing most common WordPress errors.

  8. Hi,
    it works perfectly for wordpress posts but not with custom posttypes.
    Do you have any idea to make it work on any custom posttype?

    All the best
    Sebastian

  9. Hello

    I tried this code on Elegantthemes Extra theme and it is not working !

Adicionar um comentário

Ficamos felizes por você ter optado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossa política de privacidade, e todos os links são nofollow. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.

WordPress Launch Checklist

A lista de verificação definitiva para o lançamento do WordPress

Compilamos todos os itens essenciais da lista de verificação para o lançamento de seu próximo site WordPress em um ebook prático.
Sim, envie-me o livro eletrônico gratuito grátis!