Wordpress - Loading external page template and enqueue script from plugin causes 403 forbidden error
Your CODE is fine, the reason you are getting 403 error is because $_SERVER['DOCUMENT_ROOT']
returns absolute PATH to your web root, not URL.
JavaScript needs to be added as URL. So, you may use Load_Template_Scripts_wpa83855
function in your plugin and then use:
wp_enqueue_script( 'wtd', plugins_url( '/js/wtd.js' , __FILE__ ) );
CODE to add JavaScript.
Note: obviously you can make the CODE even better using logic like what @nathan used in his answer, i.e. adding:
add_action('wp_enqueue_scripts','Load_Template_Scripts_wpa83855');
within the
wpa3396_page_template()
function inif ( is_page( 'mypanel' ) ) {}
condition block; but that's not the reason of the error. Server PATH cannot be accessed by browser, that's why the server returnsAccess Forbidden
error.
Full CODE (Updated):
Here is the full CODE for your convenience (add it in your main plugin file):
add_filter( 'page_template', 'wpse_262042_page_template' );
function wpse_262042_page_template( $page_template ) {
if( is_page( 'mypanel' ) ) {
add_action( 'wp_enqueue_scripts', 'wpse_262042_enqueue_scripts' );
$page_template = plugin_dir_path( __FILE__ ) . 'includes/mypanel.php';
}
return $page_template;
}
function wpse_262042_enqueue_scripts() {
wp_enqueue_script( 'wtd', plugins_url( 'js/wtd.js' , __FILE__ ), array( 'jquery' ) );
}