How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

Once you understand the WordPress shortcodes, they are a very convenient and easy tool to do: get any kind of PHP code anywhere on your site, from your email content to your sidebar and headers. .
WordPress Shortcodes Tutorial

WordPress shortcodes are a very handy tool to execute on one topic: Get PHP code that you can download anywhere on your site.

This article is an in-depth WordPress shortcode tutorial. We cover documents that may be used, when to use, and how to register your password, along with shortCodes of the full personal codes.

If you understand WordPress shortcodes, one thing is easy and easy to use: a customized PHP code of any type that you can display anywhere on your site, from your content to your posts, to your sidebars to tops and traps. Even with Gutenberg, the publisher of WordPress and firmly established at the core of WordPress, brief codes remain one of WordPress’s most beloved software tools – although Gutenberg has explicitly pointed out that shortcuts render them obsolete.

Before we run into code, let’s explore why WordPress shortcodes are continuing to be useful, even in the Gutenberg era.

Gutenblocks vs Shortcodes: Comparison and Tradeoffs

Our WordPress shortcode models have one thing to do: if there is one thing that Gutenberg wanted to kill, using Word Press shortcodes is when creating content.

It’s hard to see why. Quickly, what does editing a code in your desk look like at the front end of your site?

[Table id=”1″]

No idea. (That’s a current shortcode here on WPShout, by the way.) The Gutenberg team uses the nasty but accurate term “mystery meat” for the exact type of user experience that shortcodes provide.

If “Mystery Meat” is the problem, Gutenberg’s live preview blocks are the cure:

How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

So should we stop registering for personal shortcodes? Did I stop using WordPress in my work environment? Heck no! Registering personal WordPress shortcodes I find myself on almost every personal site or clients I build, and I don’t plan to slow down.

Shortcodes are very useful. Which thing do you use for them.

The truth is that WordPress shortcodes are massive and useful. Which thing do you use for them. And start to know the relative benefits of registering WordPress Shortcodes versus the Gutenberg Block to create a personal function on your WordPress site.

ADVANTAGES OF GUTENBLOCKS

We’ve already seen the advantages of Gutenberg blocks compared to shortcodes in the screenshots above:

  1. Everything in a Gutenblock is in a clean visual user interface—no [this_is_really_confusing right=”yes”] pseudocode that most site owners will be rightly scared to touch.
  2. Gutenblocks are live-previewing—no mystery meat.

Gutenberg blocks are a better user experience than shortcodes.

In other words, Gutenberg blocks have a better user experience than in shortcode. If you’re building something that the user needs to be able to share content and post content, any bonus blocks are a better bet.

ADVANTAGES OF WORDPRESS SHORTCODES

What we haven’t discussed yet are the pros of WordPress shortcodes relative to Gutenblocks, and there are quite a few:

  • Shortcodes can go anywhere, post content, yes, but even web pages contain content anywhere on your site (headers, sidebars, footers…). You can also run it literally anywhere – in the theme template file, in the plugin – with the WordPress do_shortcode() function. Good blocks are limited to content only.
  • Shortcodes are much easier to register than good blocks. For one thing they are PHP-only, while Gutenblocks are PHP and JavaScript. Registering a simple shortcode is super easy and takes a unique task, as you can see in the custom WordPress shortcode examples below.
  • Shortcodes can be anything: only a small blip of inline text, or a huge closure of PHP code execution. Gutenblocks have a stack on top of other Gutenblocks so they can’t be inline.

Shortcodes are an awful experience for nontechnical users. But for developers, they’re super-useful because they get your code on the page with minimum effort.

In summary, the problem with shortcodes is that they are a horrible experience for users who have no technical knowledge. But for developers, they are one of the most useful tools available – both during the development process itself and on production sites – because they help you get your code on the site with an absolute minimum of effort.

In this article, we’ll make sure you know how to use add_shortcode() to register custom WordPress shortcodes, with passing arguments and content when needed. Then we will discover some examples that show how WordPress shortcodes are massively useful for all kind of WordPress development needs.

