0

i need the code which will add default thumb, if there is not featured image available. I was using default thumb plus for this but this plugin is using a lot of resource so i need to remove it.

I was trying to follow this tutorial

But no luck. Inside my widget i have this code

<?php if (  (function_exists('has_post_thumbnail')) && (has_post_thumbnail())  ) { ?>

Edited : And whole code you can see here pastebin.com/715evL1E

Any idea how to this ? thanks

I tried also with suggested code but i got an error .This is what i try the last in index.php

<?php if (  (function_exists('has_post_thumbnail')) && (has_post_thumbnail())  ) { ?>


                <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail('large-thumb'); } ?>
  <img src="<?php echo get_template_directory_uri(); ?>/images/transfer-deadline-150x150.jpg" /><?php } ?></a>
1
  • Is this being added inside the loop? And what is the URL to your fallback thumb image?
    – user23654
    Commented Sep 3, 2013 at 22:49

3 Answers 3

1

While there's no such functionality built into core, there's a Track Ticket I proposed 2 years ago. You can simply rip of the functionality from the suggested wp_default_img() function. I'll greatly appreciate any support in comments on that ticket, as this would be highly needed for every theme developer. Thanks in advance.

MU-Plugin

The following code is meant to be dropped into your ~/wp-content/mu-plugins folder (or whatever you named it). It will then per default be available in every site on a network install or simply everywhere in your single site install. Use it like this:

default_img( array( /* attributes - see doc block */ ) );

Just save the code below into a new file with any name and you're ready to go.

<?php
defined( 'ABSPATH' ) OR exit;
/**
 * Plugin Name: Default Image template tag
 * Plugin URI: http://unserkaiser.com
 * Description: Adds a default image template tag
 * Version: 0.1
 * Author: Franz Josef Kaiser
 * Author URI: http://unserkaiser.com
 * License: GNU GPL 2 <https://gist.github.com/1365159>
 */

/**
 * Default image
 *
 * Builds an default <img> for use in themes or plugins before any other images are added.
 * Resizes & crops the image using the built-in (retireved via `get_intermediate_image_sizes();`)
 * or custom image (added via `add_image_size();`) sizes.
 *
 * Retrieves calculated resize dimension @uses image_resize_dimensions();
 * Builds the width and height string @uses image_hwstring();
 *
 * @param $attr
 * @internal param $args (array)
 *        string $url URl to the given default image.
 *        string $size Optional. Default is 'medium'.
 *        string (optional) $alt Image Description for the alt attribute.
 *        string (optional) $title Image Description for the title attribute.
 *        string (optional) $align Part of the class name for aligning the image.
 *        string (optional) $echo Wheter to return or echo the $image
 * @return string HTML IMG element for given image attachment
 */
function default_img( $attr )
{
    // Sizes registered via add_image_size();
    global $_wp_additional_image_sizes;

    $defaults = array(
        'size'    => 'medium',
        'classes' => false,
        'alt'     => '',
        'title'   => '',
        'align'   => 'none',
        'echo'     => true,
    );

    $attr = wp_parse_args( $attr, $defaults );
    $attr = array_map( 'esc_attr', $attr );

    if ( 'thumb' === $attr['size'] )
        $attr['size'] = 'thumbnail';

    // Size in built in sizes - call size setting from DB
    # behavoir in here dependent on @link http://core.trac.wordpress.org/ticket/18947
    # if in core, we change to:
    # $sizes = get_intermediate_image_sizes();
    # $size_data = $sizes[ $size ];
    if ( ! in_array(
        $attr['size'],
        array_keys( $_wp_additional_image_sizes )
        ) )
    {
        # @TODO delete?
        $sizes = get_intermediate_image_sizes();

        // Get option - gladly autoloaded/can use wp_cache_get();
        $size_data['width']  = intval( get_option( "{$attr['size']}_size_w" ) );
        $size_data['height'] = intval( get_option( "{$attr['size']}_size_h" ) );
        // Not sure how this will behave if cropped is false (autoloaded option not added)
        if ( ! $size_data['crop'] = get_option( "{$attr['size']}_crop" ) )
            $attr['crop'] = false;
    }
    // Size array from global registered additional/custom sizes array
    else
    {
        $size_data = $_wp_additional_image_sizes[ $attr['size'] ];
    }

    // Retrieve image width & height
    $img_info  = @getimagesize( $attr['url'] );

    // Calculate final dimensions - if "crop" was set to true during add_image_size(), the img will get ... cropped
    $end_sizes = image_resize_dimensions(
        $img_info[0],
        $img_info[1],
        $size_data['width'],
        $size_data['height'],
        $size_data['crop']
    );

    // defaults to px units.
    // Can't get changed, as applying units is not possible
    $hwstring  = trim( image_hwstring(
        $end_sizes[4],
        $end_sizes[5]
    ) );

    // Attributes:
    // Not made required as users tend to do funky things (...and lock screen readers out)
    ! empty( $attr['alt'] ) AND $attr['alt'] = " alt='{$attr['alt']}'";

    if ( ! $attr['title'] )
    {
        $mime = explode( "/", $img_info['mime'] );
        $attr['title'] = sprintf( __( 'default image of type: %1$s' ), ucfirst( $mime[1] ) );
    }

    $attr['title'] = " title='{$attr['title']}'";

    $attr['align'] = " align{$attr['align']}";
    $attr['size']  = " size-{$attr['size']}";

    // Allow filtering of the default attributes
    $attr = apply_filters( 'wp_default_img_attr', $attr );

    // Build class attribute, considering that maybe some attribute was unset via the filter
    $classes  = "class='wp-img-default{$attr['align']}{$attr['classes']}{$attr['size']}'";

    $url   = trim( $attr['url'] );
    $image = "<img src='{$url}' {$hwstring} {$classes}{$attr['alt']}{$attr['title']} />";

    // Allow filtering of output
    $image = apply_filters( 'wp_default_img', $image );

    $attr['echo'] AND print $image;

    return $image;
}
0

