wordpress content .php file in an iframe’s src in a wordpress post

There’s a file in the root of your WordPress installation called wp-load.php. If you include that file at the top of your .php file, it will bootstrap enough of WordPress that you’ll be able to access its API and execute your shortcodes.

However, there’s a better way to do it.

See, with the approach you’re using, you’re hard-coding the path to the file in your code. Even though you’re using WP_PLUGIN_URL, what happens if someone (maybe even you in future) wants to rename the plugin or moves that .php file to a different location?

WordPress provides an API for handling AJAX requests in plugins. It’s really easy to get started using it, and it’ll save you a lot of headaches down the road, especially if you release this plugin code publicly.

First, your plugin needs to register an AJAX handler.

// You can replace 'myactionname' with your own custom name
// like "user36316_renderiframe"
add_action( 'wp_ajax_nopriv_myactionname', 'myaction_handler' );
function myaction_handler() {

    // Render your iframe content here

    // Be sure to die() when you're done
    // or WordPress will append a '0' to the output
    // as a status code
    die();

}

Note the “nopriv” in the action name. WordPress’s AJAX support was originally built for their admin interface, so it checks for admin access by default. If you only wanted admins who were logged in to be running your AJAX code, you’d leave off the “nopriv” and register the action wp_ajax_myactionname. But you want everybody to be able to render this iframe, so keep the “nopriv” in there.

Now that you’re using WordPress’s AJAX API, you can leave it up to WordPress to figure out where the AJAX endpoint is. Since AJAX was originally just used for admins, the file wp-admin/admin-ajax.php is used, and the admin_url() function will tell you where to find it:

<iframe src=<?php echo add_query_arg( 'action', 'myactionname', admin_url( 'admin-ajax.php' ) ); ?>

The add_query_arg() call will append the name of your action to the AJAX request. It’s safer to use this function instead of just appending a value just in case admin_url() starts returning its own query string at some point.

You also want to pass a postid, and add_query_arg can help you there, too, if you pass in an array of query parameters:

<iframe src=<?php echo add_query_arg( array( 'action' => 'myactionname', 'postid' => get_the_ID() ), admin_url( 'admin-ajax.php' ) ); ?>