views:

446

answers:

2

On my homepage I have a list of posts, and at the top I want to show only the most recent "sticky" post, followed by the rest of the posts. Is there a way to achieve this?

Bonus points for only using one query_posts().

(I know how to do it using two query_posts(), but I'm looking for a less taxing solution.)

A: 

You'll need to tweak this code a bit but it should get you going in the right direction. What this is doing is modifying the sql query used to pull the posts.

Before your query_posts(); add the following code:

function selectSticky( $sql ){
    global $sticky_posts, $wpdb;

    $sticky_posts = get_option( 'sticky_posts' );
    $sticky_posts = implode( ', ', $sticky_posts );

    return "IF( {$wpdb->posts}.ID IN ( $sticky_posts ), 2, 1 ) as sticky, ".$sql;
}

function whereSticky( $sql ){
    global $sticky_posts, $wpdb;

    $sql .= " OR {$wpdb->posts}.ID IN ( $sticky_posts )";
    return $sql;
}

function orderSticky( $sql ){
     $sql = "sticky DESC, ".$sql;
     return $sql;
}

// just for checking sql, you can remove this once everything works
function requestSticky( $sql ){
     echo $sql."<br/><br/>";
     return $sql;
}

add_action( 'posts_fields', 'selectSticky' );
add_action( 'posts_where', 'whereSticky' );
add_action( 'posts_orderby', 'orderSticky' );
add_action( 'posts_request', 'requestSticky' );
postpostmodern
thanks for the response! wow, I didn't expect something that seems so simple to involve such a ghastly amount of code—yikes! It also makes me wonder why the WP core team didn't just add a "sticky" column to the `wp_posts` table...
gabriel
If you know the sql query that would return the correct results, you can skip the first three actions/functions and just return the query in requestSticky(). Although off the top of my head, I can only imagine a solution to the multiple sticky problem using a UNION query, which doesnt really save any overhead sql-wise, though it would be less work for PHP.
postpostmodern
A: 

Have you tried any plugins? For example this? http://wordpress.org/extend/plugins/wp-sticky/ I may be easier to use/modify them.

Umut Benzer
Thanks, Umut, but I'd prefer not to use plugins that duplicate functionality that are already in WP Core.
gabriel