Code Monkey home page Code Monkey logo

get-the-image's Introduction

Get the Image

Get the Image is a plugin that grabs images for you. It was designed to make the process of things such as adding thumbnails, feature images, and/or other images to your blog much easier, but it's so much more than that. It is an image-based representation of your WordPress posts.

What the plugin does

This plugin was made to easily get an image related to a post. This is the default method order in which the plugin attempts to grab an image.

  • Meta key (custom field).
  • Post thumbnail (WP featured image).
  • Image attachment.
  • Image embedded in the post content.
  • Default/fallback image.

Usage

The basic function call for the plugin is like so:

<?php get_the_image(); ?>

This is the only function you should use from the plugin. It expects to be called within the WordPress posts loop unless you pass it a post ID directly (post_id argument).

To do more with the image script, you'll need to use what's called function-style parameters. The following is a basic example of using function-style parameters.

<?php get_the_image( array( 'meta_key' => 'thumbnail', 'size' => 'thumbnail' ) ); ?>

Parameters

The get_the_image() function accepts a single parameter of $args, which is an array of parameters for deciding how to load an image. The following is the list of all the default arguments.

$defaults = array(

	// Post the image is associated with.
	'post_id'            => get_the_ID(),

	// Method order (see methods below).
	'order'              => array( 'meta_key', 'featured', 'attachment', 'scan', 'scan_raw', 'callback', 'default' ),

	// Methods of getting an image (in order).
	'meta_key'           => array( 'Thumbnail', 'thumbnail' ), // array|string
	'featured'           => true,
	'attachment'         => true,
	'scan'               => false,
	'scan_raw'           => false, // Note: don't use the array format option with this.
	'callback'           => null,
	'default'            => false,

	// Split image from post content (by default, only used with the 'scan_raw' option).
	'split_content'      => false,

	// Attachment-specific arguments.
	'size'               => has_image_size( 'post-thumbnail' ) ? 'post-thumbnail' : 'thumbnail',

	// Key (image size) / Value ( width or px-density descriptor) pairs (e.g., 'large' => '2x' )
	'srcset_sizes'       => array(),

	// Format/display of image.
	'link'               => 'post', // string|bool - 'post' (true), 'file', 'attachment', false
	'link_class'         => '',
	'image_class'        => false,
	'image_attr'         => array(),
	'width'              => false,
	'height'             => false,
	'before'             => '',
	'after'              => '',

	// Minimum allowed sizes.
	'min_width'          => 0,
	'min_height'         => 0,

	// Captions.
	'caption'            => false, // Default WP [caption] requires a width.

	// Saving the image.
	'meta_key_save'      => false, // Save as metadata (string).
	'thumbnail_id_save'  => false, // Set 'featured image'.
	'cache'              => true,  // Cache the image.

	// Return/echo image.
	'format'             => 'img',
	'echo'               => true,

	// Deprecated arguments.
	'custom_key'         => null, // @deprecated 0.6.0 Use 'meta_key'.
	'default_size'       => null, // @deprecated 0.5.0 Use 'size'.
	'the_post_thumbnail' => null, // @deprecated 1.0.0 Use 'featured'.
	'image_scan'         => null, // @deprecated 1.0.0 Use 'scan' or 'scan_raw'.
	'default_image'      => null, // @deprecated 1.0.0 Use 'default'.
	'order_of_image'     => null, // @deprecated 1.0.0 No replacement.
	'link_to_post'       => null, // @deprecated 1.1.0 Use 'link'.
);
  • post_id - The ID of the post to get the image for. This defaults to the current post in the loop.
  • order - Order of methods used to grab images. Defaults to array( 'meta_key', 'featured', 'attachment', 'scan', 'scan_raw', 'callback', 'default' ).
  • meta_key - This parameter refers to post meta keys (custom fields) that you use. Remember, meta keys are case-sensitive (defaults are Thumbnail and thumbnail). By default, this is an array of meta keys, but it can also be a string for a single meta key.
  • featured - This refers to the the_post_thumbnail() WordPress function. By having this set to true, you may select an image from the featured image meta box while on the edit post screen.
  • attachment - The script will look for images attached to the post (set to true by default).
  • scan - If set to true, the script will search within your post for an image that's been added.
  • scan_raw - If set to true, the script will search within your post for an image and pull the raw HTML for that image.
  • callback - A custom callback function that will be called if set. It's only called if no images are found by any other options of the plugin. However, it will be run before the default is set. The $args array is passed to the callback function as the only parameter.
  • default - Will take the input of an image URL and use it if no other images are found (no default set).
  • split_content - Whether to split the raw HTML of the found image from the post content. Default is false. This method is only used with the scan_raw method.
  • size - This refers to the size of an attached image. You can choose between thumbnail, medium, large, full, or any custom image size you have available (the default is thumbnail or post-thumbnail if theme has set a thumbnail size).
  • link - What to link the image to. 'post' (links to the post), 'file' (links to the image file), 'attachment' (links to the attachment page if image is attachment), or false (link to nothing).
  • link_class - Add a custom HTML class to the link.
  • image_attr - Array of image attributes (key is the attribute name, value is the attribute value).
  • image_class - You can give an additional class to the image for use in your CSS.
  • width - Set the width of the image on output.
  • height - Set the height of the image on output.
  • before - HTML to place before the output of the image.
  • after - HTML to place after the output of the image.
  • min_width - Minimum width of the image to get. This won't work with the scan* methods. Defaults to 0.
  • min_height - Minimum height of the image to get. This won't work with the scan* methods. Defaults to 0.
  • caption - Whether to display the image caption if it exists. Defaults to false.
  • meta_key_save - A meta key to save the image URL as. This is useful if you're not using custom fields but want to cut back on database queries by having the script automatically set the custom field for you. By default, this is set to false.
  • thumbnail_id_save - Whether to save the attachment ID as the post thumbnail (featured image) ID if no featured image is set for the post. By default, this is set to false
  • cache - Whether to use the WordPress Cache API (integrates with caching plugins) to serve the post images. By default, this is set to true.
  • format - What format to return the image in. If set to array the return value of the function will be an array of <img> attributes. All other values will return the <img> element.
  • echo - If set to true, the image is shown on the page. If set to false, the image will be returned to use in your own function. (Set to true by default.)

