Home > Enterprise >  Where should I put my shortcode file exactly? (Wordpress)
Where should I put my shortcode file exactly? (Wordpress)

Time:07-02

I'm making a custom plugin and trying to make a shortcode this time. So I have three files in my plugin folder.

  1. functions.php
  2. data.php
  3. shortcodes.php

And as you can guess, add_shortcode and do_shortcode functions are inside of shortcodes.php. I'm following this article and it said to put this code

include('custom-shortcodes.php');

inside of theme's functions.php. However, My shortcode file is placed inside of my plugin so I put this code

<?php
    include (ABSPATH . '/wp-content/plugins/my-plugin/shortcodes.php');
?>

inside of functions.php in themes folder to include my file but keep getting me error. I cannot save my post.

Am I doing the right way or am I putting it in a wrong file with wrong code?

CodePudding user response:

Let's say you have four .php files in your .../wp-content/plugins/my-plugin directory, named typically ...

  • my-plugin.php -- the file that gets run when WordPress loads your plugin.
  • functions.php -- yours
  • data.php -- yours
  • shortcodes.php -- yours

Then you put into your my-plugin.php file code like this:

add_action( 'init', 'my_plugin_startup' );

function my_plugin_startup() {
    require_once( plugin_dir_path( __FILE__ ) . 'functions.php' );
    require_once( plugin_dir_path( __FILE__ ) . 'data.php' );
    require_once( plugin_dir_path( __FILE__ ) . 'shortcodes.php' );
}

It's this require_once( plugin_dir_path( __FILE__ ) . 'functions.php' ); line of code that loads your source file.

  • __FILE__ contains the pathname of the presently running php file.
  • plugin_dir_path() retrieves the plugin's directory.
  • you append your filename (. 'functions.php') to that, and
  • use require_once to load it.

There's a bunch of other stuff that needs to go into that my-plugin.php file, which you can read about here.

When you develop a plugin, you should not edit any file in your theme to load it. WordPress does that once you have activated your plugin. You put the shortcode into your post or page to use it.

The article you showed us is accurate on how to create and use a shortcode function, but it's wrong about theme editing.

  • Related