使用ajax加载wordpress模板


Load wordpress templates with ajax

我想用ajax加载我的模板,但我遇到了困难(根本不起作用),我想主要是用PHP。我正在尝试使用ID获取正确的模板,但似乎不起作用。

这是我到目前为止的代码:

function theme_js() {
    wp_enqueue_script( 'ajaxstuff', get_template_directory_uri() . '/js/ajax.js', array('jquery'), '', true );
    wp_localize_script( 'ajaxstuff', 'ajaxify', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    ));
}
add_action( 'wp_enqueue_scripts', 'theme_js' );
add_action( 'wp_ajax_nopriv_ajax_submit', 'my_ajax_submit' );
add_action( 'wp_ajax_ajax_submit', 'my_ajax_submit' );
function my_ajax_submit() {
    $pageUrl = $_REQUEST['URL'];
    $postid = url_to_postid( $pageUrl );         
    $post = get_post($postid);
    $pageSlug = get_page_template_slug($postid);
    if ($post) {
    setup_postdata($post);
        get_template_part( $pageSlug );
    }
    exit();
}

还有我的JS:

    (function($){
   $('body').on('click', 'a', function(e) {
        e.preventDefault();
        var URL = $(this).attr('href');
        animationFunction();
        var ajaxPromise = $.ajax({
            url: ajaxify.ajaxurl,
            type: "post",
            data: {
                action: 'my_ajax_submit',
                url: URL
            },
            dataType: "html"
        });
        var animationPromise = animationFunction();
        $.when(ajaxPromise, animationPromise).done(function(data) {
            $('#page-wrap').html(data[0]);
            TweenMax.to('.page', 0.35, { alpha: 1 });
        });
    });
    function animationFunction() {
      var deferred = $.Deferred();
      TweenMax.to('.page', 0.35, { alpha: 0, onComplete: deferred.resolve  });
      return deferred.promise();
    }
})(jQuery);
$pageUrl = $_REQUEST['URL'];

$_REQUEST包含一个关联数组,数组索引区分大小写,因此:

$pageUrl = $_REQUEST['url'];