Check if a WordPress custom image size exists and provide a fallback

Sometimes you want to regenerate thumbnails to new sizes to suit a new theme, or make it retina-ready.

When a custom image size does not exist, WordPress returns the “full size version”.

But what if you want to check if a specific size exists, and fallback to the old resized version.

Let’s say you add a new custom image sizes:

<?php
if ( function_exists( 'add_image_size' ) ) {
   add_image_size( 'small', 100, 100, true ); 
   add_image_size( 'custom_size', 300, 300, true ); // this one is new
}
?>

Then you use the regenerate thumbnails plugin to resize all your images. But this can take a long time, so you might want to provide a fallback in your theme for the duration.

In the loop, check if the size you want exists before output.

Note: This example requires the Advanced Custom Fields plugin but you can modify it for any template.

<?php

// check for custom field
if( $image_id = get_field('field_name', false, false) ): 
    // if there is a custom field value in the database
	
	// get the full size version
	$full_size_image = wp_get_attachment_image_src( $image_id, 'full'); 
	
	// get the one we want
    $custom_size_image = wp_get_attachment_image_src( $image_id, 'custom_size'); 
	
	// check if they are the same
    if (!isset($full_size_image[0]) || !isset($size_we_need_image[0]) || $full_size_image[0] == $size_we_need_image[0]):
        // show the small version as a fallback, or show the full verison if you want
		$show = wp_get_attachment_image( $image_id, 'small' ); 
    else:
        // show the custom version that exists
        $show = wp_get_attachment_image( $image_id, 'custom_size' );
    endif;
    echo $show;
else : 
    // there is no custom field, so let's just grab the featured image for this post
    $image_id = get_post_thumbnail_id();
	
	// get the full size version
	$full_size_image = wp_get_attachment_image_src( $image_id, 'full'); 
	
	// get the one we want
    $custom_size_image = wp_get_attachment_image_src( $image_id, 'custom_size'); 
	
    // check if they are the same
    if (!isset($full_size_image[0]) || !isset($size_we_need_image[0]) || $full_size_image[0] == $size_we_need_image[0]):
        // show the small version as a fallback, or show the full verison if you want
		$show = wp_get_attachment_image( $image_id, 'small' ); 
    else:
        // show the custom version that exists
        $show = wp_get_attachment_image( $image_id, 'custom_size' );
    endif;
    echo $show;
    //echo 'thumb';
endif;
?>

Get a xml feed from a WordPress site using jQuery

To get a xml feed from a WordPress site and add it to a bulleted list:

Add this to the body:

    <ul id="posts"></ul>

Add this to the footer of the page:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
    $(function() {
        
		url = 'http://www.endreywalder.com/blog/rss?'+parseInt($.now());
		$.ajax({
			type: "GET",
			url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
			dataType: 'json',
			error: function(){
				alert('Unable to load feed, Incorrect path or invalid feed');
			},
			success: function(xml){
				values = xml.responseData.feed.entries;
				console.log(values);
				$.each( values, function( i, val ) {
				  console.log(i);
				  console.log(val.link);
				  console.log(val.title);
				  $("#posts").append("<li><a href='"+val.link+"'>"+val.title+"</a></li>");
				});
			}
		});
	
    }); 
    </script>

Add Open Graph Tags to WordPress Theme

In your theme header.php

Change “head” tag to:

<head <?php if (is_single()): ?>prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#"<?php endif; ?>>

And then add meta-tags between the end “head” tag:

<?php 
	if (is_single()):
		while ( have_posts() ) : the_post(); 
			$og_image_attributes = wp_get_attachment_image_src(get_post_thumbnail_id(), 'homepage-image'); // returns an array
			$og_image = $og_image_attributes[0];
?>
			<meta property="og:title" content="<?php echo $post->post_title; ?>"/>
			<meta property="og:type" content="article"/>
			<meta property="og:url" content="<?php echo get_permalink( $post->ID );?>"/>
			<meta property="og:image" content="<?php echo $og_image; ?>"/>
<?php 
		endwhile;
	endif; 
?>

Exclude posts from a WordPress Loop

Sometime you want to exclude posts from the loop.

In this example, I exclude posts that only in sub-categories or posts with a custom field value.

