Saturday, April 4, 2015

Wordpress conditional tag for checking posts and pages.

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Conditional Tags

Contents

Introduction

The Conditional Tags can be used in your Template files to change what content is displayed and how that content is displayed on a particular page depending on whatconditions that page matches. For example, you might want to display a snippet of text above the series of posts, but only on the main page of your blog. With the is_home()Conditional Tag, that task is made easy.
Note the close relation these tags have to WordPress Template Hierarchy.
Warning: You can only use conditional query tags after the posts_selection action hook in WordPress (the wp action hook is the first one through which you can use these conditionals). For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.
However: if you have a reference to the query object (for example, from within the parse_query or pre_get_posts hooks), you can use the WP_Query conditional methods (eg: $query->is_search())

The Conditions For ...

All of the Conditional Tags test to see whether a certain condition is met, and then returns either TRUE or FALSE. The conditions under which various tags output TRUE is listed below. Those tags which can accept parameters are so noted.

The Main Page

is_home() 
When the main blog page is being displayed. This is the page which shows the time based blog content of your site, so if you've set a static Page for the Front Page (see below), then this will only be true on the Page which you set as the "Posts page" inAdministration > Settings > Reading.

The Front Page

is_front_page() 
When the front of the site is displayed, whether it is posts or a Page. Returns true when the main blog page is being displayed and the 'Settings > Reading ->Front page displays' is set to "Your latest posts", or when 'Settings > Reading ->Front page displays' is set to "A static page" and the "Front Page" value is the current Page being displayed.

The Blog Page

is_front_page() and is_home() 
There is no conditional tag for the blog page. You have to use both is_home() andis_front_page() to detect this page, but those functions can be misused. In fact, a user can define a static page for the homepage, and another page to display the blog. This one will return true with is_home() function, even if it's not the homepage. Here is what a user can define :
  • a default homepage (with the latest posts)
  • a static homepage and no blog page
  • a static homepage and a blog page
When you use is_home() and is_front_page(), you have to use them in the right order to avoid bugs and to test every user configuration:
if ( is_front_page() && is_home() ) {
  // Default homepage
} elseif ( is_front_page() ) {
  // static homepage
} elseif ( is_home() ) {
  // blog page
} else {
  //everything else
}

The Administration Panels

is_admin()
When the Dashboard or the administration panels are being displayed.
is_network_admin()
When the Network Dashboard or the Network administration panels for multisite are being displayed.
Attention: The wp-login.php page is not an admin page. To check if this page is displayed, use the admin global variable $pagenow.

The Admin Bar

is_admin_bar_showing() 
Returns true if the admin bar will be displayed.
Note : To display or not this bar, use show_admin_bar(), this function should be called immediately upon plugins_loaded or placed in the theme's functions.php file.

A Single Post Page

is_single() 
When a single post of any post type (except attachment and page post types) is being displayed.
is_single( '17' ) 
When Post 17 is being displayed as a single Post.
is_single( 'Irish Stew' ) 
When the Post with Title "Irish Stew" is being displayed as a single Post.
is_single( 'beef-stew' ) 
When the Post with Post Slug "beef-stew" is being displayed as a single Post.
is_single( array( 17, 'beef-stew', 'Irish Stew' ) ) 
Returns true when the single post being displayed is either post ID 17, or the post_name is "beef-stew", or the post_title is "Irish Stew".
is_single( array( 17, 19, 1, 11 ) ) 
Returns true when the single post being displayed is either post ID = 17, post ID = 19, post ID = 1 or post ID = 11.
is_single( array( 'beef-stew', 'pea-soup', 'chili' ) ) 
Returns true when the single post being displayed is either the post_name "beef-stew", post_name "pea-soup" or post_name "chili".
is_single( array( 'Beef Stew', 'Pea Soup', 'Chili' ) ) 
Returns true when the single post being displayed is either the post_title is "Beef Stew", post_title is "Pea Soup" or post_title is "Chili".
Note: This function does not distinguish between the post ID, post title, or post name. A post named "17" would be displayed if a post ID of 17 was requested. Presumably the same holds for a post with the slug "17".

A Sticky Post

is_sticky() 
Returns true if "Stick this post to the front page" check box has been checked for the current post. In this example, no post ID argument is given, so the post ID for the Loop post is used.
is_sticky( '17' ) 
Returns true when Post 17 is considered a sticky post.

A Post Type is Hierarchical

is_post_type_hierarchical( $post_type ) 
Returns true if this $post_type has been set with hierarchical support when registered.
is_post_type_hierarchical( 'book' ) 
Returns true if the book post type was registered as having support for hierarchical.

A Post Type Archive

is_post_type_archive() 
Returns true on any post type archive.
is_post_type_archive( $post_type ) 
Returns true if on a post type archive page that matches $post_type.
is_post_type_archive( array( 'foo', 'bar', 'baz' ) ) 
Returns true if on a post type archive page that matches either "foo", "bar", or "baz".
To turn on post type archives, use 'has_archive' => true, when registering the post type.

A Comments Popup