has_post_thumbnail() function used without the ID has to be inside the loop.

while(has_post()) {
  the_post();
  if ( has_post_thumbnail() ) {
     the_post_thumbnail();
  } else {
    ?>
    <img src="<?php echo get_template_directory_uri(); ?>/images/default-thumb.jpg" />
  <?php
  }
}

You can also use has_post_thumbnail() with specific post id:

 <?php
     //Just an exampl
     $post_id = 45;
     if ( has_post_thumbnail($post_id) ) {
        //in this case we can not use the_post_thumbnail
         get_the_post_thumbnail($post_id, 'thumbnail');
     } else {
     ?>
        <img src="<?php echo get_template_directory_uri(); ?>/images/default-thumb.jpg" />
     <?php
     }

Also, be sure the theme suppports post thumbnails adding this in functions.php

add_theme_support( 'post-thumbnails' ); 

If you post the full code of your widget I can teach you exactly how to implement the default thumbnail feature.

9
  • This is not an answer, this is just an addendum to Chip Bennett's answer.
    – vancoder
    Commented Sep 3, 2013 at 23:11
  • @vancoder What's wrong with that? Yes, it could as well have been an edit, but people reading it will still honor this question as well if they found Chips answer useful.
    – kaiser
    Commented Sep 3, 2013 at 23:28
  • "If you wish to improve an existing answer, click the edit link beneath it." wordpress.stackexchange.com/help/deleted-answers
    – vancoder
    Commented Sep 4, 2013 at 0:14
  • I've edited now the Chip Bennett's answer, but honestly I think the original answer was really very incomplete and could be in the no-answer zone. I will delete this answer if the edition is accepted.
    – cybmeta
    Commented Sep 4, 2013 at 1:52
  • @cybnet Approved edit.
    – kaiser
    Commented Sep 4, 2013 at 2:54
0

There is no such functionality in WordPress core. You'll have to create, upload, and call your own default Thumbnail if no featured image is selected. For example, if you have a default Thumbnail inside your Theme file structure you can use has_post_thumbnail() to check if the current post has a thumbnail and the_post_thumbnail() to display it; both functions have to be used inside the loop.

   if ( has_post_thumbnail() ) {
      the_post_thumbnail();
   } else {
   ?>
      <img src="<?php echo get_template_directory_uri(); ?>/images/default-thumb.jpg" />
   <?php
   }
?>

There are lots of methods to implement; this is just a quick-and-dirty example.

3
  • Hi All, i m not sure where to respond, so i will to this one. This is the code which i trid to add ,but nothing.Also i tried to mix it a little, but errors keep showing. As for the uploaded image of course i add it after ?>/ and i tried here several solutions as my images are inside wp-content/uploads/date/name.jpg ..so maybe its the best to give the code so you can see it better pastebin.com/715evL1E Thanks all for your help @ChipBennett
    – Max
    Commented Sep 3, 2013 at 23:58
  • @Max Please, just add the code as edit to your question. Don't hide progress in comments.
    – kaiser
    Commented Sep 4, 2013 at 2:54
  • @kaiser , sorry,didnt know that, but i edited now
    – Max
    Commented Sep 4, 2013 at 23:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.