Content MarketingMobile and Tablet MarketingSocial Media & Influencer Marketing

WordPress: A Shortcode to Add a Share on X Link With Your Content in WordPress

Capturing and directing relevant traffic to your website is more crucial than ever. Social media platforms like X (formerly Twitter) have evolved from simple microblogging tools to dynamic hubs for real-time conversations, breaking news, and vibrant community engagement. With over 450 million monthly active users, X represents a goldmine of potential traffic for your brand. Leveraging this platform effectively can amplify your content’s reach and establish meaningful connections with your target audience.

Why Focus on X?

Since its inception, X has become a go-to platform for consumers and businesses seeking immediate insights and trending topics. The platform’s unique real-time nature makes it an ideal source of highly relevant B2C and B2B traffic—users often turn to X to explore products, services, and ideas they’ve just discovered. Whether running a blog, an e-commerce site, or a service-based business, strategically encouraging visitors to share your content on X can significantly expand your audience, build social proof, and increase your online authority.

This is where creating a seamless, user-friendly sharing option, like a custom Share on X button, can work wonders. Users can broadcast your content to their followers with just a single click, sparking engagement and drawing attention to your brand. This approach doesn’t just generate traffic; it fosters organic, authentic interactions that convert casual browsers into loyal advocates.

WordPress Shortcode

By implementing a simple shortcode on your WordPress site, you can streamline this process, giving your audience the tools they need to share your content effortlessly. Let’s explore how to set this up and turn your X presence into a powerful traffic engine. Here’s the output:

How to create a Share on @X shortcode in WordPress

For my site, I have a specific style associated with the blockquote so I’ve added my blockquote class to the attribute in the shortcode:

[tweetthis via="martech_zone" class="wp-block-quote quote-solid quote-solid is-layout-flow quote-solid-is-layout-flow"]How to create a Share on @X shortcode in WordPress![/tweetthis]

Within the output, I have a class on the anchor tag, twitter-button. I’ve added the following styling to my theme’s stylesheet:

.wp-block-quote quote-solid .twitter-button {border-radius: 10px; background-color: #000; color: #fff; padding: 4px 8px; margin-bottom: 8px}
.wp-block-quote quote-solid .twitter-button:hover { color: #fff; }

How To Implement this Share on X Shortcode

Adding custom code like a shortcode to your theme’s functions.php file is common, but it’s not always the best practice. Changes to your theme—or switching to a new one—could overwrite or remove your customizations. A custom plugin provides a safer, more portable solution for adding functionality like a Share on X button. I have a single custom shortcode plugin for my site with all of my shortcodes.

Here’s how to create a custom WordPress plugin to implement a shortcode for seamless sharing on X.

Step 1: Create Your Custom Plugin File

  1. Navigate to your WordPress installation directory using an FTP client or your hosting file manager.
  2. Open the /wp-content/plugins/ directory.
  3. Create a new folder for your plugin, for example, share-on-x.
  4. Inside the folder, create a file named share-on-x.php.

Step 2: Add the Plugin Code

Copy and paste the following code into the share-on-x.php file:

<?php
/**
 * Plugin Name: Share on X Shortcode
 * Description: Adds a customizable shortcode to create a "Share on X" button for WordPress posts and pages.
 * Version: 1.0
 * Author: Douglas Karr
 * Author URl: https://dknewmedia.com
 * License: GPL2
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Function to generate the "Share on X" button with content.
function tweet_this_shortcode($atts, $content = null) {
    // Extract shortcode attributes with defaults.
    $atts = shortcode_atts(
        array(
            'via' => '',       // Optional: Twitter/X handle.
            'class' => '',     // Optional: CSS class for the button.
            'blockquote' => 'true' // Default to wrapping in blockquote.
        ),
        $atts
    );

    // Get the current post URL.
    $post_url = get_permalink();
    $tweet_text = urlencode($content);

    // Include "via" only if provided.
    $via_handle = !empty($atts['via']) ? "&via=" . urlencode($atts['via']) : '';

    // Construct the X (Twitter) share URL.
    $x_url = "https://x.com/intent/post?text={$tweet_text}{$via_handle}&url={$post_url}";

    // Build optional attributes.
    $class_attr = (!empty($atts['class'])) ? ' class="' . esc_attr($atts['class']) . '"' : '';

    // Generate the button HTML.
    $button_html = '<a class="twitter-button" href="' . esc_url($x_url) . '" target="_blank" rel="noopener noreferrer">Share on X</a>';

    // Wrap in blockquote if blockquote="true" (default behavior).
    if (strtolower($atts['blockquote']) === 'true') {
        return '<blockquote ' . $class_attr . '>' . esc_html($content) . ' <cite>' . $button_html . '</cite></blockquote>';
    }

    // Default output without blockquote.
    return '<span>' . esc_html($content) . '</span> ' . $button_html;
}

// Register the shortcode.
add_shortcode('tweetthis', 'tweet_this_shortcode');

Step 3: Activate Your Plugin

  1. Log in to your WordPress admin dashboard.
  2. Navigate to Plugins > Installed Plugins.
  3. Locate your “Share on X Shortcode” plugin and click Activate.

Step 4: Use the Shortcode

By following this approach, you ensure your Share on X functionality is safe, reliable, and easy to customize.

Appreciate this content?

Sign up for our weekly newsletter, which delivers our latest posts every Monday morning.

We don’t spam! Read our privacy policy for more info.

Douglas Karr

Douglas Karr is CMO of OpenINSIGHTS and the founder of the Martech Zone. Douglas has helped dozens of successful MarTech startups, has assisted in the due diligence of over $5 bil in Martech acquisitions and investments, and continues to assist companies in implementing and automating their sales and marketing strategies. Douglas is an internationally recognized digital transformation and MarTech expert and speaker. Douglas is also a published author of a Dummie's guide and a business leadership book.
Back to top button
Close

Adblock Detected

Martech Zone is able to provide you this content at no cost because we monetize our site through ad revenue, affiliate links, and sponsorships. We would appreciate if you would remove your ad blocker as you view our site.