Must Read:

How to create WordPress Website in only 3-4 hours

How to add FAQ schemas in WordPress website

How to Create WordPress Shortcodes

As a WordPress developer, you definitely want to know how to register your personal shortcodes. The tutors in this section will walk you through that process.

How to Resister a custom ShortCode: The Most Basic Example

This blog is a Quick Guide covering the most basic possible use of add_shortcode() to register a custom shortcode. That tutorial also covers how to register a plugin to hold the custom shortcode itself (which is better than using your theme’s functions.php).

Without that plugin boilerplate at the top, the code example looks like this:

add_shortcode( 'wpshout_sample_shortcode', 'wpshout_sample_shortcode' );
function wpshout_sample_shortcode() {
    return 'hi!';
}

Notice a few things:

  • You use add_shortcode() to register a new shortcode.
  • You name your shortcode whatever you want using the first argument of add_shortcode(). You’d put the shortcode we just registered onto the page with [wpshout_sample_shortcode].
  • With the second argument of add_shortcode(), you name a shortcode handler function. This function will be used to “handle” the shortcode: what that means is that it will return a text string that WordPress will then output onto the page. In this case, the function wpshout_sample_shortcode() simply returns “hi!”—which is what will appear on the page anytime[wpshout_sample_shortcode] is called.

This very simple shortcode setup is most of what we’ll be using in the examples below, but for completeness it’s also important to show you how to create shortcodes with content, and shortcodes that take passed-in arguments.

Custom ShortCode: How to create and flow in attributes

It’s also good to know how to create WordPress shortcodes that accept user-specified data. Here’s a shortcode with two new elements: a user-definable align attribute, and user-defined content inside the shortcode itself.

[pullquote_shortcode align="left"]This is the text that should 
go inside my pullquote[/pullquote_shortcode]

What do we do with this new data? By default, the shortcode handler function can have two arguments:

  • A set of attributes
  • The text content in the shortcode.

Adding these to our handler function allows us to work with them, as in this example:

// Alternate website of coding learning 
// $attributes is an array of passed-in attributes. It would look like
// [ 'align' => 'left' ].
// $content is a string of passed-in shortcode content. It would look like
// 'This is the text that should go inside my pullquote'.
function pqsc_process_shortcode( $attributes, $content = null ) {
	// Save each attribute's value to its own variable.
	// This creates a variable $align with a value of 'left'.
	extract( shortcode_atts( array(
		'align' => ''
	), $attributes ) ); 
	
	// Return a string to display on the page
	return '<blockquote class="pullquote align' . $align . '">' . $content . '</blockquote>';
}

The hardest thing here is the combination of the PHP Standard Extract Function Extract () and WordPress Shortcode_atts () PHP function.

shortcode_atts()

shortcode_atts () is a WordPress-powered function that combines an array of defaults with the array of passions that pass into the function itself. It essentially says that the alignment attribute has a default value, an empty string – and that the default value can be suppressed by any alignment element in the step $attribute array. For us that value ‘left’.

extract()

The extract() is a PHP function that takes every ordered element and creates a similarly named variable from it. So in the above example, now $align the specified string variable with the value ‘left’. If we had other past attributes, they would also be variable.

Use extract() with care because of the danger of duplicate variable names.

By the way, make sure that your Extract() function does not return any variables of the same name! So do not mention any of your shortcode arguments, say, post if you plan to use extract (). Because of this potential confusion, extract () is not the most secure PHP function overall, but boy is it convenient in this case. So fair warning.

That’s a Fancy Shortcode

This is about as rich in options as getting WordPress shortcodes, so if you understand the shortcode tutorial above, you are pretty much set on the tech page to register your own shortcodes personalized. Now, what can we do to start WordPress with WordPress shortcodes?

Shortcode Examples: Outputting PHP Code During Development

One reason why I like shortcodes is because they get me everything I do in PHP right to the page. They are great for testing code, understanding what a function or variable does, and all the other places of visibility. And if you are used to registering and using shortcodes, they may have less setup than any other sensible way of displaying your code.