is_comments_popup() 
When in Comments Popup window.

Any Page Containing Posts

comments_open()
When comments are allowed for the current Post being processed in the WordPress Loop.
pings_open()
When pings are allowed for the current Post being processed in the WordPress Loop.

A PAGE Page

This section refers to WordPress Pages, not any generic webpage from your blog, or in other words to the built in post_type 'page'.
is_page() 
When any Page is being displayed.
is_page( 42 ) 
When Page 42 (ID) is being displayed.
is_page( 'About Me And Joe' ) 
When the Page with a post_title of "About Me And Joe" is being displayed.
is_page( 'about-me' ) 
When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( array( 42, 'about-me', 'About Me And Joe' ) ) 
Returns true when the Pages displayed is either post ID = 42, or post_name is "about-me", or post_title is "About Me And Joe".
is_page( array( 42, 54, 6 ) ) 
Returns true when the Pages displayed is either post ID = 42, or post ID = 54, or post ID = 6.
See also is_page() for more snippets.
Note: There is no function to check if a page is a sub-page. We can get around the problem:
if ( is_page() && $post->post_parent > 0 ) { 
    echo "This is a child page";
}

Is a Page Template

Allows you to determine whether or not you are in a page template or if a specific page template is being used.
is_page_template() 
Is a Page Template being used?
is_page_template( 'about.php' ) 
Is Page Template 'about' being used?
Note: if the file is in a subdirectory you must include this as well. Meaning that this should be the filepath in relation to your theme as well as the filename, for example page-templates/about.php.

A Category Page

is_category( $category ) 
When the actual page is associated with the $category Category.
is_category( '9' ) 
When the archive page for Category 9 is being displayed.
is_category( 'Stinky Cheeses' ) 
When the archive page for the Category with Name "Stinky Cheeses" is being displayed.
is_category( 'blue-cheese' ) 
When the archive page for the Category with Category Slug "blue-cheese" is being displayed.
is_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) ) 
Returns true when the category of posts being displayed is either term_ID 9, or slug "blue-cheese", or name "Stinky Cheeses".
in_category( '5' ) 
Returns true if the current post is in the specified category id (read more).
in_category( array( 1,2,3 ) ) 
Returns true if the current post is in either category 1, 2, or 3.
! in_category( array( 4,5,6 ) ) 
Returns true if the current post is NOT in either category 4, 5, or 6. Note the ! at the beginning.
Note: Be sure to check your spelling when testing: "is" and "in" are significantly different.

A Tag Page

is_tag() 
When any Tag archive page is being displayed.
is_tag( 'mild' ) 
When the archive page for tag with the slug of 'mild' is being displayed.
is_tag( array( 'sharp', 'mild', 'extreme' ) ) 
Returns true when the tag archive being displayed has a slug of either "sharp", "mild", or "extreme".
has_tag() 
When the current post has a tag. Prior to 2.7, must be used inside The Loop.
has_tag( 'mild' ) 
When the current post has the tag 'mild'.
has_tag( array( 'sharp', 'mild', 'extreme' ) ) 
When the current post has any of the tags in the array.
See also is_archive() and Tag Templates.

A Taxonomy Page (and related)

is_tax

is_tax() 
When any Taxonomy archive page is being displayed.
is_tax( 'flavor' ) 
When a Taxonomy archive page for the flavor taxonomy is being displayed.
is_tax( 'flavor', 'mild') 
When the archive page for the flavor taxonomy with the slug of 'mild' is being displayed.
is_tax( 'flavor', array( 'sharp', 'mild', 'extreme' ) ) 
Returns true when the flavor taxonomy archive being displayed has a slug of either "sharp", "mild", or "extreme".

has_term

has_term() 
Check if the current post has any of given terms. The first parameter should be an empty string. It expects a taxonomy slug/name as a second parameter.
has_term( 'green', 'color' ) 
When the current post has the term 'green' from taxonomy 'color'.
has_term( array( 'green', 'orange', 'blue' ), 'color' ) 
When the current post has any of the terms in the array.

term_exists

term_exists( $term, $taxonomy, $parent ) 
Returns true if $term exists in any taxonomy. If $taxonomy is given, the term must exist in this one. The 3rd parameter $parentis also optional, if given, the term have to be a child of this parent, the taxonomy must be hierarchical.

is_taxonomy_hierarchical

is_taxonomy_hierarchical( $taxonomy ) 
Returns true if the taxonomy $taxonomy is hierarchical. To declare a taxonomy hierarchical, use 'hierarchical' => truewhen using register_taxonomy().

taxonomy_exists

taxonomy_exists( $taxonomy ) 
Returns true if $taxonomy has been registered on this site using register_taxonomy().
See also is_archive().

An Author Page

is_author() 
When any Author page is being displayed.
is_author( '4' ) 
When the archive page for Author number (ID) 4 is being displayed.
is_author( 'Vivian' ) 
When the archive page for the Author with Nickname "Vivian" is being displayed.
is_author( 'john-jones' ) 
When the archive page for the Author with Nicename "john-jones" is being displayed.
is_author( array( 4, 'john-jones', 'Vivian' ) ) 
When the archive page for the author is either user ID 4, or user_nicename "john-jones", or nickname "Vivian".
See also is_archive() and Author Templates.

