Wordpress Rest API:返回 100 多个结果

Posted

技术标签:

【中文标题】Wordpress Rest API:返回 100 多个结果【英文标题】:Wordpress Rest API: Return more than 100 results 【发布时间】: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;
    
  

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

【问题讨论】:

【参考方案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 );

【讨论】:

以上是关于Wordpress Rest API:返回 100 多个结果的主要内容,如果未能解决你的问题,请参考以下文章