How to use WordPress (PHP) functions in AngularJS partials files?

What works is calling WP’s Ajax endpoint. Note that it is not the address of your partial, but the fixed WP address for all AJAX calls

wp_localize_script('handle', 'myLocalized', array(
     'ajaxUrl' => admin_url( 'admin-ajax.php' )
) );

provides the endpoint adress in the JS object myLocalized. You send all requests to that page and refer to your partials only as GET parameters:

$routeProvider.when('/search-results', {
    templateUrl: myLocalized.ajaxUrl + '?action=get_my_partial&partial=" + "main';
    controller: 'Main'
}).when('/:ID', {
    templateUrl: myLocalized.ajaxUrl + '?action=get_my_partial&partial=" + "content';
    controller: 'Content'
});

All calls to admin-ajax.php with a parameter {action} get routed to actions named wp_ajax_{action} (for logged in users) or wp_ajax_nopriv_{action} (for users not logged in). On the server side, you can hook up to them and include your partials:

function get_the_partials () {
    switch ( $_GET['partial'] ) {
        case 'main':
            // check authorization
            include plugin_dir_path(__FILE__) .'/partials/main.html';
            break;
        case 'content':
            // check authorization
            include plugin_dir_path(__FILE__) .'/partials/content.html';
            break;
        default:
            wp_die( 'Nothing found.' );
            break;
    }
    die();
}
add_action( 'wp_ajax_nopriv_get_my_partial', 'get_the_partials' );
add_action( 'wp_ajax_get_my_partial', 'get_the_partials' );

This way, WordPress is fully initialised and can handle any functions normally available. (Well, outside the loop.)

Since you handle selecting specific posts from the controller and through the wp-json endpoint, that should do it.

Leave a Comment

tech