Create Shortcode in WordPress


The Shortcode is the simple custom functions in WordPress. You can use shortcodes in posts and pages. Here I am continuing with the last post on creating plugins.

Write down the following code in functions.php file inside your custom plugin folder.

function printHelloWord(){
    return "<p>".Hello World!."</p>";

add_shortcode("hello-world", "printHelloWord");

Here we have created a shortcode named “hello-world”. its function defenition is in printHelloWord function.

on WordPress Pages and WordPress Posts, you can use this shortcode like below. It will simply echo “Hello World!”.


if you want to interact with a database you can use following reference code.

Use one of three defined constants. Default is OBJECT
1: - OBJECT - the result will be output as an object.
2: - ARRAY_A - the result will be output as an associative array.
3: - ARRAY_N - the result will be output as a numerically indexed array.

add_shortcode(getOptionValue, function($params){
    global $wpdb;
    $id = $params["id"];
    $res = $wpdb->get_results('select * FROM wp_options WHERE option_id = '$id limit 1;', ARRAY_A );
    return "<p>".$res["option_name"]."</p>";

Usage is like

[getOptionValue id=1]

Here we are passing params to our shortcode you can also pass more params as per your need. There are multiple options available for output type of query like here ARRAY_A.