Wordpress:从帖子ID(ajax)返回页面的HTML

时间:2018-05-27 01:09:01

标签: ajax wordpress

我按照此答案的说明进行操作:https://stackoverflow.com/a/26950030/9200273

我可以根据传递给它的帖子ID从Ajax模板返回数据。

这就是模板的样子(与我发布的答案基本相同):

<?php
/*
Template Name: Ajax
*/

$post = get_post($_POST['id']);

if ($post) {
    setup_postdata($post); ?> 

    <div><?php the_title();?></div>

<?php } 

因此,当我单击一个链接时,我的ajax逻辑将用返回的内容替换div中的内容。在这种情况下只是帖子/页面的标题。

如果我没有使用ajax,如何返回页面内容?与我的自定义页面模板及其内容一样。

我的JS:

$(document).on( 'click', '.nav-header a', function( e ) {
 e.preventDefault();
    $.ajaxSetup({cache:false});
    pageurl = $(this).attr('href');

    if( pageurl != window.location ) {
        window.history.pushState( {path: pageurl}, '', pageurl);
    }

    if ( $(this).parent().attr('class') != "logo" ) {
        var postID = $(this).parent().attr("class").split('page-item-').pop().split(' ')[0];
    } else {
        var postID = $(this).attr("class").split('page-item-').pop().split(' ')[0];
    }

    $.ajax({
        url: wp_vars.httpHost,
        type: "POST",
        data: {
            id: postID
        },
        beforeSend: function() {
            $("main.main-wrap").children().remove();
        },
        success: function (data) {
            $("main.main-wrap").append($(data));
            console.log(data);
        },
        error: function () {
            console.log(data);
        }
    });

});
});

1 个答案:

答案 0 :(得分:0)

要在将帖子类保存到$ post变量时获取帖子内容,请使用此。

<?php echo $post->post_content; ?>
相关问题