簡體   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