Simple Plugin for a Shortcode


Creating a plugin in WordPress to handle your custom shortcode is a great way to keep your functionality separate from your theme. This means you can switch themes without losing the shortcode functionality. Here’s a step-by-step guide to creating a simple WordPress plugin for your shortcode:

Step 1: Create the Plugin Folder and File

First, navigate to your WordPress installation directory, then go to the wp-content/plugins directory. Inside, create a new folder named acf-link-shortcode.

Within this folder, create a file named acf-link-shortcode.php. This will be your main plugin file.

Step 2: Add the Plugin Header

Open acf-link-shortcode.php in a text editor and start by adding the following header information at the top of the file. This header tells WordPress that it’s a plugin file.

<?php
/*
Plugin Name: ACF Link Shortcode
Plugin URI: http://yourwebsite.com
Description: This plugin adds a shortcode to output URLs of files uploaded via ACF.
Version: 1.0
Author: Your Name
Author URI: http://yourwebsite.com
*/

Step 3: Add the Shortcode Function

Below the header, you can now add the function that handles your shortcode. This is the same function you would otherwise add to your functions.php file in your theme.

function get_acf_upload_url($atts) {
    $atts = shortcode_atts(array(
        'post_id' => get_the_ID(),
        'field_name' => '',
    ), $atts);

    if (!$atts['field_name']) {
        return 'No field name provided.';
    }

    $file_url = get_field($atts['field_name'], $atts['post_id']);

    if (!$file_url) {
        return 'No file uploaded or incorrect field name.';
    }

    return '<a href="' . esc_url($file_url) . '" target="_blank">Download File</a>';
}

add_shortcode('acf_upload_link', 'get_acf_upload_url');

Step 4: Activate the Plugin

  • Save your changes and go to your WordPress dashboard.
  • Navigate to the ‘Plugins’ section where you will see your new plugin listed.
  • Click ‘Activate’ next to “ACF Link Shortcode”.

Now, your shortcode will be available for use across your site, independent of your theme. You can use this shortcode in posts, pages, and even widget areas that support shortcodes.

Step 5: Adding More Functionality

In the future, if you wish to add more features or additional shortcodes, you can simply add more functions and add_shortcode calls to this plugin file.

Best Practices

  • Always test your plugin on a development site before using it on a live site.
  • Ensure your plugin gracefully handles errors, such as when ACF is not installed or activated.

By following these steps, you’ll have created a simple yet effective WordPress plugin tailored to your specific needs for handling file links via ACF!