0
votes

I was creating a wordpress plugin where the user enters in some information, and is able to generate shortcodes. I was not quite sure where the shortcodes are supposed to go - my current setup is class-based, and I want to be able to create a shortcode when an AJAX request is being made, and is successful. The following two methods are in the same file in the class.

This method gets called via the admin-ajax.php file:

public static function processAjax()
{

    global $wpdb;
    $event_data = $_POST['obj'];

    $event_title = $event_data[0];
    $event_subdomain = $event_data[1];
    $result_events = $wpdb->get_results("SELECT * FROM wp_shortcode_plugin WHERE subdomain = '{$event_subdomain}'", OBJECT);
    if (sizeof($result_events)>0) {
        echo "duplicate";
    } else {
        add_shortcode($event_subdomain, 'getEmbed');
        $results = $wpdb->insert('wp_shortcode_plugin', array("event_name"=>$event_title, "subdomain"=>$event_subdomain));
        echo json_encode($_POST['obj']);
    }

    die();
}

And here is my getEmbed() method that I would like to call.

public static function getEmbed()
{
    return 'test';
}

It seems that the shortcodes are not being created, however. Am I missing something here? Also, is it possible to pass a value to the getEmbed function from the add_shortcode() method?

1

1 Answers

1
votes

Instead of adding shortcode directly from AJAX, you should use update_option to store in the information for the shortcode to be loaded. If option doesn't exist, it will be created.

Than you will simple use wp_init hook to load up all of the shortcodes you need to load in the function.php file for the theme or plugin php file.

You should use get_option within the wp_init hook and check the values in there. You will need to have function(s) associated with the shortcodes, which can be autogenerated in php using create_function or you can route them through 1 function (defined in your php file) that will have the $atts and $content parameters defined and do whatever depending on the value of your get_option that you send to that function.

add_shortcode function should be defined within the wp_init hook, after checking the value of the get_option function. You will need to give your option a name and add to it via the ajax function. the option will most likely want to be an array, that wordpress will automatically serialize. Than you use that array returned from get_option to loop through the array of shortcodes, and call add_shortcode as many times as you need there. This requires setting up your option array so that it has a shortcode tag defined in each index of the array. I would, personally, make the shortcode tag the key of the array and all attributes of the shortcode, imo, would than be an array of that array.

Hope this helps you to get started on this.