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

290

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/

995

Answer

Solution:

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;
}

People are also looking for solutions to the problem: php - How to dynamically load a list of classes?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.