• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

WP Thinker

The WordPress Playground

  • Snippets
  • Best
  • Guides
  • Reviews
Home / Code Snippets

March 3, 2021 Jayan

Create a WordPress Shortcode

WordPress shortcodes are extremely useful for inserting custom content without having to manually type them in every time. You can basically run almost any PHP code almost anywhere on your WordPress website that supports a shortcode. Below is an example of a code snippet that creates a simple shortcode that outputs the string “Hello World!”. Inside the function, you can place whatever you want as long as it is a working piece of PHP code.

Usage

  • To implement custom functions anywhere on your website without having to edit your template files.
  • Easily organize your code by making them into readable shortcodes which can be inputted in template files as well as inside post content.
  • Add code inside your website where PHP codes are not supported. WordPress will grab the shortcode and run the PHP scripts behind the scenes.
  • You can use shortcodes for almost anything done via PHP. For example, you can add a simple button with styles, or an amazing slider with your post content in it.

Code

// Create a WordPress Shortcode
function wpt_simple_shortcode() {
    echo 'Hello World!';
}
add_shortcode('my-shortcode', 'wpt_simple_shortcode');

Inserting [my-shortcode] will return ‘Hello world!’. You can replace it with any value that you want to call the shortcode.

A word of caution. Make sure that the code inside the function doesn’t have any bugs and runs properly. If not, you will end up with a broken website wherever you inserted the shortcut.

Explanation

  1. Just a comment.
  2. Creating a function wpt_simple_shortcode.
  3. Returning the content of our shortcode. In this example, we are using a simple return echo statement that outputs ‘Hello World!’ wherever you insert the shortcut. You should change it to a working piece of code that you can use inside your WordPress website.
  4. Closing the function.
  5. Adding our shortcode ‘my-shortcode' to run the code inside the wpt_simple_shortcode function using the built-in WordPress function add_shortcode. You should change my-shortcode to whatever you want to type inside the [ and ]. In this example, the shortcode will execute only if you use [my-shortcode] on your website.

Primary Sidebar

Related Articles

Footer

WPThinker-White-Logo

Website

  • About Us
  • Advertise
  • Write for Us
  • Contact Us

Policies

  • Privacy Policy
  • Terms and Conditions
  • Facebook
  • Twitter
  • Pinterest
Copyright © 2025 · WP Thinker
This website uses cookies to serve you better. By continuing to use this website, you agree to our cookie and Privacy Policy.