Home > other >  Wordpress plugin - can't create shortcodes from within a class
Wordpress plugin - can't create shortcodes from within a class

Time:02-23

I stored an array in the wordpress database with shortcodes I want to create. I want to read the array of shortcodes and create them on my wordpress site using class functions from a class that is not instantiated. (I'm new to classes in PHP, so tried to keep it as simple as possible)

Array structure stored in the wordpress database:

my_array = [ 
'code1' => 'text_to_replace1', 'show1' => 'text_to_show1',
'code2' => 'text_to_replace2', 'show2' => 'text_to_show2',
 ];

I'm using code like this to try to create the shortcodes:

add_action( 'admin_init', ['my_class','register_shortcodes'] );

and the functions inside the class are:

class my_class {
  private static $codes = [];

  static function register_shortcodes() {
    self::$codes = get_option('my_options_in_database');
    add_shortcode( $codes['code1'],['my_class', 'render_shortcode1'] );
    add_shortcode( $codes['code2'],['my_class', 'render_shortcode2'] );
  }

  static function render_shortcode1() {
    return self::$codes['show1'];
  }

  static function render_shortcode2() {
    return self::$codes['show2'];
  }
}

The code appears to half-run, because the shortcode is being created (as viewed by another plugin showing me active shortcodes), but the shortcode doesn't do anything. The text is never replaced. For example, if the shortcode stored in 'code1' = 'foo', and 'show1' = 'bar' and I have this on one of my pages in the website This is what [foo] looks like it is never replaced by the correct text in 'show1'.

I've tried many variations and looked up many articles, like this one: Create a shortcode for a handmade plugin in Wordpress or this one: WP Shortcodes not being added

Nothing seems to address this exactly, and because no errors are thrown, I have no idea why it isn't working. I would really appreciate some pointers here.

ALSO: I haven't figured out how to pass arguments to my functions inside the class when calling them this way. If I knew that, I could have a single function render all my shortcodes, so that would help too. Any info on that would also be appreciated. I can create a separate question for that if needed.

CodePudding user response:

When you want to register a shortcode, do not use admin_init but init. Even if you want to set it up in the admin area. Because WordPress does not store in the database what you register, the code that register the shortcode is read at each page load.

With the admin_init hook the shortcode will only be registered in the admin area but not on the front.

  • Related