0

我正在制作一个网站,其提要从 tumblr 流出。有一个部分用于一般帖子,另一部分用于“特色”帖子,由标签(即#featured)指定。

我试图阻止同一个帖子出现在同一页面上的两个不同位置,所以对于我的一般提要部分,有没有办法让它排除带有 ? 的帖子#featured

4

2 回答 2

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 密钥和博客名称。

于 2014-03-01T17:34:23.083 回答
0

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

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

我猜你抓住$apidata->response->posts并运行一个foreach循环?否则,请随时询问更多信息

于 2013-09-24T17:43:47.470 回答