简体   繁体   中英

How do I write a function for showing only one category?

I want my wordpress page to show recent posts, with just one category. I'm new to PHP and wordpress, so please bear with me.

$categories = get_the_category();

if ( ! empty( $categories ) ) {
    echo esc_html( $categories[0]->name );   
}

When I past this code into my functions.php, the site crashes.

You can see the site here: http://2016.sv.emil2518.mguro.sde.dk/skatersmag/

Send the post id, check haw many categories the post belongs to and return false if there are more than one, and return the category if it is only one.

function get_posts_with_only_one_category( $postId ) {
    $terms = wp_get_post_terms( $postId, 'category' );
    $term = false;

    if( count( $terms ) == 1 ) {
        $term = $terms[0]->name;
    }

    return $term;
}

Later when you do the looping through the posts you can check:

// loop
$ifOnlyOne = get_posts_with_only_one_category( get_the_ID() );

if( $ifOnlyOne == false ) {
   continue;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM