首页 > 解决方案 > Wordpress:从帖子ID(ajax)返回页面的HTML

问题描述

我按照这个答案的说明进行操作: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);
        }
    });

});
});

标签: ajaxwordpress

解决方案


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

<?php echo $post->post_content; ?>

推荐阅读