WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] link to newest post, excluding 2 categories (3 posts)

  1. cluesew
    Member
    Posted 2 years ago #

    I'm trying to create a hyperlink on the home page that takes you to the latest blog post (in single view, ie the entire post) that excludes 2 categories (23, 24).

    On the homepage, I am linking separately to the excluded categories like this:

    <?php
        $args = array( 'numberposts' => '1', 'category' => 23 );
        $recent_posts = wp_get_recent_posts( $args );
        foreach( $recent_posts as $recent ){
        echo '<a href="' . get_permalink($recent["ID"]) . '">Latest Post</a>';
        }
    ?>

    but don't know how to code a link that takes you to the newest post excluding categories 23 & 24

  2. Ross Hanney
    Member
    Posted 2 years ago #

    Hello,

    I think this should do the trick:

    <?php
    $args = array(
    	'posts_per_page'   => 1,
    	'category__not_in' => array( 23, 24 )
    );
    
    $recent_posts = get_posts( $args );
    
    foreach ( $recent_posts as $recent ) {
    	echo '<a href="' . get_permalink( $recent ) . '">Latest Post</a>';
    }
    ?>

    The get_posts and wp_get_recent_posts functions accept any of the WP_Query parameters as arguments. The code above makes use of the category__not_in parameter, documented here.

  3. cluesew
    Member
    Posted 2 years ago #

    Fantastic Ross!

Topic Closed

This topic has been closed to new replies.

About this Topic