A Multi-author Site

is_multi_author( ) 
When more than one author has published posts for a site. Available with Version 3.2.

A Date Page

is_date() 
When any date-based archive page is being displayed (i.e. a monthly, yearly, daily or time-based archive).
is_year() 
When a yearly archive is being displayed.
is_month() 
When a monthly archive is being displayed.
is_day() 
When a daily archive is being displayed.
is_time() 
When an hourly, "minutely", or "secondly" archive is being displayed.
is_new_day() 
If today is a new day according to post date. Should be used inside the loop.
See also is_archive().

Any Archive Page

is_archive() 
When any type of Archive page is being displayed. Category, Tag, other Taxonomy Term, custom post type archive, Author and Date-based pages are all types of Archives.

A Search Result Page

is_search() 
When a search result page archive is being displayed.

A 404 Not Found Page

is_404() 
When a page displays after an "HTTP 404: Not Found" error occurs.

A Paged Page

is_paged() 
When the page being displayed is "paged". This refers to an archive or the main page being split up over several pages and will return true on 2nd and subsequent pages of posts. This does not refer to a Post or Page whose content has been divided into pages using the <!--nextpage--> QuickTag. To check if a Post or Page has been divided into pages using the <!--nextpage--> QuickTag, see A_Paged_Page section.

An Attachment

is_attachment() 
When an attachment document to a post or Page is being displayed. An attachment is an image or other file uploaded through the post editor's upload utility. Attachments can be displayed on their own 'page' or template.

Attachment Is Image

wp_attachment_is_image( $post_id ) 
Returns true if the attached file to the post with ID equal to $post_id is an image. Mime formats and extensions allowed are: .jpg, .jpeg, .gif, et .png.

A Local Attachment

is_local_attachment( $url ) 
Returns true if the link passed in $url is a real attachment file from this site.

A Single Page, a Single Post, an Attachment or Any Other Custom Post Type

is_singular() 
Returns true for any is_single()is_page(), or is_attachment().
is_singular( 'foo' ) 
Returns true if the post_type is "foo".
is_singular( array( 'foo', 'bar', 'baz' ) ) 
Returns true if the post_type is "foo", "bar", or "baz".
See also the Custom Post Types book.

Post Type Exists

post_type_exists( $post_type ) 
Returns true is the given $post_type has been registered on this site using register_post_type().

Is Main Query

is_main_query()
Returns true when the current query (such as within the loop) is the "main" query.
Example with the filter hook the_content
add_action( 'the_content', 'baw_add_social_buttons' );
function baw_add_social_buttons( $content ) {
    if ( ! is_admin() && is_main_query() ) {
        return $content . function_from_a_social_plugin();
    }
    return $content;
}
If, when WordPress tries to display the content of each post in the Loop or in a single post page, we are in the main query, and not admin side, we add some social buttons (for example).
Example with the action hook pre_get_posts
add_action( 'pre_get_posts', 'baw_modify_query_exclude_category' );
function baw_modify_query_exclude_category( $query ) {
    if ( ! is_admin() && $query->is_main_query() && ! $query->get( 'cat' ) ) {
        $query->set( 'cat', '-5' );
    }
}
With pre_get_posts, this is not possible to call directly is_main_query, we should use $query given as a parameter.

A New Day

is_new_day() 
Returns true if today is a new day.

A Syndication

is_feed() 
When the site requested is a Syndication. This tag is not typically used by users; it is used internally by WordPress and is available for Plugin Developers.

A Trackback

is_trackback() 
When the site requested is WordPress' hook into its Trackback engine. This tag is not typically used by users; it is used internally by WordPress and is available for Plugin Developers.

A Preview

is_preview() 
When a single post being displayed is viewed in Draft mode.

Has An Excerpt

has_excerpt() 
When the current post has an excerpt
has_excerpt( 42 ) 
When the post 42 (ID) has an excerpt.

Has A Nav Menu Assigned

has_nav_menu() 
Returns true when a registered nav menu location has a menu assigned.

Inside The Loop

in_the_loop() 
Check to see if you are "inside the loop". Useful for plugin authors, this conditional returns as true when you are inside the loop.

Is Dynamic SideBar

is_dynamic_sidebar() 
Returns true if the theme supports dynamic sidebars.

Is Sidebar Active

is_active_sidebar() 
Check to see if a given sidebar is active (in use). Returns true if the sidebar (identified by name or id) is in use.
Note: To display a sidebar's content, use dynamic_sidebar( $sidebar ).

Is Widget Active

is_active_widget( $widget_callback, $widget_id ) 
Returns true if the widget with callback $widget_callback or it's ID is $widget_idwill be displayed on front-end.
Note : To be effective this function has to run after widgets have initialized, at action 'init' or later, see Action Reference.

Is Blog Installed

