1
<?php echo plugins_url().'/jamesplugin/assets/library/classes/process_mailchimp.php';?>

The above is path of a file that is kept in a plugin, but I want to transfer that file to a theme say here →

inc/process_mailchimp.php

For this plugins_url() what will be its theme-equivalent?

Please let me know If I need to provide any extra information to you.

1 Answer 1

3

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/'); ?>
1
  • 3
    This is the approach to take, I cannot understate how dangerous it is security wise to have standalone files you ping from the frontend like that. REST endpoints are super easy to make, and significantly more secure
    – Tom J Nowell
    Aug 25, 2017 at 19:37

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.