Tumblr API - 按标签排除结果

问题描述 投票:0回答:2

我正在创建一个网站,其提要来自 tumblr。有一个部分用于一般帖子,另一部分用于“特色”帖子,由标签指定(即

#featured
)。

我试图防止同一篇文章出现在同一页面上的两个不同位置,因此对于我的常规提要部分,有没有办法让它排除带有

#featured
的帖子?

php json api jsonp tumblr
2个回答
0
投票

当您获取要处理的帖子对象时,您可以随时检查

if(!in_array($tag_to_exclude, $post->tags)) {
    // Post does not contain tag - display ...
}

我猜你抓住了

$apidata->response->posts
并运行了
foreach
循环?否则请随时询问更多信息


0
投票

我一直在尝试完成同样的事情,但在 Tumblr API 上却没有成功。看起来很奇怪他们没有这个功能,但我想就是这样。我确实编写了一个 PHP 类来完成此任务,这可能对 OP 或任何其他想要做同样事情的人有帮助。

class Tumblr {
    private $api_key = 'your_tumblr_api_key';
    private $api_version = 2;
    private $api_uri = 'api.tumblr.com';
    private $blog_name = 'your_tumblr_blog_name';

    private $excluded = 0;
    private $request_total = 0;

    public function get_posts($count = 40, $offset = 0) {
        return json_decode(file_get_contents($this->get_base_url() . 'posts?limit=' . $count . '&offset=' . $offset . $this->get_api_key()), TRUE)['response']['posts'];
    }

    /*
     * Recursive function that can make multiple requests to retrieve
     * the $count number of posts that do not have a tag equal to $tag.
     */
    public function get_posts_without_tag($tag, $count, $offset) {
        $excluded = 0;

        // get the the set of posts, hoping they won't have the tag
        $posts = $this->get_posts($count, $offset);
        foreach ($posts as $key => $post) {
            if (in_array($tag, $post['tags'])) {
                unset($posts[$key]);
                $excluded++;
            }
        }
        // if the full $count hasn't been retrieved, call this function recursively
        if ($excluded > 0) {
            $posts = array_merge($posts, $this->get_posts_without_tag($tag, $excluded, $offset + $count));
        }

        return $posts;
    }

    private function get_base_url() {
        return 'http://' . $this->api_uri . '/v' . $this->api_version . '/blog/' . $this->blog_name . '.tumblr.com/';
    }

    private function get_api_key() {
        return '&api_key=' . $this->api_key;
    }
}

get_posts_without_tag()
函数是大部分操作发生的地方。不幸的是,它通过发出多个请求来解决该问题。请务必将
$api_key
$blog_name
替换为您的 API 密钥和博客名称。

© www.soinside.com 2019 - 2024. All rights reserved.