How to load WP functions?

The root problem here is that you should never make direct requests to PHP files in a theme or plugins from the browser. It is extreme bad practice, fragile, and open to lots of security issues.

To get this working as is you would need to bootstrap WordPress by putting something similar this near the top of your PHP file:

// the line below is a bad idea, I apologise to those reading this
require_once('wp-blog-header.php');

You may also want to reduce WordPress core load by defining SHORT_INIT, though this depends on which functions you are using ( and wether they get loaded when this is defined ).

But this is completely the wrong way of going about it. Because its:

  • more effort
  • wasteful
  • slower
  • less secure
  • likely to incurr a higher maintenance and support cost

Judging from your comment, I would advise you use the REST API instead. Using these APIs will save you time and effort, and it will make things simpler/easier in the long run ( and more secure )

e.g.

add_action( 'rest_api_init', function () {
    register_rest_route( 'porton/v1', '/sendemail', array(
        'methods'  => 'GET',
        'permission_callback' => '__return_true',
        'callback' => 'portons_email_function',
    ) );
} );

function portons_email_function( $request ) {
    // you get the parameters sent from $request:  
    $to = $request['to'];
    $subject = $request['subject'];
    ... etc ...

    // then send your emails

    // and return the result
    return 'Email is sent successfully.';
}

and

jQuery.ajax({
    url: <?php echo wp_json_encode( esc_url_raw( rest_url( 'porton/v1/sendemail' ) ) ); ?>,
    data: {
        'to':      '[email protected]',
        'subject': 'the subject',
        ...etc...
    }
}).done(function( data ) {
    console.log( data ); // should print email sent successfully int he browser console
});

Note that 'permission_callback' => '__return_true', means everybody can use this endpoint, swap __return_true for the name of a function that returns true if the user can do this, or false if the user cannot to avoid anybody being able to send emails.

Leave a Comment