Wordpress - How do I create a Shortcode that returns text if domain is .com, not .co.uk

to read the attribut country, you just need to read it in $atts

add_shortcode( 'ifurl', 'ifurl' );

function ifurl($atts, $content = null) {

 $url =  'https://' . $_SERVER['SERVER_NAME']; 
 $current_tld = end(explode(".", parse_url($url, PHP_URL_HOST)));

 if ($current_tld === $atts["country"]) {
  return $content;
 }

};

While if ($current_tld === $atts["country"]) check will do the job for you when everything is perfect, it has the potential of generating error when your shortcode is either wrongly inserted or incomplete.

For example, check the following two scenarios:

// misspelled contry attribute
[ifurl contry="com"] Show only if .com [/ifurl]
// incomplete shortcode with no country attribute
[ifurl] Show only if .com [/ifurl]

In both these cases, WordPress will call your shortcode function, but your shortcode function will produce error or unexpected result because you haven't handled these.

One way to fix the CODE is to do an isset( $atts["country"] ) check, like this:

if ( isset( $atts["country"] ) && $current_tld === $atts["country"] )

However, an even better way is to first declare the default attributes before processing the shortcode using the shortcode_atts function. For example, the improved CODE could be like:

add_shortcode( 'ifurl', 'ifurl' );

function ifurl( $atts, $content = "" ) {
    $atts = shortcode_atts(
        array(
            'country' => 'com'
        ), $atts, 'ifurl' );

    $url =  'https://' . $_SERVER['SERVER_NAME']; 
    $current_tld = end( explode( ".", parse_url( $url, PHP_URL_HOST ) ) );

    if( $current_tld === $atts['country'] ) {
        return $content;
    }
    return "";
}

With this CODE, we've made the .com site as default, so shortcode given in the following example will give output on .com site, but not on .co.uk site:

[ifurl] Show only if .com [/ifurl]

More importantly, it'll not throw any error.

Additionally, by doing it this way, you open the window to enhance your shortcode attributes to be altered by other plugins using a filter hook named shortcode_atts_{$shortcode_name} (in your case, it'll be shortcode_atts_ifurl).

This is very useful if you want to develop a plugin and want other developers to be able to enhance your plugin easily without having to modify it directly.

Tags:

Shortcode