0

We're making a WordPress plugin that generates an iframe with a shortcode, and that iframe that should work and display the same no matter what site, page or theme it's used on. The view is located at an URL inside the plugin folder.

Similarly, the plugin's styles and scripts shouldn't affect the site as a whole.

I'm not sure what the right way to do that isolation is. One way would be not to use wp_head() or wp_footer() and put my styles and scripts directly in the HTML instead of enqueuing them.

That works, but I can't help but wonder if there could be a better "WordPress Way" to do this.

I also thought of just mass-dequeuing every script and stylesheet only at this URL, but the theme would still be free to inject arbitrary HTML using hooks.

What's the right way to get a "clean slate" to work on for my plugin page?

1

Preferably don't load the plugin URL directly (well, unless it is a public URL and you can pass whatever data you need as querystrings) as this makes it difficult to load WordPress and access any stored data (as the path is not always determinable), but instead either:

  1. load the view via a querystring and check for it in WordPress load OR
  2. similar, but add it to an AJAX action querystring function.

Option 1. via /any-page/?my-action=trigger

add_action('init', 'my_plugin_view');
function my_plugin_view() {
    // check for querystring trigger
    if (!isset($_REQUEST['my-action']) || ($_REQUEST['my-action'] != 'trigger-value')) {return;}

    if (!is_user_logged_in()) {
       wp_die('You need to be logged in to do this.');
    } else {
        // ... plugin view output code ...
    }
    exit;
}

Option 2. via /wp-admin/admin-ajax.php?action=my_plugin_view

// logged in users
add_action('wp_ajax_my_plugin_view', 'my_plugin_view');

function my_plugin_view() {
    // ... plugin view output code ...
    exit;
}

// logged out users (optional) 
add_action('wp_ajax_nopriv_my_plugin_view', 'my_plugin_view');
function my_plugin_logged_out_message() {
    wp_die('You need to be logged in to do this.');
}

As you can see there is a difference in the target URL that is used as well as how logged out users are handled (if needed, in this example it is assumed the user must be logged in, but this distinction is not necessary for compltely public view.)

Either are viable options, but probably the AJAX method is the more common "WordPress way" of doing this. Of course any plugin scripts and styles would need to be added directly to the output instead of enqueueing them as normal.

Codex Reference: AJAX in Plugins

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.