A shortcode to show the site title in WordPress

This is a simple yet useful shortcode for displaying the title of your WordPress site. It is useful when you do not want to hardcode the title. It retrieves the value specified in Settings > General > Site Title.

Usage

[hx_site_name]

Note: you can change the prefix when you setup the shortcode.

Shortcode

// This shortcode returns the name of the WordPress site, as defined
// in Settings > General > Site Title. To use a different prefix, replace
// all instances of hx_ with the prefix of your choice. Be sure to update
// this function and the add_shortcode call.
function hx_site_name_shortcode() {
    // Use get_bloginfo to get the site title from the WordPress settings
    return get_bloginfo('name');
}

// Register the function to handle the shortcode. The first parameter
// is the name of the shortcode. The second parameter is the function
// that handles the shortcode.
add_shortcode('hx_site_name', 'hx_site_name_shortcode');

How it works

This code follows the standard pattern of defining a shortcode. The add_shortcode function takes two parameters: the name of the shortcode, and the function that is called when the shortcode is rendered.

The function calls get_bloginfo with ‘name’ as a parameter. The get_bloginfo function returns information about the current site including its title, tagline, admin email, and so on. When ‘name’ is specified, the function returns the value as entered in Settings > General > Site Title.

How to use

To manually install this shortcode, you can add it to functions.php in your theme. However, this is dangerous and we recommend using a plugin that allows you to create and manage custom bits of code without changing your theme files. Two plugins we recommend are Code Snippets and WPCode. Both have free versions that allow you to create custom shortcodes.

Reference

License

Feel free to remix this content for your website.

Licensed under CC BY 4.0

Leave a Reply