获取AJAX请求的初始帖子类型

时间:2019-03-19 14:01:38

标签: php jquery ajax wordpress

在WordPress中,我有一个加载更多按钮,该按钮发出AJAX请求以获取更多帖子。通过检测按钮上的click事件,然后向运行$query = new WP_Query();之类的查询的PHP脚本发出请求,可以实现此目的。

我想将同一函数用于几种不同的帖子类型,将帖子类型暴露给我的AJAX函数的最佳方法是什么?

$.ajax({
  type: "POST",
  dataType: "json",
  url: ajax_get_posts_object.ajax_url,
  data: {
    action: "ajax_get_posts",
    security: ajax_get_posts_object.ajax_nonce,
    current_page: next_page,
    categories: $selectedCategories,
    tags: $selectedTags,
  },
  beforeSend: function(xhr) {
    load_more.text("Fetching...");
  },
  success: function(response) {
    if (response) {
      console.log(response);

      // An array to store new items added via AJAX
      var new_items = [];

      // Run through JSON
      $.each(response.posts, function(key, value) {
        var $new_item = $(`<div class="grid-item article-post-card ${value.category["slug"]} ${value.tags ? value.tags[0]["slug"] : ''}">
          <a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}">
            <div class="article-post-card__featured-image-container">
              <div class="article-post-card__overlay"></div>
              <div class="article-post-card__featured-image">${value.thumbnail}</div>
              <div class="article-post-card__category-label">${value.category["name"]}</div>
            </div>
            <div class="article-post-card__content-wrapper">
              <div class="article-post-card__publish-date">
                <time class="updated" datetime="${value.post_time}">${value.date}</time>
              </div>
              <div class="article-post-card__title">${value.title}</div>
              <div class="article-post-card__excerpt">${value.introduction}</div>
            </div>
          </a>
        </div>`);
        new_items.push($new_item[0]);
      });

      next_page >= response.pages ? disableLoadMore(true) : disableLoadMore(false);

      rebuildGrid($grid, new_items, '*');

      updateFilterCount(response.post_count);

      // Update boolean so that page count is not reset
      load_more_has_run = true;

      next_page++;

      // If the AJAX function returned no data
    } else {
      load_more.remove();
    }
  },
  error: function(xhr, status, error) {
    console.log("There was an error", error);
  }
});
});

1 个答案:

答案 0 :(得分:0)

You can simply add in the data:{} object a post_type element

$.ajax({
  type: "POST",
  dataType: "json",
  url: ajax_get_posts_object.ajax_url,
  data: {
    action: "ajax_get_posts",
    security: ajax_get_posts_object.ajax_nonce,
    current_page: next_page,
    categories: $selectedCategories,
    tags: $selectedTags,
    post_type: 'your_post_type'
  },
  ...
});

and then use it in your WP_Query()

$post_type = key_exists('post_type', $_POST) ? $_POST['post_type'] : 'post';
$query = new WP_Query(
  'post_type' => $_POST['post_type'],
  ...
);