Some usage examples

Example 1

Let's suppose that you want to add thumbnails to your category archive pages. What you'll need to do is open your category.php file and add this code within the Loop:

<?php get_the_image(); ?>

By default, that will look for an image with the custom field key Thumbnail and thumbnail. If that image doesn't exist, it will check if a post image has been set. If that image doesn't exist, it will search for any images attached to your post.

Example 2

Let's suppose you want a full-sized image and maybe you want to grab it by a custom field key of feature. Depending on your theme, this will need to go within the Loop in whatever file is calling the featured article.

<?php get_the_image( array( 'meta_key' => 'feature', 'size' => 'full' ) ); ?>

If no feature image exists by custom field, it will look for images attached to your post.

Example 3

If you want to have a sort of fallback image, then you can set an image for the script to default to if no other images are found.

<?php get_the_image( array( 'default' => 'http://mysite.com/wp-content/uploads/example.jpg' ) ); ?>

Example 4

You can even make the script scan for images that have been added to your post with this:

<?php get_the_image( array( 'scan' => true ) ); ?>

Example 5

Saving an image to the thumbnail custom field automatically.

<?php get_the_image( array( 'meta_key_save' => 'thumbnail' ) ); ?>

A real-world example

This is an example Loop, which may differ slightly from your theme, but the concept is the same. The call to get the image can go anywhere between the opening and closing lines. In the following example, the image will appear before the post title.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

	<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

		<?php get_the_image( array( size' => 'medium', 'image_class' => 'feature' ) ); ?>

		<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

		<div class="entry-summary">
			<?the_excerpt(); ?>
		</div>

	</div>

<?php endwhile; endif; ?>

Protect yourself from errors in the future

Sometimes, we stop using plugins, but we forget to remove the function calls to the plugin in our theme files. When deactivated, this causes errors. To protect yourself from these errors, you can call the image script like this:

<?php if ( function_exists( 'get_the_image' ) ) {
	get_the_image();
} ?>

Basically, this just checks to see if the plugin is activated and has loaded the appropriate function.

Styling your images

The plugin will help you style your images by giving you some CSS classes to work with. It will turn your custom field keys and default size into CSS classes. You can also choose to input your own class.

By default, you can add this to your CSS:

img.thumbnail {}

Let's suppose you've used this code:

<?php get_the_image( array( 'meta_key' => array( 'Donkey Kong', 'mario' ), 'size' => 'full' ) ); ?>

This will give you these CSS classes to work with:

img.full {}
img.donkey-kong {}
img.mario {}

You can also input a custom CSS class like so:

<?php get_the_image( array( 'image_class' => 'custom-image' ) ); ?>

You will still have the size and meta_key classes plus your additional class:

img.custom-image {}
img.thumbnail {}

Support

I run a WordPress community called Theme Hybrid, which is where I fully support all of my WordPress projects, including plugins. You can sign up for an account to get plugin support for a small yearly fee.

I know. I know. You might not want to pay for support, but just consider it a donation to the project. To continue making cool, GPL-licensed plugins and having the time to support them, I must pay the bills.

Copyright and License

Get the Image is licensed under the GNU GPL, version 2 or later.

2008 – 2017 © Justin Tadlock.

get-the-image's People

Contributors

justintadlock avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

get-the-image's Issues

Quirky 'Scan' situation

I can only get 'scan' => true to grab an image if it is a new image uploaded for the post. If I'm adding an existing image (that's been used before) to a post, nothing shows.

Is this normal or am I doing something wrong?

Error finding Image when using switch_to_blog

Hi,

I believe I may have found a bug in get_the_image. I have a multisite blog and on one custom template I'm using the switch_to_blog() function to get content from another site in the network. For whatever reason get_to_image is looking somewhere else for the image in this instant.

For example on the site with the post and original image it links to:
http://site1.beegoodmarketing.com/files/2012/10/fredhutchinson_logo.jpg

However within switch_to_blog it links to:
http://site1.beegoodmarketing.com/wp-content/blogs.dir/2/files/2012/10/fredhutchinson_logo.jpg

A few issues with this are 1) I'm using a custom wp-content folder ie "core" and second the logo in the folder isn't accessible.

