【问题标题】:WordPress send post URL to ajaxWordPress 将帖子 URL 发送到 ajax
【发布时间】:2018-02-19 17:32:49
【问题描述】:

我正在使用wp_localize_script 将发布数据发送到 ajax。

wp_localize_script( 'my-script.js', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'ajax_posts' );

发送post数据到ajax:

function ajax_posts(){
    global $post;
    $args = array('post_type'=>'post', 'posts_per_page'=> 2);
    $posts_arr=[];
    $query = new WP_Query($args);
    if($query->have_posts()):
        while($query->have_posts()):$query->the_post();

            $posts_arr[] = $post;

        endwhile;
        wp_reset_postdata();

    endif;
    wp_send_json_success(array('post'=>$posts_arr));
}

在我的 ajax 成功函数中,我使用以下内容将帖子附加到 HTML:

success:function(response){

     var post_data = response.data.post;

     $.each(post_data, function(index, value) {

        $("#content").append('<a href="How can I get the post URL here?">' + value.post_title + '</a>');

    });          

}

它将 2 个帖子添加到 HTML。它运作良好,但我怎样才能将帖子网址添加到ajax_posts() php 函数并将其传递给 ajax 并使用?

这是我从 ajax 得到的数据:

是否可以将帖子网址也添加到帖子数组中?

注意:我使用 ajax 在单击按钮时加载更多帖子,但此处简化了代码。我无法将 php 直接添加到 js 中。它必须从ajax_posts() php函数发送到我的js中的ajax。

【问题讨论】:

    标签: javascript ajax wordpress


    【解决方案1】:

    你可以简单地做这样的事情:

    function ajax_posts(){
        global $post;
        $args = array('post_type'=>'post', 'posts_per_page'=> 2);
        $posts_arr=[];
        $query = new WP_Query($args);
        if($query->have_posts()):
            while($query->have_posts()):$query->the_post();
    
                $posts_arr[] = array(
                    'permalink' => get_permalink(),
                    'ID' => $post->ID,
                    'post_title' => $post->post_title,
                    'post_content' => $post->post_content,
                    'post_author' => $post->post_author,
                    'post_date' => $post->post_date
                    // Add more fields as needed here
                );
    
            endwhile;
            wp_reset_postdata();
    
        endif;
        wp_send_json_success(array('post'=>$posts_arr));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2011-03-17
      • 2016-09-29
      相关资源
      最近更新 更多