首页 > 解决方案 > 使用 Ajax 获取 Wordpress 帖子数据

问题描述

我在一个 WorPress 网站上工作,我希望我的页面上只有 4 个帖子,并使用 ajax 在其他帖子之间导航。

我有我的 front-page.php(只是尝试的代码):

<section>
  <button type="button" name="button" id="btn_next">+</button>
  <button type="button" name="button" id="btn_pre">-</button>
  <div class="" id="result"></div>
  <div class="" id="offset"></div>
</section>

我有我的 ajax.js

jQuery(document).ready(function($){

  $("#btn_next").click(function(){
    var off = $('#offset').html();
    data_ajax(1);
  })
  $("#btn_pre").click(function(){
    data_ajax(-1);
  });

  function data_ajax(new_offset){
    $.ajax({
      url: ajaxObject.url,
      dataType: 'json',
      method: 'POST',
      data: {
        action : 'ajax_agenda',
      },
      success: function(responseText){
        console.log("result : " + JSON.stringify(responseText));
        $("#result").html('<h3>résultats</h3>');
      },
      error: function(xhr, error, exception){
        console.log(xhr);
        console.log(error);
        console.log(exception);
        $("#result").html('<h3>Pas de résultats</h3>');
      }
    }); // fin ajax
  }

});

和我在function.php中的函数

add_action('wp_ajax_ajax_agenda', 'ajax_agenda');
add_action('wp_ajax_nopriv_ajax_agenda', 'ajax_agenda');
function ajax_agenda(){

  $final_array = array();

  $args = array(
    'posts_per_page' => 3, /* how many post you need to display */
    'offset' => 1,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'agenda', /* your post type name */
    'post_status' => 'publish'
  );
  $query = new WP_Query($args);
    $posts = $query->posts;

    if($query->have_posts()){
        $final_array["success"] = "true";
        $final_array["results"] = $posts;
  }
  else{
    $final_array["success"] = "false";
  };

  echo json_encode( $final_array );


    die(); // Pour eviter les erreurs due au "die(0)"" prédrnt dans le fichier "admin-ajax.php"
};

但是我没有到达使用js返回的数据:(我需要你的帮助。

标签: phpajaxwordpress

解决方案


PHP 代码

function get_ajax_posts_data() {
    $args = array(
        'post_type' => array('yout post type'),
        'post_status' => array('publish'),
        'posts_per_page' => 10,
        'order' => 'DESC',
        'orderby' => 'date',
    );

    $ajaxposts = get_posts( $args );
    echo json_encode( $ajaxposts );

}

add_action('wp_ajax_get_ajax_posts_data', 'get_ajax_posts_data');
add_action('wp_ajax_nopriv_get_ajax_posts_data', 'get_ajax_posts_data');

jQuery代码:


$.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php');?>',
    dataType: "json",
    data: { action : 'get_ajax_posts_data' },
    success: function( response ) {
        $.each( response, function( key, value ) {
            console.log( key, value ); 
        } );
    }
});

推荐阅读