X

Establecer automáticamente la imagen destacada

Snippets by IsItWP

A veces no tienes una imagen destacada para una entrada y quieres que la primera imagen de tu artículo se utilice como imagen destacada automáticamente.

Instrucciones: Añade el siguiente código al archivo functions.php de tu tema de WordPress para establecer automáticamente la imagen destacada de tus entradas. Si añades una imagen destacada a una entrada, entonces anulará este código y mostrará tu imagen destacada en su lugar.


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');

También puede disfrutar de la eliminación de la imagen destacada meta caja.

Comentarios   Deja una respuesta

  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 !

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!