Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Så här ställer du in en standardfallback-image för inläggsminiatyrer i WordPress

Featured images är viktiga för att göra dina WordPress inlägg visuellt tilltalande och engagerande. De fångar läsarnas ögon och hjälper your content att sticka ut.

Vi vet dock att det kan vara en utmaning att skapa unika images för varje post, särskilt om du runar en upptagen site som vår.

Det är där det blir praktiskt att ställa in en standardinställning för en fallback-image för inläggsminiatyrer i WordPress. Detta säkerställer att dina inlägg alltid har en image, vilket upprätthåller ett professionellt utseende på hela din site även när du inte har tid att skapa en custom featured image.

I den här artikeln kommer vi att visa you hur du ställer in en standard fallback image för dina WordPress inläggsminiatyrer.

How to Set a Default Fallback Image for WordPress Post Thumbnails

Varför ställa in en standard featured image i WordPress?

I WordPress är featured images (eller inläggsminiatyrer) mycket viktiga visuella element som representerar ditt content.

De fångar uppmärksamhet på din blogg, i archives och på social media och ger läsarna en snabb preview av vad de kan förvänta sig.

Example of featured images in WPBeginner

Men vad händer när du inte har en unik image för varje post? Det är där inställningen av en standardinställning för WordPress featured image kommer väl till pass.

Den här lösningen är perfekt för välbesökta webbplatser med nyheter, äldre content utan images eller för att upprätthålla ett konsekvent varumärkesutseende på din website i WordPress.

Utan en standard image kan din site se konstig ut.

Posts utan images kan sticka ut på ett dåligt sätt och få din site att se rörig ut. Detta kan förvirra läsarna och få din site att verka mindre professionell.

Example of a missing featured image

Med det i åtanke, låt oss titta på 3 enkla sätt att ställa in en standard featured image för dina WordPress blogginlägg. Du kan använda snabblänkarna under för att hoppa till din önskade metod:

Denna metod är perfekt för Beginnare eftersom den inte är obligatorisk för någon kodning. Vi kommer att använda Default Featured Image plugin för att visa en standard fallback WordPress inlägg thumbnail.

Installera och aktivera först pluginet Default Featured Image på din WordPress site. Om du ej är säker på hur du gör detta, kontrollera vår guide för nybörjare om hur du installerar tillägg till WordPress.

När du är aktiverad går du till Settings ” Media i din WordPress dashboard. Du kommer att se ett new alternativ för att ”Select default featured image”. Click på denna knapp för att öppna ditt mediabibliotek.

Här kan du välja en befintlig image eller uploada en new image att använda som din fallback för posts.

Uploading a featured image to the Default Featured Image plugin

När du har valt din bild kommer du att notera alternativ för att ställa in maximala dimensioner för dina standard featured image-storlekar.

Du kan justera dessa om du vill eller lämna dem som de är om du är nöjd med standardinställningarna.

Setting the dimensions for the default featured image

När du är klar rullar du ner och clickar på ”Save Changes”. För att se dina ändringar i action, preview din website på både mobil och desktop.

Nu, när du skapar ett inlägg utan att ställa in en featured image, kommer din WordPress webbplats automatiskt att använda denna reservbild som inläggsminiatyr.

Example of setting a default featured image using a plugin

Om du är bekväm med kodning eller ej föredrar att använda det andra pluginet, kan du ställa in en reservbild för inläggsminiatyr manuellt.

Vi kommer att använda WPCode plugin för att lägga till denna funktionalitet säkert och enkelt.

Först installerar och aktiverar du WPCode plugin på din WordPress site. Om du behöver hjälp kan du kontrollera vår guide om hur du installerar tillägg till WordPress.

När du är aktiverad går du till Code Snippets ” + Add Snippet i din WordPress dashboard. Välj ”Add Your Custom Code (New Snippet)” och klicka på ”+ Add Custom Snippet”.

