Get WordPress theme, php file-URL via javascript

I am using jQuery load() to load a PHP page at runtime. And I am not using an elegant way to get the PHP URL. Somebody tell me an elegant way?

My method:

Read More
'http://' + document.domain + '/wp-content/themes/mytheme/ajax/myload.php'

If my wp is under a sub dir,I have to change the url to this:

'http://' + document.domain + '/mysubdir/wp-content/themes/mytheme/ajax/myload.php'

this is so ugly!

Structure of code is;

  • index.php contains a.js
  • a.js uses ajax to load tpl.php (just echo some div) into index.php
  • tpl.php is in my theme path.

So the question is how to get the URL of tpl.php in a.js?

Related posts

Leave a Reply

2 comments

  1. You should be able to use get_template_directory_uri.

    http://codex.wordpress.org/Function_Reference/get_template_directory_uri

    Also, get_site_url may come in handy as well.

    http://codex.wordpress.org/Function_Reference/get_site_url

    And get_bloginfo gives you a bunch of stuff, like the site url and home directory url.

    http://codex.wordpress.org/Function_Reference/get_bloginfo


    Also, It sounds like you need to add a parameter to your JS code, which is “passed” from PHP.

    For example (in pseudocode)

    a.js:

    loadDivFromThemePage(var themePagePath)
    {
         // call ajax load with themePagePath variable
    }
    

    index.php:

    <script>
    loadDivFromThemePage(<?php echo get_template_directory_uri() . "/tpl.php" ?>)
    </script>
    
  2. You need to use wp_localize_script.

    https://codex.wordpress.org/Function_Reference/wp_localize_script

    For example, in my javascript I call the variable ‘myLocalized’ when I need my path. I use Angular with WordPress. My code is below:

    function() mes_scripts{
       wp_register_script(
         'angularjs',
         get_stylesheet_directory_uri() . '/bower_components/angular/angular.min.js'
       );
     
       wp_register_script(
         'angularjs-route',
         get_stylesheet_directory_uri() . '/bower_components/angular-route/angular-route.min.js'
       );
     
     wp_enqueue_script(
       'my-scripts',
       get_stylesheet_directory_uri() . '/js/scripts.min.js',
       array('angularjs', 'angularjs-route' )
     );
    
      wp_localize_script(
        'my-scripts',
        'myLocalized',
        array(
          'partials' => trailingslashit( get_template_dir
          )
      );
    }
    add_action( 'wp_enqueue_scripts', 'mes_scripts' );