首页 > 解决方案 > 获取 AJAX 请求的初始帖子类型

问题描述

在 WordPress 中,我有一个加载更多按钮,它发出 AJAX 请求以获取更多帖子。这通过检测按钮上的单击事件,然后向运行查询的 PHP 脚本发出请求(如$query = new WP_Query();.

我想对几种不同的帖子类型使用相同的功能,将帖子类型公开给我的 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);
  }
});
});

标签: phpjqueryajaxwordpress

解决方案


您可以简单地在data:{}对象中添加一个post_type元素

$.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'
  },
  ...
});

然后在你的 WP_Query() 中使用它

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

推荐阅读