Adding a new custom code snippet in WPCode

Namnge nu ditt snippet något som gillar ”Set Fallback Image for Posts Without Featured Images”.

Ändra också Code Type till ”PHP Snippet”.

Setting a default fallback image with WPCode

Klistra sedan in den kod som providern tillhandahåller i boxen Code Preview:

function set_default_featured_image( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
    if ( empty( $post_thumbnail_id ) ) {
        // Replace 'http://example.com/path/to/your/default-image.jpg' with the URL of your default image.
        $default_image_url = 'http://example.com/path/to/your/default-image.jpg';
        $html = '<img src="' . esc_url( $default_image_url ) . '" class="wp-post-image" alt="Default Image"/>';
    }
    return $html;
}
add_filter( 'post_thumbnail_html', 'set_default_featured_image', 10, 5 );

function set_default_featured_image_url( $url, $post_id ) {
    if ( empty( get_post_thumbnail_id( $post_id ) ) ) {
        // Replace 'http://example.com/path/to/your/default-image.jpg' with the URL of your default image.
        $url = 'http://example.com/path/to/your/default-image.jpg';
    }
    return $url;
}
add_filter( 'default_post_thumbnail_url', 'set_default_featured_image_url', 10, 2 );

Den här koden gör två huvudsakliga saker. För det första ställer den in en standardbild som ska visas när ett inlägg inte har en featured image.

För det andra säkerställer det att denna standard featured image används konsekvent på hela din site, inklusive på webbplatser där endast bildens URL behövs.

Du måste ersätta URL:en till exempelbilden i koden med URL:en till din valda standard image (se de markerade delarna av kodexemplet).

Om du ej är säker på hur du får fram URL:en till din image, kontrollera vår artikel om hur du får fram URL:en till images som du uploadar i WordPress.

När du har klistrat in koden rullar du ner till sektionen Insertion. Behåll metoden för insert som ”Auto Insert” och ändra Location till ”Front-end Only”.

Slutligen togglar du knappen högst upp till höger till ”Active” och klickar på ”Save Snippet”.

Choosing Frontend Only as the code insertion location in WPCode

När du nu viewar din blogg homepage, bör du se din standard image appearing for any posts that don’t have a featured image set.

Metod 3: Ställ in den första bilden som inläggsminiatyr med kod

Den här metoden använder automatiskt den första imagen i your post som thumbnail. Det är ett bra alternativ om du alltid inkluderar bilder i dina inlägg och vill spara tid genom att ej ställa in featured images manuellt.

Vi kommer att använda WPCode plugin igen för detta. Om du inte har installerat det ännu, följ vår guide för nybörjare om hur du installerar WordPress tillägg.

När du har aktiverat WPCode, gå till Code Snippets ” + Add Snippet i din WordPress dashboard. Välj ”Add Your Custom Code (New Snippet)” och klicka på ”+ Add Custom Snippet”.

I detta skede kan du namnge ditt snippet något som gillar ”Använd första bilden i inlägget som featured image”.

Ändra sedan Code Type till ”PHP Snippet”.

Custom code for using first image as featured image, inserted using WPCode

Klistra sedan in följande kod i boxen Code Preview:

// Function to get the first image from the post content
function get_first_image_from_content( $post_content ) {
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($post_content);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);
    $image_nodes = $xpath->query("//img");

    if ( $image_nodes->length > 0 ) {
        $image_url = $image_nodes->item(0)->getAttribute('src');
        return $image_url;
    }

    return false;
}

// Function to set the first image as the featured image
function set_first_image_as_featured( $post_id ) {
    if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
        return;
    }

    if ( has_post_thumbnail( $post_id ) ) {
        return;
    }

    $post = get_post( $post_id );
    if ( ! $post ) {
        return;
    }

    $image_url = get_first_image_from_content( $post->post_content );

    if ( $image_url ) {
        $upload_dir = wp_upload_dir();
        if ( false !== strpos( $image_url, $upload_dir['baseurl'] ) ) {
            $attachment_id = attachment_url_to_postid( $image_url );
            if ( $attachment_id ) {
                set_post_thumbnail( $post_id, $attachment_id );
            }
        }
    }
}
add_action( 'save_post', 'set_first_image_as_featured' );