Project overhaul - Must read for developers

I'm rewriting this entire project as a new script called Hybrid Carbon. You can find the repo here: https://github.com/justintadlock/hybrid-carbon

Get the Image (GTI) has served as both a standalone plugin and drop-in script for theme authors over these past 10+ years now. But, that's been a bit of a maintenance headache for me. Therefore, the Hybrid Carbon project was born.

Hybrid Carbon is going to be the actual code behind both the GTI plugin and the drop-in script for theme authors.

It will eventually be made available as a Composer package. GTI will load it as a dependency, of course. And, theme authors can make it a dependency for their themes if needed.

This was a decision I needed to make to help move this project forward.

I'll be rolling out Hybrid Carbon as a theme drop-in within a few months. It could be early 2019 before I start adding it to the plugin. This ticket is meant to serve as an early heads up.

GTI will definitely still be living on as a plugin. I'm just organizing things a bit better, more or less.

Please do check out the new project and provide any feedback.

how can I set the default fallback image

how can I set a default fallback image if my post dosent have any kind of images attached to it, I want to show a particular default image. How can I achieve that?

WP Retina 2x

Hello,
Have anyone made this plugin/function compatible with WP Retina 2x plugin?

Correct readme link in FAQ

The FAQ in the readme.txt links to the Breadcrumb Trail repo's readme.md. Need to point it to this repo.

get_the_image: Non-Existing or invalid featured image meta not handled

This got posted in the issue tracker for a different repo. Just posting it here. CC: @kraftner

Reference: themehybrid/hybrid-core#121


When you have a featured image assigned to a post (thumbnail_id) that doesn't actually exist get_featured_image() or better more generally _get_image_attachment should handle that.

This can easily happen e.g. with the WP importer. The problem is that no other method is tried afterwards which e.g. means that you end up with nothing although a default image is defined.

image_attr don't add attr

I try to add atribut to my image:

          get_the_image( array(
                    'meta_key' => 'Large',
                    'size' => 'large-img',
                    'link_to_post' => false,
                    'image_attr' => array(
                        'data-pin-nopin' => 'true',
                      ),
                    ));