is_blog_installed() 
Returns true if the current is properly installed.
Note: The cache will be checked first. If you have a cache plugin, which saves the cache values, then this will work. If you use the default WordPress cache, and the database goes away, then you might have problems.

Right To Left Reading

is_rtl() 
Returns true if the current locale est read from right to left (RTL).
Example
 if ( is_rtl() ) {
   wp_enqueue_style(  'style-rtl',  plugins_url( '/css/style-rtl.css', __FILE__ ) );
   wp_enqueue_script( 'script-rtl', plugins_url( '/js/script-rtl.js',  __FILE__ ) );
 }

Part of a Network (Multisite)

is_multisite() 
Check to see whether the current site is in a WordPress MultiSite install.

Main Site (Multisite)

is_main_site() 
Determine if a site is the main site in a network.

Admin of a Network (Multisite)

is_super_admin() 
Determine if user is a network (super) admin.

Is User Logged in

is_user_logged_in() 
Returns true if any user is currently logged-in, any roles.

Email Exists

email_exists( $email ) 
Check whether or not the given email address $email has already been registered to a username, and returns that user's ID orfalse if does not exists.

Username Exists

username_exists( $username ) 
Check whether or not the given username $username has already been registered to a username, and returns that user's ID orfalse if does not exists.

An Active Plugin

is_plugin_active( $path ) 
Checks if a plugin is activated.
is_plugin_active( 'akismet/akismet.php' ) 
Checks if Akismet is activated.
is_plugin_inactive( $path ) 
Checks if a plugin is deactivated. Same as ! is_plugin_active( $path ).
is_plugin_active_for_network( $path ) 
Same thing for a network activation on a multisite installation.
is_plugin_page() 
Returns true if the loaded page, admin side is a plugin's one. This function is deprecated depuis since WordPress 3.1, with no known alternative.

A Child Theme

is_child_theme() 
Check whether a child theme is in use.

Theme supports a feature

current_theme_supports() 
Check if various theme features exist.
current_theme_support( 'post-thumbnails' ) 
Returns true if the current theme supports featured images. To add a theme support functionality, use add_theme_support().

Has Post Thumbnail

has_post_thumbnail( $post_id ) 
Returns true if the post with ID equal to $post_id contains a featured image. Theme should support Featured Images, see above.

Script Is In use

wp_script_is( $handle, $list ) 
Returns true if the script with handle is $handle has been 'registered', 'enqueue/queue', 'done', ou 'to_do' depending on $list.
Example
    $handle = 'fluidVids.js';
    $list = 'enqueued';
      if ( wp_script_is( $handle, $list ) ) {
        return;
      } else {
        wp_register_script( 'fluidVids.js', plugin_dir_url(__FILE__).'js/fluidvids.min.js');
        wp_enqueue_script( 'fluidVids.js' );
      }
This would check if the script named 'fluidVids.js' is enqueued. If it is not enqueued, the files are then registered and enqueued.

Working Examples

Here are working samples to demonstrate how to use these conditional tags.

Single Post

This example shows how to use is_single() to display something specific only when viewing a single post page:
if ( is_single() ) {

   echo 'This post\'s title is ' . get_the_title();

}
Add this custom function to your child themes functions.php file and modify the conditional tag to suit your needs.
add_action( 'loop_start', 'add_to_single_posts' );
function add_to_single_posts() {
if ( is_single('post') ) {
echo'<div class="your-class">Your Text or HTML</div>';
    }
}
You could also use:
add_action( 'loop_start', 'wpsites_add_to_single_posts' );
function wpsites_add_to_single_posts() {
if ( is_single() ) {
echo'<div class="your-class">Your Text or HTML</div>';
    }
}
Another example of how to use Conditional Tags in the Loop. Choose to display content or excerpt in index.php when this is a display single post or the home page.
if ( is_home() || is_single() ) {

   the_content();

}
else {

   the_excerpt();

}
When you need display a code or element, in a place that is NOT the home page.
<?php if ( ! is_home() ) {?>

 Insert your markup ...

<?php } ?>

Check for Multiple Conditionals

You can use PHP operators to evaluate multiple conditionals in a single if statement.
This is handy if you need to check whether combinations of conditionals evaluate to true or false.
// Check to see if 2 conditionals are met


if ( is_single() || is_page() ) ) {
  
 // If it's a single post or a single page, do something special

}

if ( is_archive() && ! is_category( 'nachos' ) ) {
  
 // If it's an archive page for any category EXCEPT nachos, do something special

}
// Check to see if 3 conditionals are met


if ( $query->is_main_query() && is_post_type_archive( 'products' ) && ! is_admin() ) {
  
 // If it's the main query on a custom post type archive for Products
 // And if we're not in the WordPress admin, then do something special

}

if ( is_post_type_archive( 'movies' ) || is_tax( 'genre' ) || is_tax( 'actor' )  ) {
  
 // If it's a custom post type archive for Movies
 // Or it's a taxonomy archive for Genre
 // Or it's a taxonomy archive for Actor, do something special

}

Date-Based Differences

If someone browses our site by date, let's distinguish posts in different years by using different colors:
<?php
// this starts The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

