Content snippet in blog posts with a shortcode

Advertisement:

You’re having the same content snippet on multiple WordPress blog posts and are fed up with making changes to that small piece on each single post? I’m showing you how to create a custom WordPress shortcode that pulls the content from a single post and injects it right into your blog posts.

!This post is seriously aged.The world has moved on and the stuff described in this post might be outdated. Having trouble getting this to work? Leave a comment and I'll have a look into that.

The situation

I used an ad managing plugin for displaying the same content in multiple articles. Basically, those are a series of blog posts that had a table of contents. This table of contents linked to each article in this series. Every time a new article was published to that series, I only had to edit the table of contents once, which was pretty comfortable. The plugin I used was acutally made for displaying ads across multiple (if not all) posts on my blog, so I think it was way too much of what I needed.

The downside of every plugin is that it uses resources and costs pageload time. My Google AdSense ads – that are kind of the same type of repetetive code snippets – can easily be integrated into my template files. To make a long story short: I had no use for that plugin. Or at least my necessity was too small for a plugin that assumably consumes 20% pageload time (as the P3 Plugin Profiler measured). I wanted a simpler and easier solution.

The need: Pulling a content snippet from another blog post

What I needed was the possibility to have small content snippets that can easily be included in multiple WordPress articles – just as if they actually were ads. Those content snippets would always be the same across all posts they are inserted into. If I had to change that snippet for any reason, I didn’t want to have to go through numerous articles to change that content piece but only change it once instead.

The approach

I thought that the use of a shortcode might be a good thing. Shortcodes are easy to use and to understand and allow me as an author to use them anywhere in the blog post. I found this an appropriate way of integrating a content snippet to other blog posts.

Those snippets of repeating content would make good pages. WordPress’ pages are made for content-types that do not regularly update and do not need to have the whole WordPress taxonomy of categories and tags and such. Articles are too fluctuant and there are way too many of them (at least in my blogs). My content snippet wouldn’t properly fit in there – and I’d probably find them never again between all my blog posts.

How to insert a blog post as a content snippet with using a shortcode

Now I will explain to you, how I made this whole shabang work.

Creating the Prerequisites

First of all, create a page called banner. It does not need to have any content, because its only mission is being a parent page to my stuff called banner. Then you can create subpages to banner and copy the desired contents that you want to display in other posts.

Creating the banner parent page was not only an organisational thing. Since WordPress pages’ permalinks are structured by page hierarchy, you can now treat all the subpages as if they were in a folder. I suggest that you edit your robots.txt file and prevent search engines from crawling anything that resides in the /banner/ folder (or wahtever you named your parent page). I did not want Google and any other proper search engine to index those pages, so I added the line

Disallow: /banner/

I also had to think about how I am going to identify the banners as blog posts and how I actually would link them. I decided to use a shortcode with an attribute value, so that I would have to enter [banner id="1"] to access content. But where would you place the id and the information that the current post is supposed to be a banner?

The custom fields box is below every post-editing area.

The custom fields box is below every post-editing area.

I chose to use WordPress’ native custom fields for assigning IDs to the pages that should be included with the banner-shortcode.

Hint: If you don’t see the custom fields box below your page, make sure its visibility is set by ticking the checkbox in your screen options. Read more about custom fields in the WordPress codex.

Now you are ready to start and tweak your functions.php.

The code

Finding the description on how to add a custom shortcode in the WordPress Codex is easy. You simply add the following code to your functions.php – it is customized the way I needed to be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function custom_banner ( $id ) {
	/* Setting up querying for the id and defaults. */
	$atts = shortcode_atts( array(
		'id' => '',
	), $atts );
 
	/* Setting up arguments for WP DB query. */
	$args = array(
		'post_type' => 'page',
		'meta_key' => 'banner',
		'meta_value' => $id
	);
 
	$query = new WP_Query($args);
 
	if( $query->have_posts() ):
		$query->the_post();
		$banner = apply_filters( 'the_content', get_the_content() );
		wp_reset_postdata(); // updated!
		return $banner;
	else :
		wp_reset_postdata(); // updated!
		return;
	endif;
}
add_shortcode( 'banner', 'custom_banner' );

Explanation of the function

The first part of the functions creates (and reads) the attribute id which i chose to identify the banner with. I like using IDs, because they’re usually unique and do not return multiple results – if assigned correctly 😉

The second part of the script sets the arguments for the database query. By these arguments, the query will search for posts that have the custom field name (= meta_key) named banner and where the correspending ID is the same as the attribute used with the shortcode.

The third part of the function gets the posts content and renders it as post. It is necessary to use the get_the_content()-function over WordPress’ the_content()-function. the_content() will not only get the content but immediately echo (= output) it. Therefore using the_content() will make the banner always appear on top of each post. That is probably not what you want.

Since get_the_content() does not render the content – which means that not HTML or other shortcodes or anything is applied – you will have render it “manually” by apply_filters( 'the_content', ...).

Update 2015-12-02

As it turned out, I forgot to reset the postdata. After initiating a new query, WordPress was returning wrong data for pagination, previous and next posts, and author information. This data had ben pulled from the page/banner that was returned with the query. So I fixed that.

Result

After adding the function to your functions.php and creating a subpage to banner with the custom fields name “banner” and the ID 1 (the post title is irrelevant), you can now use the shortcode [banner id="1"] in any blog post and will have the content snippet of that blog post’s content right where you entered the shortcode.

If you have any questions to my solution on how to display static content snippets on multiple blog posts and only maintaining them once with using a shortcode, feel free to ask.

Like this post? Share it!

Advertisement:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>