Shortcodes let me get anything I’m doing in PHP directly onto the page.

Below are examples of the matter. Note that in these examples I am using PHP buffer output: write out David’s excellent article on why output buffer is so convenient to shortcodes:

SHORTCODE EXAMPLE: USING A SHORTCODE TO TEST A WP_QUERY

Let’s say I’m writing a WP_Query and I want to know what it’s outputting:

add_shortcode( 'dump_query', 'wpshout_dump_query' );
function wpshout_dump_query() {
	// Write query
	$args = array(
		'posts_per_page' => 1
	);
	$query = new WP_Query( $args );

	// Return output
	ob_start();
	var_dump( $query );
	return ob_get_clean();
}

Then I just write [dump_query] anywhere, in any sample post or page on my site:

How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

And I get something—an error, an array, or whatever—right in the page content:

How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

SHORTCODE EXAMPLE: SEARCHING COMMENT TEXT

Say I’m willing to search through the last ten comments of an acceptable site:

add_shortcode( 'get_recent_comments', 'wpshout_get_recent_comments' );
function wpshout_get_recent_comments() {
	$args = array(
		'status' => 'approve',
		'number' => '10'
	);
	$comments = get_comments($args);
	
	ob_start();
	foreach($comments as $comment) :
		echo $comment->comment_content . '<hr>';
	endforeach;
	return ob_get_clean();
}

With [get_recent_comments] on the page, that gives us:

How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

SHORTCODE EXAMPLE: DISPLAY ALL RECENT MEDIUM-SIZED IMAGES

Wait, I need to inspect (and perhaps save in a folder) the “average” size of all images of the last 50 images;

add_shortcode( 'rec_images_medium', 'wpshout_rec_images_medium' );
function wpshout_rec_images_medium() {
	$query_images_args = array(
		'post_type'      => 'attachment',
		'post_mime_type' => 'image',
		'post_status'    => 'inherit',
		'posts_per_page' => 50,
	);
	$query_images = new WP_Query( $query_images_args );

	ob_start();
		foreach( $query_images->posts as $image ) :
			echo wp_get_attachment_image( $image->ID, 'medium' );
			echo '<hr>';
		endforeach;
	return ob_get_clean();
}

The result with [rec_images_medium] on the page:

SHORTCODE : DISPLAY ALL RECENT MEDIUM-SIZED IMAGES

Shortcodes are great for getting just the content on the page

Do you see what I like about shortcodes? These use cases are the kind of random needs that can appear on the PHP page of any WordPress project, and in any case, registering a shortcode was a very simple, easy way to turn my PHP code into something visual with which I could work on and get feedback from. In general, shortcodes are one of the easiest and lightweight-best ways to get a WordPress developer stuff – any stuff – to display on the page so you can use it, debug, test, tweak, and so on. . And you know exactly where to expect it on the page because you set the shortcode yourself.

Shortcodes are one of the easiest and most lightweight ways to display content on a page during development.

So if you don’t know how to get your code on the page, don’t reach custom page templates, the_content filters, or anything else. Arrive for a short code.

Our WordPress Articles to help you out :

WordPress Real-Life Short Code Example: Use shortcode in production sites

Gutenberg or not, I still use shortcodes on client projects all the time.

As we discussed above, shortcodes are ideal if the relevant section of the site is only being updated by a technical person. This is often the case with client sites: most clients want to edit their pages and publish content, but they are more likely to call you rather than try, e.g. to change footers on their site.

I use custom shortcodes on personal and client sites all the time.

Also, there are a number of cases that occur in real-world WordPress site projects; for example when you need your custom code inline (in the middle of a text stream) or when you save custom code to go both. page content and potentially in widget areas or elsewhere on the site—what a shortcode can do what a Gutenblock can’t.

It’s just for commercially released products, or projects that will be managed by many less-technical people, that shortcodes are not usually a good choice.

Below, we will take a look at some real-life examples of short codes on live production pages. You can see that the shortcuts are still very convenient. Short codes are not a good choice for commercial products or group-managed projects, but for many small technical people.