but there's no effect. My image still don't have data-pin-nopin: 'true'

Class on anchor wrapper

There's an attribute for adding a class to Get The Image, but no way to customize the anchor tag wrapper. It'd be nice to have a class there: https://github.com/justintadlock/get-the-image/blob/master/get-the-image.php#L712

Twenty Fifteen uses what I think is a relative standard 'post-thumbnail' class on the anchor tag or featured image wrapper (archive vs singular): https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentyfifteen/inc/template-tags.php#L196

I'd be up for just making that a class. But otherwise, at least an attribute to the args to be able to customize this?

I often have to not link to post via an attribute and then manually build this wrapper however I want it, which seems silly when a class could be what I need.

Tracking images

When people use 3rd party services such as Amazon Affiliates they often have a tracking image which is a transparent 1x1 image. It there are no other images on the post get-the-image can end up picking up that image and it get's displayed as the thumbnail.

Example

<img src="http://ir-uk.amazon-adsystem.com/e/ir?t=bagpussandfri-21&amp;l=as2&amp;o=2&amp;a=B00EE6C47I" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />

To exclude these perhaps a filter could be used passing the URL as a parameter. Then users could specifically exclude these by returning false when there was a URL they did not want to include?

PHP 7.3 compatibility

Under PHP 7.3, the method for generating the cache key throws PHP Notices:

[28-Nov-2019 10:33:03 UTC] PHP Notice:  compact(): Undefined variable: post_id in /path/to/get-the-image.php on line 307
[28-Nov-2019 10:33:03 UTC] PHP Notice:  compact(): Undefined variable: order in /path/to/get-the-image.php on line 307
[28-Nov-2019 10:33:03 UTC] PHP Notice:  compact(): Undefined variable: meta_key in /path/to/get-the-image.php on line 307
[28-Nov-2019 10:33:03 UTC] PHP Notice:  compact(): Undefined variable: featured in /path/to/get-the-image.php on line 307
etc etc

The code responsible for this is:

$key = md5( serialize( compact( array_keys( $this->args ) ) ) );

The resulting cache key is always the same no matter what the post_id meaning the cache is polluted and therefore unusable. The modifications in #9 solve this, but that PR is stale.

Edge case?

This is a very handy plugin, thanks. But would you have any idea why the first image in this post wasn't used in the homepage? I had to set it as the featured image to get it to work. I haven't had this problem before so it's strange.

The HTML:

<p dir="ltr" style="text-align: center;"><a href="http://engineroom.teamwork.com/wp-content/uploads/2014/01/Teamwork_Launch_105-1280x852-800x533.jpg"><img class="size-full wp-image-3184 aligncenter" alt="J" src="http://engineroom.teamwork.com/wp-content/uploads/2014/01/Teamwork_Launch_105-1280x852-800x533.jpg" width="800" height="533" /></a></p>

I just noticed that the previous post has strange behaviour too. There is no featured image set and the second image is being pulled out.

HTML for the first image:

<p dir="ltr"><img class="alignnone size-full wp-image-3153" alt="Teamwork for Chrome" src="http://engineroom.teamwork.com/wp-content/uploads/2014/01/1.png" width="1280" height="800" /></p>

HTML for the second image:

<p dir="ltr">Getting started is easy - all you need to do is install our extension on the <a href="https://chrome.google.com/webstore/detail/teamwork-for-chrome/okekkfbjgdmfmogicbhdechdmkfhfphc">Chrome Web Store</a>, navigate to any page and add your account with your <a class="underline" href="http://docs.teamwork.com/article/392-article">API key</a>. For this to work, all you need to do is click the Teamwork icon in your extensions toolbar and click “Settings”.</p>
<img class="alignnone size-full wp-image-3152" alt="Teamwork for Chrome" src="http://engineroom.teamwork.com/wp-content/uploads/2014/01/5.png" width="640" height="400" />
<p dir="ltr">If you ever forget how it’s done - don’t worry, we’ve got the instructions built into the extension.</p>

The only different I can see is that the image in this case is not in a paragraph


No custom fields are set. Wordpress 3.8.1.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.