<?php
// are we showing a date-based archive?
if ( is_date() ) {
     if ( date( 'Y' ) != get_the_date( 'Y' ) ) {
          // this post was written in a previous year
          // so let's style the content using the "oldentry" class
          echo '<div class="oldentry">';
     } else {
          echo '<div class="entry">';
     }
} else {
     echo '<div class="entry">';
}

the_content( 'Read the rest of this entry »' ); 

?>
</div>

Variable Sidebar Content

This example will display different content in your sidebar based on what page the reader is currently viewing.
<!-- begin sidebar -->
<div id="sidebar">
<?php
// let's generate info appropriate to the page being displayed
if ( is_home() ) {
    // we're on the home page, so let's show a list of all top-level categories
    echo "<ul>";
    wp_list_categories( 'optionall=0&sort_column=name&list=1&children=0' );
    echo "</ul>";
} elseif ( is_category() ) {
    // we're looking at a single category view, so let's show _all_ the categories
     echo "<ul>";
    wp_list_categories( 'optionall=1&sort_column=name&list=1&children=1&hierarchical=1' );
    echo "</ul>";
} elseif ( is_single() ) {
    // we're looking at a single page, so let's not show anything in the sidebar
} elseif ( is_page() ) {
    // we're looking at a static page.  Which one?
    if ( is_page( 'About' ) ) {
        // our about page.
        echo "<p>This is my about page!</p>";
    } elseif ( is_page( 'Colophon' ) ) {
        echo "<p>This is my colophon page, running on WordPress, " . bloginfo( 'name' ) . "</p>";
    } else {
        // catch-all for other pages
        echo "<p>Vote for Pedro!</p>";
    }
} else {
    // catch-all for everything else (archives, searches, 404s, etc)
    echo "<p>That's all.</p>";
} // That's all, folks!
?>
<form id="searchform" method="get" action="<?php echo esc_url( $_SERVER['PHP_SELF'] ); ?>">
<div>
<input type="text" name="s" id="s" size="15" />
<input type="submit" value="<?php _e( 'Search' ); ?>" />
</div>
</form>

</div>
<!-- end sidebar -->

Helpful 404 Page

The Creating an Error 404 Page article has an example of using the PHP conditional function  isset() in the Writing Friendly Messages section.

Dynamic Menu Highlighting

The Dynamic Menu Highlighting article discusses how to use the conditional tags to enable highlighting of the current page in a menu.

In a theme's footer.php file

At times queries performed in other templates such as sidebar.php may corrupt certain conditional tags. For instance, in header.php a conditional tag works properly but doesn't work in a theme's footer.php. The trick is to put wp_reset_query before the conditional test in the footer. For example:
<?php
wp_reset_query();
if ( is_page( '2' ) ) {
    echo 'This is page 2!';
} 
?>

Conditional Tags Index

Alphabetical List

Thursday, April 2, 2015

How to display wordpress recent posts of custom size image in widgets


Function Reference/get the post thumbnail

Description

Gets the Featured Image (formerly called Post Thumbnail) as set in post's or page's edit screen and returns an HTML image element representing a Featured Image, if there is any, otherwise an empty string.
Note: To enable Post Thumbnails, the current theme must include add_theme_support( 'post-thumbnails' ); in its functions.php file. See alsoPost Thumbnails.

Usage

 <?php echo get_the_post_thumbnail$post_id$size$attr ); ?> 

Parameters

$post_id
(integer) (Optional) Post ID.
Default: Post ID
$size
(string/array) (Optional) Either a string keyword (thumbnail, medium, large or full) or a 2-item array representing width and height in pixels, e.g. array(32,32).
Default: 'post-thumbnail'
$attr
(string/array) (optional) Query string or array of attributes. See wp_get_attachment_image.
Default: None
$default_attr = array(
 'src' => $src,
 'class' => "attachment-$size",
 'alt' => trim( strip_tags( $attachment->post_excerpt ) ),
 'title' => trim( strip_tags( $attachment->post_title ) ),
);

Return Values

Returns a string containing an HTML image element, or an empty string if no post thumbnail is found.

Examples

Sample Usage

<?php $pages = get_pages( array( 'child_of' => 1 ) ); ?> 
<ul>
 <?php foreach ( $pages as $page ) : ?>
  <li>
   <?php echo get_the_post_thumbnail( $page->ID, 'thumbnail' ); ?>
   <h1><?php echo apply_filters( 'the_title', $page->post_title, $page->ID ); ?></h1>
   <?php echo apply_filters( 'the_content', $page->post_content ); ?>
  </li>
 <?php endforeach; ?>
</ul>

Thumbnail Sizes

The default image sizes of WordPress are "thumbnail", "medium", "large" and "full" (the size of the image you uploaded). These image sizes can be configured in the WordPress Administration Media panel under Settings > Media. Themes may also add "post-thumbnail". This is how you can use these default sizes with get_the_post_thumbnail():
// without parameter -> Post Thumbnail (as set by theme using set_post_thumbnail_size())
get_the_post_thumbnail( $post_id );                   

