0

I have a plugin that opens a pop-up window and displays it's content in there, not using any of the default wordpress theme/style etc.

My question is, what is the best way of securing access to this window? At the moment if a user copies/pastes the address into the browser it will show the content. I would like it to only be visible to users logged in with the role of admin.

Yet when i add some basic security to the plugin landing page, it affects the entire site, not just the plugin page:

my-plugin.php (located in /wp-content/plugins/my-plugin)

function check_logged_in() {
    if(!is_user_logged_in()){
        die('foo');
    }
}
add_action( 'wp_loaded', 'check_logged_in' );

This is being executed whether i am visiting the plugin page, or any other page on the site. I would like it to apply only to the plugin / subdirectories from the plugin (i.e. will apply to mysite.com/plugin/view-orders but not on mysite.com/contact)

  • for security you don't want the popup contents to be directly accessible. set the popup address to admin-ajax.php and add an AJAX action that does the security check that if passed includes the PHP file. – majick Jun 1 '19 at 7:53
  • Thanks for the reply - could you explain what you mean with a code example? – John Crest Jun 1 '19 at 14:30
  • ok see posted answer. – majick Jun 2 '19 at 9:00
0

Add some AJAX actions in your plugin file, something like this... The first one (without _nopriv) will already only be executed for logged in users, and the second will only be executed for logged out users, so there is no need to retest is_user_logged_in() here:

add_action('wp_ajax_show_popup_contents', 'show_popup_contents');
function show_popup_contents() {
    $filepath = dirname(__FILE__).'/popup.php';
    include($filepath); exit;
}

add_action('wp_ajax_nopriv_show_popup_contents', 'deny_popup_contents');
function deny_popup_contents() {
    wp_die("You need to be logged in to view these contents.");
}

Then set the popup URL to /wp-admin/admin-ajax.php?action=show_popup_contents

You probably want to also add if (!defined('ABSPATH')) {exit;} at the top of the included popup.php file so it cannot be accessed directly that way.

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.