<?php 
	// get a list of categories
	$args = array(
		'type'				=> 'post',
		'hide_empty'		=> 1,
		'hierarchical'		=> 1,
		'taxonomy'			=> 'category',
		'pad_counts'		=> false 
	); 
	$subcategories = get_categories( $args );
	
	// separate a list of parent and sub categories
	$parentcategories_array = array();
	$subcategories_array = array();
	foreach ( $subcategories as $subcategory ) {
		// check if parent category (or any other condition here)
		if ($subcategory->parent == 0)
		{
			$parentcategories_array[] = $subcategory->term_id;
		}
		else
		{
			$subcategories_array[] = $subcategory->term_id;
		}
	}
	$subcategories_list = implode(",",$subcategories_array);	// make this a comma delimited string
	
	// get excluded posts
	// in this case, all posts in a sub category
	$args = array(
		'post_type'        => 'post',
		'post_status'      => 'publish'
		);
	$posts_array = get_posts( $args );
	$excludeposts_array = array();
	foreach ( $posts_array as $post_eval ) {
		// check that it is not also in a parent category and custom field not set to true
		$custom_exclude_from_loop = get_post_meta( $post->ID, 'your-custom-field', true ); // get from custom field types plugin
		if ( !in_category( $parentcategories_array, $post_eval ) || $custom_exclude_from_loop) {
			// They have long trunks...
			$excludeposts_array[] = $post_eval->ID;
		} 	
	}
	
	// get pagination information
	$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
	
	// create new loop with this query
	if ( is_home() ) {
		// This is the  home page
		$args=array(
		  'paged' => $paged,
		  'post__not_in' => $excludeposts_array,
		  'post_type' => 'post',
		  'post_status' => 'publish',
		);
		// run query
		query_posts($args);
	} else if (is_category()) {
		// This is a category page
		$cat_id = get_query_var('cat');	// current category
		$args=array(
		  'cat' => $cat_id,
		  'post__not_in' => $excludeposts_array,
		  'post_type' => 'post',
		  'post_status' => 'publish',
		);
		// run query
		query_posts($args);
	}
?>

<?php if ( have_posts() ) : ?>

etc....

Get the first parent category only from a WordPress post

Add this to your theme functions.php

// get the first parent category only
function get_the_first_parent_category_only($id)
{
	$categories = get_the_category($id);
	$parent_categories = array();
	if($categories){
		foreach($categories as $category) {
			if ($category->parent == 0)
			{
				$parent_categories[] = $category;
			}
		}
	}
	return (isset($parent_categories[0])) ? $parent_categories[0] : false;
}

Then display a category with link like this (in index.php or single.php):

<!-- Print a link to this category -->
$category = get_the_first_parent_category_only(get_the_ID()); 
<a href="<?php echo esc_url( get_category_link( $category_id ) ); ?>" title="<?php echo $category->name; ?>"><?php echo $category->name; ?></a>

Create a responsive WordPress attachment page

Create a new file in your theme folder called “single-attachment.php”.

Replace

with:

<?php 
$image_info = getimagesize($post->guid); var_dump($image_info); 
$imgclass = "";
if ($image_info[0] >  1280) // replace 1280 with your max width
{
	$imgclass = "resposiveattachment";
}
?>
<img class="<?php echo $imgclass; ?>" src="<?php echo $post->guid; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" <?php echo $image_info[3]; ?> />

Add the following CSS to your site:

.resposiveattachment { width:100%!important; height:auto!important;}

Responsive HTML5 video shortcode for WordPress

Here is the code for functions.php

/* HTML5 video shortcode */
function html5_video($atts, $content = null) {
	extract(shortcode_atts(array(
		"webm" => '',
		"ogg" => '',
		"mp4" => '',
		"width" => '',
		"height" => '',
		"poster" => ''
	), $atts));
	$poster = ($poster != "") ? "poster='".$poster."'" : "";
	$height = ($height != "") ? "height='".$height."px'" : "";
	$width = ($width != "") ? "width='".$width."px'" : "";
	$string = "<video ".$poster." ".$width." ".$height." controls autobuffer>";
	$string .= "<source src='".$webm."' type='video/webm; codecs=\"vp8.0, vorbis\"'/>";
	$string .= "<source src='".$ogg."' type='video/ogg; codecs=\"theora, vorbis\"'/>";
	$string .= "<source src='".$mp4."' type='video/mp4; codecs=\"avc1.4D401E, mp4a.40.2\"'/>";
	$string .= "<p>Your browser does not support HTML5 video. Please upgrade.</p>";
	$string .= "</video>";
	return $string;
}

add_shortcode('video5', 'html5_video');

Required CSS:

video {
  width: 100%    !important;
  height: auto   !important;
}

This shortcode…

[video5 webm="movie.webm" ogg="movie.ogv" mp4="movie.mp4" width="720" height="480" poster="movie.jpg"]

…will output:

<video poster="movie.jpg" controls>
        <source src="movie.webm" type='video/webm; codecs="vp8.0, vorbis"'/>
        <source src="movie.ogg" type='video/ogg; codecs="theora, vorbis"'/>
        <source src="movie.mp4" type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'/>
        <p>This is fallback content</p>
</video>

Try this as an example:

[video5 webm="http://www.quirksmode.org/html5/videos/big_buck_bunny.webm" ogg="http://www.quirksmode.org/html5/videos/big_buck_bunny.ogv" mp4="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4" width="720" height="480"]