get_the_post_thumbnail( $post_id, 'thumbnail' );      // Thumbnail (Note: different to Post Thumbnail)
get_the_post_thumbnail( $post_id, 'medium' );         // Medium resolution
get_the_post_thumbnail( $post_id, 'large' );          // Large resolution
get_the_post_thumbnail( $post_id, 'full' );           // Original resolution

get_the_post_thumbnail( $post_id, array( 100, 100) ); // Other resolutions
Register new image sizes for Post Thumbnails with: add_image_size().
To set the default size for Post Thumbnails see: set_post_thumbnail_size().

Post Thumbnail Linking to the Post Permalink

This example shows the 5 latest Post Thumbnails linked to their Post permalink.
<?php 
$thumbnails = get_posts( 'numberposts=5' );
foreach ( $thumbnails as $thumbnail ) {
 if ( has_post_thumbnail( $thumbnail->ID ) ) {
  echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
  echo get_the_post_thumbnail( $thumbnail->ID, 'thumbnail' );
  echo '</a>';
 }
}
?>

Post Thumbnail Linking to large Image Size

This example links to the "large" Post Thumbnail image size and must be used within The Loop.
<?php 
if ( has_post_thumbnail() ) {
 $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' );
 echo '<a href="' . $large_image_url[0] . '" title="' . the_title_attribute( 'echo=0' ) . '" >';
 echo get_the_post_thumbnail( $post->ID, 'thumbnail' ); 
 echo '</a>';
}
?>

Styling Post Thumbnails

Post Thumbnails are given a class "wp-post-image". They also get a class depending on the size of the thumbnail being displayed You can style the output with these CSS selectors:
img.wp-post-image
img.attachment-thumbnail
img.attachment-medium
img.attachment-large
img.attachment-full
You can also give Post Thumbnails their own class.
Give the Post Thumbnail a class "alignleft".
<?php echo get_the_post_thumbnail( $post_id, 'thumbnail', array( 'class' => 'alignleft' ) ); ?>

Notes

If the required add_theme_support( 'post-thumbnails' ); in the current theme's functions.php file is attached to a hook, it must be must be called before the init hook is fired. The init hook may be too late for some features. If attached to a hook, it must beafter_setup_theme.

Change Log

Since: 2.9.0

Source File

get_the_post_thumbnail() is located in wp-includes/post-thumbnail-template.php.

External Resources

Related

See also index of Function Reference and index of Template Tags.

Monday, March 30, 2015

20 useful wordpress plugins

The 10 WordPress plugins we use to supercharge the Buffer blog

(A note about WordPress plugins: They’re super great, which makes it easy to add a whole bunch without thinking of the ramifications. Here’s a helpful post from WP Engine about the effect that plugins can have on your site speed. Takeaway: Check the quality of the plugins you install.)

1. Scroll Triggered Box

Probably our most-asked-about plugin is the one we use for our email capture slideup. Drumroll please … it’s Dreamgrow’s Scroll Triggered Box.
Screen Shot 2014 07 14 at 6.05.09 AM 730x499 20 WordPress plugins for easier sharing, better posting and a more powerful blog
The email capture box slides up from the bottom right-hand corner of the page whenever a visitor scrolls down 60 percent of the page’s height. If a visitor closes the box, they won’t see it again for 30 days. The box itself can be completely customized with whatever HTML text you want; we chose to sync it with our MailChimp list.
And all these numbers and options can be completely customized—scroll percentage, days hidden, position, width, colors, and more. You can even choose where the box is visible, e.g. frontpage, posts,and/or pages.
Price: Free

2. Digg Digg

There are a huge number of different plugins you can use to display social share buttons on your blog post. We’ve got a rooting interest in Digg Digg.
Digg Digg was built by our Buffer engineers a couple of years back, and it’s been a staple on the Buffer blog ever since. What we’ve found most helpful with Digg Digg integration is the flexibility of where you can place the share buttons: floating to the left or right of the article (see our Open blog), pinned to the top or bottom of a blog post (see this Buffer Social blog), or manually wherever you wish inside your theme.
Screen Shot 2014 07 14 at 6.08.05 AM 730x366 20 WordPress plugins for easier sharing, better posting and a more powerful blog
(While I’m thinking of it, I should mention that we’re often asked about the plugin that powers our author bio sections. Believe it or not, we don’t use a plugin for that! Our theme designers built the bios right into the template code.)
Price: Free

3. WordPress SEO by Yoast

Many SEO experts would recommend you grab an SEO plugin for your WordPress blog. Our go-to plugin is WordPress SEO by Yoast, which handles just about every element of SEO you could think of.
The most direct impact of this plugin on us writers is the SEO box beneath every post. Here we can choose our keyword for the post—a great tactic for staying focused on a topic—and add a custom title and description. The plugin will also show you in bright green/red text how your post stacks up based on the keyword you’ve entered.
Screen Shot 2014 07 14 at 8.15.40 AM 730x706 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Price: Free

4. Hello Bar