// Function to filter the post thumbnail HTML
function filter_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
    if ( ! $html ) {
        $post = get_post( $post_id );
        if ( $post ) {
            $image_url = get_first_image_from_content( $post->post_content );
            if ( $image_url ) {
                $html = '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( get_the_title( $post_id ) ) . '" class="frame" />';
            }
        }
    }
    return $html;
}
add_filter( 'post_thumbnail_html', 'filter_post_thumbnail_html', 10, 5 );

Imagely, den här koden letar efter den första imagen i ditt post content. Om den hittar en bild och det inte finns någon featured image inställd, gör den den första bilden till den featured image.

Den här koden fungerar automatiskt när du sparar eller updaterar en post. Den ställer bara in en new featured image om ingen redan är inställd, så den åsidosätter inte några featured images som du ställer in manuellt.

När du är klar rullar du ner till sektionen Insertion. Se till att hålla infogningsmetoden som ”Auto Insert” och platsen som ”Run Everywhere”.

Till sist togglar du knappen högst upp till höger till ”Active” och klickar på ”Save Snippet”.

Applying the code snippet everywhere using WPCode

När du nu viewar din blogginläggs homepage bör du se att den första imagen från varje post används som inläggsminiatyr.

Like so:

Using first image as featured image example

Bonus: Viktiga tips om images i WordPress

Nu när du har lärt dig hur du ställer in standardfallback-bilder för dina inläggsminiatyrer, här är några andra användbara bildrelaterade tekniker för WordPress:

Vi hoppas att den här artikeln har hjälpt dig att lära dig hur du ställer in en standardfallback-image för inläggsminiatyrer i WordPress. Du kanske också vill kontrollera våra expertval av de bästa drag and drop page builders för WordPress och vår ultimata guide om hur man redigerar en WordPress website.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

