【问题标题】:Wordpress Rest API: Return more than 100 resultsWordpress Rest API:返回 100 多个结果
【发布时间】:2021-03-27 14:02:07
【问题描述】:

我目前正在构建一个 Vue webapp 来显示所有自定义帖子类型,最近超过 100 个结果。 Wordpress REST API 将帖子数量限制为 100,我无法弄清楚如何对请求进行分页,因此在初始加载时获取所有帖子。

我目前的代码如下:

getPosts: function(context) {
      return new Promise((resolve, reject) => {
        if (context.state.posts) {
          resolve();
        } else {
          axios
            .get(
              "https://localhost:81/admin/wp-json/wp/v2/cap?per_page=100"
            )
            .then(response => {
              this.posts = response.data;
              context.commit("storePosts", response.data);
              console.log("Cap retrieved from Vuex!");
              //console.log(this.posts);
              resolve();
            })
            .catch(error => {
              console.log(error);
              reject(error);
            });
        }
      });
    }

我有以下computed 代码来显示结果:

computed: {
    caps() {
      const caps = new Map();

      if (this.$store.state.loading === false) {
        sortPosts(this.$store.state.posts).forEach(post => {
          const c = post.acf.address.country;
          const s = post.acf.address.state;

          if (!resorts.has(c)) resorts.set(c, new Map());

          const stateMap = resorts.get(c);
          if (!stateMap.has(s)) stateMap.set(s, []);

          stateMap.get(s).push(post);
        });
      }
      return caps;
    }
  }

如何在没有用户交互的情况下开始加载所有帖子

【问题讨论】:

    标签: vuejs2 axios vuex wordpress-rest-api


    【解决方案1】:

    把这个放在 API REST 网站的functions.php中

    add_filter( 'rest_{your_CPT}_collection_params', function ( $params, WP_Post_Type 
    $post_type ) {
        if ( '{your_CPT}' === $post_type->name && isset( $params['per_page'] ) ) {
            $params['per_page']['maximum'] = PHP_INT_MAX;
        }
        return $params;
    }, 10, 2 );
    

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 2016-12-02
      • 1970-01-01
      • 2018-09-26
      • 2017-05-20
      相关资源
      最近更新 更多