You’ve likely noticed the bright, orange bar welcoming you to the Buffer blog every morning. That’s the Hello Bar, an amazing tool for A/B testing different CTAs and power words—and a pretty great tool for collecting email addresses, too.
Via HelloBar, we collect over 400 email addresses each week on the Buffer blog. Along with the slideup, those two sources account for over half of our new email signups each week.
Screen Shot 2014 07 14 at 8.14.26 AM 730x163 20 WordPress plugins for easier sharing, better posting and a more powerful blog
The WordPress plugin for Hello Bar is as simple as it comes: Simply download, install, and paste in your Hello Bar code. You can also signup for a free Hello Bar account and grab the embed code yourself. We found the plugin to be the easier way to go.
Price: Free

5. Disqus comments

One of the easiest (and prettiest) commenting systems we’ve found has been Disqus. The powerful Disqus system works right off your standard WordPress setup, allowing you to manage all comments neatly and quickly through the Disqus admin area or straight from the comments section on your blog.
We’ve run into a spate of comment spam on some of our old blog posts recently, and turning off comments for individual posts is as simple as two clicks on a drop-down menu.
Screen Shot 2014 07 14 at 8.13.56 AM 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Price: Free

6. WP Engine

We host the Buffer blog through WP Engine, and we get a lot more goodies from them beyond just hosting. WP Engine creates daily backups and one-click restores of the blog, manages all our major WordPress updates automatically, and provides security features to keep our blog safe.
While it’s not technically a plugin, WP Engine does add a little menu item to our WordPress sidebar, and we can quickly check there to see error logs, change some advanced settings, or log in to our WP Engine dashboard.
Price: Starting at $29 per month

7. Pin It Button for Images

Here’s one people seem to love: the Pin It Button for Images. This plugin adds a Pinterest Pin It button overlay on top of any image that appears in your blog post. Simple as that!
We’ve installed the plugin on the Buffer blog, and we’ve changed the settings so that the Pin It button only shows up when you add a specific CSS class to an image. You can also change the settings so that the button only shows on images on single posts, pages, index, category, and more.
Price: Free

8. Editorial Calendar

When Courtney and I were getting into the groove of posting to the Buffer blog, we found it helpful to stay organized with an editorial calendar. The Editorial Calendar WordPress plugin seemed to do the trick just fine. It grabbed all of our scheduled posts and drafts, and it placed them on a neatly organized calendar so we could see at-a-glance what content was coming up.
Perhaps my favorite feature of the plugin was the cool way you could drag and drop different stories around the calendar, and it would update not only the calendar but the post itself. It was a huge help for keeping all our content organized and our team in sync.
Price: Free

9. WP Hide Post

Most likely our least-known WordPress plugin, WP Hide Post does exactly what it says: It hides posts from the blog.
Of course, these posts are still visible if you navigate there directly. However, they won’t show up in RSS feeds or on the main index page of blog posts.
We use this plugin to publish marketing materials (case studies, interviews, etc.) that we might want to reference later with our outreach efforts or promotions. These materials typically don’t fit the content strategy we have on the blog, so we hide them from our standard publishing streams.
Price: Free

10. MyTweetLinks

Another plugin we keep in the toolbox (but you might not have seen lately) is MyTweetLinks. Think of this plugin as a soundbite source. You can enter a soundbite or quotable via the post editor, and this plugin will create a list of tweets to share and buffer at the end of your published post.
Screen Shot 2014 07 14 at 7.00.12 AM 1024x225 730x160 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Price: Free
Next: 10 more plugins worth trying

10 plugins we’d love to try (someday)

1. Filament

You might be familiar with Filament’s adopted plugin Flare, a social share button plugin made by Digital Telepathy. You download and install Filament to your WP blog one time, then you can add any number of apps through the Filament dashboard whenever you choose.
Current apps include: MailChimp subscribe form, Google Analytics tracking, all-in-one profiles, code management, and share highlighter.
Price: Free

2. SumoMe – Twitter highlighter, photo share, email list popup

Built by Noah Kagan’s App Sumo team, SumoMe has a three-part tool to help promote your website: Visitors can share text they highlight, they can share images they find, and they can easily sign up for a newsletter. You can see parts of this plugin in action at the OK Dork blog and Andrew Chen’s blog. Here’s a screengrab of what the photo share overlay would look like:Screen Shot 2014 07 14 at 7.13.43 AM 1024x534 730x380 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Price: Free

3. Click to Tweet by CoSchedule

Among the elements that make up a perfect blog post is one that often flies under the radar: Give your readers an easy way to share your best sound bites. The Click to Tweet plugin by CoSchedule accomplishes this in a really beautiful way. Once installed, you can add shareable quotes right inside your blog posts.
Screen Shot 2014 07 07 at 10.55.07 AM 730x271 20 WordPress plugins for easier sharing, better posting and a more powerful blog(Note: CoSchedule also makes a full-featured editorial calendar plugin that integrates nicely with a social media promotion strategy, too.)

4. WooDojo

