【问题标题】:Is there any way to get related posts API in WordPress?有没有办法在 WordPress 中获取相关帖子 API?
【发布时间】:2019-07-30 11:38:17
【问题描述】:

我需要创建一个 API,以按类别过滤器呈现相关帖子。我已经在我的 functions.php 文件中编写了代码,但我没有明白如何将帖子 ID 传递给参数?

function related_posts_endpoint( $request_data ) {
    $uposts = get_posts(
    array(
        'post_type' => 'post',
        'category__in'   => wp_get_post_categories(183),
        'posts_per_page' => 5,
        'post__not_in'   => array(183),
    ) );
    return  $uposts;
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'sections/v1', '/post/related/', array(
        'methods' => 'GET',
        'callback' => 'related_posts_endpoint'
    ) );
} );

我需要从我当前的 API 调用中传递 id。因此,我需要将该 id 传递给我当前作为静态 (180) 传递的相关 API 参数

我需要从中呈现相关 API 的当前帖子 API 的图像

【问题讨论】:

    标签: wordpress wordpress-rest-api


    【解决方案1】:

    您可以将一个名为post_id 的参数添加到您的rest route,然后从request_data 数组中访问id。

    function related_posts_endpoint( $request_data ) {
    
        $post_id = $request_data['post_id'];
    
        $uposts = get_posts(
            array(
                'post_type' => 'post',
                'category__in'   => wp_get_post_categories($post_id),
                'posts_per_page' => 5,
                'post__not_in'   => array($post_id),
            )
        );
    
        return  $uposts;
    }
    
    add_action( 'rest_api_init', function () {
    
        register_rest_route( 'sections/v1', '/post/related/(?P<post_id>[\d]+)', array(
                'methods' => 'GET',
                'callback' => 'related_posts_endpoint'
        ));
    
    });
    

    您可以将 id 添加到 URL 调用的末尾 /post/related/183

    【讨论】:

      【解决方案2】:

      您可以像普通获取请求一样获取帖子 ID。 ?key=value 并使用它的广告 $request['key'] 所以你的代码应该是这样的。

      function related_posts_endpoint( $request_data ) {
          $uposts = get_posts(
          array(
              'post_type' => 'post',
              'category__in'   => wp_get_post_categories(183),
              'posts_per_page' => 5,
              'post__not_in'   => array($request_data['post_id']),//your requested post id 
          )
          );
          return  $uposts;
       }
      add_action( 'rest_api_init', function () {
          register_rest_route( 'sections/v1', '/post/related/', array(
                  'methods' => 'GET',
                  'callback' => 'related_posts_endpoint'
          ));
      });
      

      现在你的 api url 应该是这样的/post/related?post_id=183 试试这个然后告诉我结果。

      【讨论】:

        猜你喜欢
        • 2020-02-23
        • 1970-01-01
        • 2014-02-28
        • 1970-01-01
        • 1970-01-01
        • 2021-10-06
        • 1970-01-01
        • 2015-05-02
        • 2015-07-13
        相关资源
        最近更新 更多