0

I am wondering what's the best way to give a user the option to feature a custom post type on the home page.

I have a Case Study custom post type and some of them need to be feautured on the home page. Ideally when creating the case study there would be like a checkbox labeled "Feature on home page". Once that is selected the home page will show the image, excerpt and a link to the full case study.

1 Answer 1

0

First, you'll want a quick way to toggle whether a post is featured or not. I wrote a plugin that does this:

http://wordpress.org/extend/plugins/featured-item-metabox/

but I feel like a total dork because I just discovered that this plugin was already doing that! http://wordpress.org/extend/plugins/featured-post

Ugh. Anyway, how you want to feature them on the home page will effect how you can query them.

From my plugin's usage docs this will get a list of all featured "portfolios". You can adapt the UL list to be whatever you'd like.

// Get any existing copy of our transient data
if ( false === ( $featured_portfolios = get_transient( 'featured_portfolios' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient

   // params for our query
    $args = array(
        'post_type' => 'portfolio'
       'posts_per_page'  => 5,
       'meta_key'        => '_featured',
       'meta_value'      => 'yes'
    );

    // The Query
    $featured_portfolios = new WP_Query( $args );

    // store the transient
    set_transient( 'featured_portfolios', $featured_portfolios );

}

// Use the data like you would have normally...

// The Loop
if ( $featured_portfolios ) :

    echo '<ul class="featured">';

    while ( $featured_portfolios->have_posts() ) :
        $featured_portfolios->the_post();
        echo '<li>' . get_the_title() . '</li>';
    endwhile;

    echo '</ul>';

else :

echo 'No featured portfolios found.';

endif;

/* Restore original Post Data
 * NB: Because we are using new WP_Query we aren't stomping on the
 * original $wp_query and it does not need to be reset.
*/
wp_reset_postdata();

And because I'm using transients to store the query, we'll need to update the transient any time you update a portfolio post.

// Create a function to delete our transient when a portfolio post is saved
    function save_post_delete_featured_transient( $post_id ) {
       if ( 'portfolio' == get_post_type( $post_id ) )
        delete_transient( 'featured_portfolios' );
    }
    // Add the function to the save_post hook so it runs when posts are saved
    add_action( 'save_post', 'save_post_delete_featured_transient' );
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.