WordPress Shortcodes in Post on content site

I help manage the Writers.com website, which sells online writing courses. At any time, some courses are planned, and some are not, except for the call on each course page.

We have written a short code to serve the right call-to-action, like calling in a second short code that records HTML for unplanned courses. Here is the code:

add_shortcode( 'conditional_enroll_button', 'writers_conditional_enroll_button' );
function writers_conditional_enroll_button() {
	global $post;
	
	// Get unix time of event
	$end_datetime = new DateTime(
		get_post_meta( get_the_ID(), '_event_end_date', true )
	);

	// A class should display until its end date has passed (is after yesterday)
	$class_is_joinable = $end_datetime > new DateTime( 'yesterday' );
	
	
	ob_start();
	
	if( $class_is_joinable ) : ?>
		<div class="enroll-button"><input type="button" style="padding: 5px;" onclick="location.href='https://www.writers.com/regform.html?course_id=<?php echo $post->ID; ?>'" value="Enroll »"></div>		
		
	<?php else :
		// See "Interested" plugin
		echo do_shortcode( '[single_unscheduled_interested]' );
	endif;
	
	return ob_get_clean();
}

Here’s the shortcode in post content

How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

A WordPress ShortCode that adds many functions

WordPress shortcuts are often small, but can be large – don’t forget, this site is a way to add any PHP you want. One of the biggest in real life is the wpshout_homepage_scroll short code that you use on the WPShout homepage, which runs the “Recently Published” section of the homepage:

How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

This code is short code containing a few hundred lines in our argument function.php file:

How to Create Shortcodes & Why They Are Useful: WordPress Shortcode Tutorial

Beaver Builder is always a great plugin to use because of the complexity of the site. The question then is: how do we get this complex custom code to our page? There’s no better answer than using that short code again

  • No direct review or other features of Gutenberg are needed.
  • We just need a simple cover for our complicated normal operation.
  • There is no definite “border” to enter it; the code should go to the middle of something, in this case the middle of the mail content.
  • Not just developers, but creators who are making changes to this section.

WordPress Version: good for good

Shortcuts are not great for users, but man, I consider them convenient as a creator. With or without user-defined information, I hope you have a better understanding of how to create traditional WordPress shortcuts and why and when to use them in your WordPress work.

What did I send? We want to hear from you in the comments below

Total
0
Shares
9 comments
  1. Hey there! This is my first comment here so I just wanted to give
    a quick shout out and say I truly enjoy reading your articles.

    Can you recommend any other blogs/websites/forums that deal with the same subjects?
    Appreciate it!

  2. After I originally commented I appear to have clicked on the -Notify me when new comments are added- checkbox and from
    now on each time a comment is added I receive four emails with the same comment.
    Is there an easy method you can remove me from that service?

    Kudos!

  3. I’m not sure why but this web site is loading incredibly slow for me.
    Is anyone else having this issue or is it a issue on my end?
    I’ll check back later on and see if the problem still exists.

  4. I am now not sure where you are getting your info, but great topic.
    I must spend some time finding out more or figuring out more.
    Thanks for magnificent info I was in search of this info
    for my mission.

  5. You could certainly see your expertise within the article you write.

    The sector hopes for more passionate writers like you who
    are not afraid to say how they believe. At all times
    go after your heart.

  6. This is really interesting, You’re a very skilled blogger.
    I have joined your feed and look forward to seeking more of
    your magnificent post. Also, I have shared your site in my social
    networks!

Leave a Reply

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

Previous Post
How to Monetize Your Blog with Low Traffic

How to Monetize Your Blog with low Traffic?

Next Post
How-did-Websites-work

How did Websites work?

Related Posts
fastest-wordpress-themes

15 Fastest WordPress Themes in 2021 (Based on real Data)

Speed is an important factor in building ongoing customer engagement and can have a significant impact on your engagement. If you want to get high rankings in Google, a complete website is also important. Fortunately, there are many easy WordPress themes to help you achieve your goals
Read More
Total
0
Share