Is it just み?

Tag: Twitter Tools

WordPress: Filter certain categories on main page

by on Nov.20, 2009, under PHP, Programmierung

Ich werde mal versuchen einige meiner Einträge auf Englisch zu verfassen – um in der Übung zu bleiben.

I am using the Twitter Tools plugin to automatically create Tweets for my blog entries and vice versa to have some kind of tweet archive on my blog. That works flawlessly.

The only problem is: I tweet too much. I only want to show five entries on my front page, which basically means, that my last real blog entry is gone after one or two days, because of the twitter entries. The solution: Entries from the Tweets category should not be visible on the front page.

I had to extend my my-blog-exclusively-plugin with a function that filters the posts that appear on the front page, for this I added a filter to the hook “the_posts” which is called quite early in the loop before anything has been done to the posts. The posts that would be shown on the front page are given to the callback-function as first parameter in the form of an array. Here is the code:


<?php


/**/
// Filter post from the category Tweets on front page
add_filter(
    
'the_posts',
    
'filterTweets'
); /**/

function filterTweets($posts) {
    
// Filter only on the front page!
    
if (!is_front_page()) {
        return 
$posts;
    }

    
$tweetCategoryName 'Tweets';
    
$numVisiblePosts 5;

    
$postsToShow = array();
    
$filteredPosts = array();

    
$num 0;
    foreach (
$posts as $post) {
        
$cats in_category($tweetCategoryName, (int) $post->ID);
        if (!
$cats) {
            
$postsToShow[] = $post;
            
$num++;
        } else {
            
$filteredPosts[] = $post;
        }

        if (
$num >= $numVisiblePosts) {
            break;
        }
    }

    if (
$num $numVisiblePosts) {
        
// Too many twitter posts... what the hell... show some of them
        
$numTwitterPosts $numVisiblePosts $num;
        
$postsToShow array_merge(
            
$postsToShow
            
array_slice($filteredPosts0$numTwitterPosts)
        );
    }

    return 
$postsToShow;
}

Another thing I had to do was increase the number of posts shown on the front page, since my plugin now handles restricting the number of posts and I have to ensure that my function gets at least some posts that are not tweets. (But even if there are not enough, it fills up the front page with twitter posts.)

Comments Off on WordPress: Filter certain categories on main page :, , , , more...