66 kommentarerLämna ett svar

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Muhammed says

    How do you set up dafault thumbnail for posts that have thumbnails already but the images no longer exist on your server? And these posts are up to 1,000, which were created years ago. And these broken images make your site look messy.

  3. Hum says

    Hi,

    I tried to implement above code in my site with Sahifa theme (it doesn’t have default fallback thumbnail, I guess). However I am not success yet. I just want to display default image if post has no image. Here is the code in template:

    <a href="” title=”” rel=”bookmark”>

    Where and what code should I add to above to meet my requirement?

    Many thanks in advance.

  4. Andrei Filonov says

    Unfortunately adding condition ”has_post_image” may be tricky when plugins are used for ”latest” or ”related” posts, as we don’t want to mess up plugin code :)

    In this case we can add a custom filter to load custom default image when the_post_thumbnail is called:

    You can use it as a starting point and expand if you want custom default images for different post types or categories.

  5. JAVAD says

    hi i use auto-post-thumbnail to create auto thumbnail

    now i want if i enable show excerpt in my theme , first image or featured image shown on above the post in index.php

  6. Siddharth says

    Great! It is easy to understand now. I have seen different preference of feature images in many different themes but your blog post made sense.

  7. Laura P. says

    How can I tweak this function for adding a specific image (example.jpg) as the default image for post type: topic? Basically, I’m trying to set a default image for bbpress topic pages.

    Thanks!

    L

  8. Jose Salazar says

    Hi!

    Im adding the First Post Image as the Default Fallback, but would like to display attachment image ONLY if size in pixels is between 460×350 and 700×525. Is that possible? Any suggestions?

    Thanks in advance!

    • Dee says

      Hi Jose, How did you get the first image to show up? I removed the echo thumbnail and else statements and only have echo main image but it’s still showing the manual featured image. Thanks

  9. Paal Joachim Romdahl says

    Hey

    Could someone update the above code but this time to be added into the functions.php file?

    Perhaps even add on to how to define various category post images.

    Thank you!

  10. Nestor Cheese says

    Works great, thanks! The thing, though. is that the default thumbnail links automatically to the post but if you add a featured image, it doesn’t link. Has anyone resolved this?

  11. wfriley says

    I pasted the code into the functions.php file and checked my site to make sure nothing went haywire. For some reason my posts are now ending up on my static home page. I removed the code but it did not correct the problem. Any chance you might know a fix for that? I tried recreating the home page but the same thing happens.

  12. Alexandre Michel says

    Hi, looks like it’s working but in my single post page the default image does not show up. It returns blank code. Would you happen to know why?

  13. Mitch Larouche says

    How can I do an if statement where if there is no FEATURE or no MEDIA image then show google ad? This works but I want to add and IF for when I add a media image also. So if there is NO media image or feature image INCLUDE the adsense…php ad.

    ?php if( has_post_thumbnail() ) { ?>
    ?php } else { ?>
    ?php include(’adsense_singlepost_top_square.php’) ?>
    ?php }

    Can’t see to figure out how to include the media file from the post?

  14. Chetan Patel says

    Hello I have Wallpapers site on wordpress. I have little problem with images. Google Indexing my thumbnail instead of full size images. I want to index only full size image. Any way to do this. ?? please help ,me.

  15. Doop says

    This is great except if you upload an image to a post and then decide to delete it, it will still be attached to the post.

  16. Byron says

    Hi,
    I’m tying to set a default image for one of my custom post types. I’ve not been able to do this and have tried many of the plugin on the WP repository… Default featured image sets a featured image to All post types even Ubermenu.

    I need to limit this to one post type. Do you have any suggestions for me please?

    • WPBeginner Support says

      Byron, does the custom post type you want to set the default thumbnail for has featured image support? If yes then using this code in your theme template should display the default post thumbnail.

      <?php if ( has_post_thumbnail() ) {
      the_post_thumbnail();
      } else { ?>
      <img src="<?php bloginfo('template_directory'); ?>/images/default-image.jpg" alt="<?php the_title(); ?>" />
      <?php } ?>
      

      Administratör

  17. Paul says

    Okay, that didn’t work…! The a href tag messed it up. How do I show you code?

    <a href="" title="" >

    Try that!

  18. Alejandro says

    Excellent solution. Now, how I can use this to assign to a specific category and taking ramdom images from a folder?

    <img src="/images/default-image.jpg” alt=”” />

    Thank you a lot!

    • WPBeginner Support says

      This requires a more complicated solution. First you would want to set an image for each category and upload them to a specific folder probably using category slug as the image file names. Then you need to get the category slug for each post and use it as the fallback image URL.

      Administratör

  19. Konstantin says

    I am having a small problem, when calling the image, it only shows the full image, not the ones I try to specify (small, medium, thumbnail, etc).

    Did anything change in wp3.7+? The images are there, and are being created, but they wont display :(

  20. Susan Clifton says

    Will this work with a custom post type? I’m building a Portfolio theme. Your tutorials are always so helpful. I don’t really know PHP but I’m comfortable with messing with it.

  21. Tania says

    Is there a way to show a default ”image not available” image when the source image src is empty ?
    I’m promoting amazon products in my blog (using API) but most of the products do not have image. By providing a default ”image not available” image, I can help my visitors to understand that the sellers do not provide any image.

    I prefer html, css or javascript solution.

    thanks and sorry about my english ;)

  22. Waheed Akhtar says

    Hi Balkhi,

    I have some old posts where post thumbnail is not defined. Also may be for some posts there’s no image uploaded (did it manually through FTP and linked in the post). The result is I don’t see any featured thumbnail for the post.

    Is there a way we can grab the first image, resize it (e.g. 200 x 200) and show as featured image?

    Thanks.

  23. Amin says

    Thanks for this post. I’ve been searching for days to find a way to have an automatic default featured image. This saved me so much time! Thanks a lot.

  24. James says

    I’ve tried to merge both options but failed.

    How would you Check for Thumbnail, but if none then check for First Post Image, but then if none then post Default Branded Image?

      • Editorial Staff says

        Try this:

        function get_fbimage() {
          if ((function_exists('has_post_thumbnail')) && (has_post_thumbnail())) {
          $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), '', '' );
          $fbimage = $src[0];
          } else {
            global $post, $posts;
            $fbimage = '';
            $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',
            $post->post_content, $matches);
            $fbimage = $matches [1] [0];
          }
          if(empty($fbimage)) {
        	
            $fbimage = //Define Default URL HEre;
          }
          return $fbimage;
        }
        

        Administratör

        • Vanessa K says

          Hi :), great tutorial. I’m a somewhat beginner for a lot of wordpress code. I tried to follow this tutorial for setting up the fall back image a few months ago and failed :p but was able to successfully implement it just now. Yay me! haha. However I would really like to set it up in the way James mentioned…

          ”How would you Check for Thumbnail, but if none then check for First Post Image, but then if none then post Default Branded Image?”

          Posting the code you offered in response to his request is only showing up with syntax errors for me in my functions file :/. I’m sure it’s me and not the code :p but any suggestions? Thanks! And Happy Thanksgiving!

  25. jfwebdesignstud says

    wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), ’full’ );
     
    can this be used somehow with this for including pinterest featured image

  26. CharlesUibel says

    Yes But I don’t want to just display the fallback image, I want to assign the image to permanently be the featured image.

  27. leitseitenmacher says

    how do you create a real fall back thumbnail?

    with the solution a post rhumbnail is shown but therefore not registerate in the backend.

    any solution

    • wpbeginner says

      @leitseitenmacher The whole idea of a fallback is to show when nothing is selected at the thumbnails area in the backend… so NO you will not be able to see it in the backend….

      • leitseitenmacher says

        @wpbeginner

        well i allready noticed that.

        but the question was: is it possible in wordpress to register a standard post thumbnail via php code so you can see it in the backend?

        • wpbeginner says

          @leitseitenmacher Great find. Again, there is no HYPE that we are trying to create. It is impossible to keep track of what exists in the plugin sphere of WordPress because there are thousands.Just tested out that plugin… It doesn’t register those thumbnails in the database of each post. It is just hooking and giving you a visual display of what you selected in the plugins setting.

          If that is what you want, then sure.

          The article above accomplishes exactly the same thing without going the extra lengths of visually displaying. In most sites the fallback is usually the site logo. So you don’t really need to see it. But we will do a writeup on the plugin you found. Thanks for the suggestion :)

  28. gal1982 says

    Excellent solutions, i was looking for that for a while

    Is there a way to change the resize the image?

    I have tried for example:

    $image=wp_get_attachment_image($num, ’medium’);

    But it doesn’t effects the image size. any idea?

  29. milohuang says

    Nice tutorial. Have test the first method but it did not seem to work. Check the HTML and the default thumb does not exist (no img tag was found). However, if I use the Default Post Thumbnail plugin, it works. Any help? Running 3.2 locally. Thank you!

  30. wp_smith says

    Hello,

    I have written a plugin, <a href=”http://wpsmith.net/go/genesis-featured-images”>Genesis Featured Images</a>, that will do this for the <a href=”http://wpsmith.net/go/genesis”>Genesis Framework</a>. I’d love to hear your thoughts!?

  31. sleepingsun says

    Hello !

    Thanks a lot for this useful tip. How would I make the same function to work in RSS feeds please ? If a post thumbnail has been set : use it, otherwise : use the first image attached to the post.

    Any help would be much appreciated !

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.