Built by the team at WooThemes, the WooDojo plugin contains a suite of fun tools that add a bit of flair to your blog. Several of the WooDojo features deal with the WordPress sidebar and widgets, including some fun installations for social widgets and a tabbed content box.
Screen Shot 2014 07 14 at 7.24.17 AM 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Price: Free

5. PlugMatter

A few weeks back, we were itching to put a featured box email signup form on the home page of our blog. Before we found a custom solution, we explored the PlugMatter plugin. With PlugMatter, you simply insert a piece of code at the end of your header.php file, then you can design and customize your featured box right from within the PlugMatter interface inside WordPress.
PlugMatter basic comes with a handful of premade themes, and you can upgrade for even more options.
Price: $37 and up

6. VaultPress

If you’re in the market for daily backups of your blog along with strong security features,VaultPress deserves a look. Built by the WordPress team (so you bet they know their stuff!), VaultPress performs daily backups, simple restores, and constant security scans, and you can monitor all the activity from your ValutPress dashboard.
Price: Starting at $5 per month

7. Jetpack

Another incredibly useful plugin from the WordPress team, JetPack features a bevy of tools all bundled into one plugin.  Many of the 33 tools are the same as those available to the WordPress-hosted blogs. You’ll find things like contact form, related posts, share tools, and single sign on.
Perhaps the most-loved feature of Jetpack is its built-in analytics reporting. You can check your site stats straight from your WordPress dashboard, without having to log in anywhere else.
screenshot 1 730x314 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Price: Free

8. upPrev

Do you remember the little slideup made popular by the New York Times website that showed a link and preview of related content to read next? Well, wouldn’t you know it, someone made it into a WordPress plugin!
The upPrev plugin shows a related content box when a visitor nears the bottom of a post. The related content can be picked however you choose—the previous article, from a certain category/tag, or a completely random article.
Screen Shot 2014 07 14 at 7.50.02 AM 730x419 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Price: Free

9. Custom login

You can use this one for professional branding purposes or just for fun. On my personal blog, it’s completely for fun.
Screen Shot 2014 07 14 at 7.59.39 AM 730x549 20 WordPress plugins for easier sharing, better posting and a more powerful blog
Basically, you can upload any photo and use it as a tiled background on your WordPress login page. Same goes for the WordPress logo, too, if there’s a company logo you’d like to use in place of the WordPress one. Along with photos, you can change typography, styles, and alignment of pretty much every element on the login page.
Price: Free

10. ManyContacts Bar

Much like the Hello Bar, the ManyContacts Bar is an email capture form that sits in a bar at the top of your website. There’re just a couple of differences: The ManyContacts Bar has a bit of animation when it pops onto the screen, there are a couple design differences, and you can set it so that a custom message pops onto the screen after a few idle moments on the page:
Screen Shot 2014 07 14 at 7.56.51 AM 730x554 20 WordPress plugins for easier sharing, better posting and a more powerful blog
All contacts are emailed directly to you and added to one of nine popular email newsletter services, including MailChimp and Aweber.
Price: Free

Pro tip: How to find out a plugin if you don’t know its name

I don’t know about you, but there always seems to come a time when I’m browsing a site and find a feature or tool I absolutely love. How do they do that? I wonder.
Well, if the site you’re browsing runs on WordPress, there are a few simple ways to find out. The sleuthing requires that you know how to look at the source code of a website. To do this, you can press CTRL+U in most browsers or right click and select “View Source.” (Chrome users can select “Inspect Element” to look at a specific piece of code.)
To check to see if a website is using WordPress, look for this tag in the section of the code:
To see the name of a site’s WordPress theme, open the site’s style.css file, and look for this section:
/*
Theme Name: On Topic
Theme URI: http://www.woothemes.com/
Version: 1.1.2
Description: Designed by WooThemes.
Author: WooThemes
Author URI: http://www.woothemes.com
Tags: woothemes
To see the name of a plugin, you can browse a site’s scripts and stylesheets, looking for anything that might include the word “plugin” or similar naming. If there is an element on the page that looks like a plugin, the classes and ids of that element might also contain the plugin name. Here’s a good example from Stack Exchange:
Go through the source code and look for any scripts and stylesheets that might be loaded as well as any unique IDs or class names inserted by the plugins.
Screen Shot 2014 07 18 at 12.17.01 PM 730x88 20 WordPress plugins for easier sharing, better posting and a more powerful blog
and
Screen Shot 2014 07 18 at 12.17.18 PM 20 WordPress plugins for easier sharing, better posting and a more powerful blog
would all be hints that the theme is using a plugin called Socialize. Here’s a screengrab of what the code looks like just below the buttons for our Digg Digg plugin.
Screen Shot 2014 07 14 at 8.06.17 AM 730x330 20 WordPress plugins for easier sharing, better posting and a more powerful blog

Over to you: What are your go-to WordPress plugins?

We rely quite heavily on WordPress plugins to make our job a little easier and to help the Buffer blog run at full capacity.
Which plugins are most helpful to you?
I’d love to hear which ones have helped you supercharge your blog or website. I’m always in the market for new plugin ideas (as you can tell!). If you’ve got one to share, it’d be awesome to hear about it in the comments.