Migrating a File from Plugin to Theme and changing its path → instead create a REST endpoint

I’m not sure why are you trying to print out a PHP file’s path, because it’s not a good practice. But to get the equivalent function for themes, you can use:

  • For parent themes : get_template_directory_uri();
  • For Child themes: get_stylesheet_uri();

Both are without trailing slash.

Important Note

Don’t ping a PHP file directly from your plugin or theme’s folder. Including a PHP file (for example, by using require_once()) is fine, but accessing it directly by the browser is not. The better practice is to even check if the file being accessed directly, and block the access:

if( !defined( 'ABSPATH' ) ) {
    die();
}

ABSPATH is a constant, defined by WordPress, which contains the absolute path to your installation root. If it’s not defined, it means that your file is being accessed directly, maybe by a hacker.

So, instead create a REST endpoint and use that. Here is a simple example for you.

First, create an endpoint to call. It’s as simple as this:

add_action( 'rest_api_init', 'my_endpoint' );
function my_endpoint() {
    register_rest_route( 
        'wpnovice/v1', '/my_path/', 
        array(
            'methods'  => 'GET',
            'callback' => 'wpnovice_callback'
        )
    );
}

Then, do the calculation in your callback function and return the value there:

function wpnovice_callback( $request ){
    // Your code here
    return $data;
}

The final stage is to use the REST endpoint as URL in your Ajax call. Set your URL to this:

<?php echo rest_url('/wpnovice/v1/my_path/'); ?>

Leave a Comment