繁体   English   中英

为什么我的Ajax请求从wordpress返回空对象?

[英]Why is my ajax request returning an empty object from wordpress?

在我的functions.php文件中,我有一个函数:

function get_news_recipes()
{
    global $wpdb;
    $interval=$_REQUEST['interval'];
    $getPosts = $wpdb->get_results("SELECT ID FROM wp_posts WHERE post_status='publish' AND post_type='post' LIMIT 3 OFFSET ".$interval."");
    foreach ($getPosts as $blog)
    {
        $id=$blog->ID;
        $title=get_the_title($id);
        $url=get_permalink($id);
        $content=get_the_content($id);
        $image=wp_get_attachment_url(get_post_thumbnail_id($id));
        $postArray[$id]=array(
            'title'=>$title,
            'content'=>$content,
            'url'=>$url,
            'image'=>$image
        );}
    echo wp_send_json($postArray);
    die();
}

在我的脚本文件中,我具有如下的ajax设置:

function getNewsPosts(interval) {
            jQuery.ajax({
                url : ajaxurl,
                type : 'post',
                data : {
                    action : 'get_news_recipes',
                    interval:interval,
                },
                success : function( response ){
                    //get and store references to modules in slides
                    var imgs = jQuery('.js-slideImg');
                    var titles = jQuery('.js-slideTitle');
                    var contents = jQuery('.js-slideContent');
                    var links = jQuery('.js-slideURL');
                    var count = 0;

                    //interate over each slide and replace html
                    for(var key in response){
                        if(response.hasOwnProperty(key)){
                            jQuery(imgs[count]).css('background-image', 'url('+response[key].image+')');
                            jQuery(titles[count]).html(response[key].title);
                            jQuery(contents[count]).html(response[key].content);
                            jQuery(links[count]).attr('href', response[key].url);
                            count++;
                        }
                    }
                }
            });
        }

一切都很好,除了响应的内容变空了,我不知道为什么。 图片网址,实际网址和标题都会按预期返回,但是内容为空字符串。

必须在循环中使用函数get_the_content ,否则它将不返回任何内容。 您应该将以下代码用于帖子的内容。

$post = get_post($id);
$content = $post->post_content;

修改代码如下

$id=$blog->ID;
$content=$blog->post_content;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM