-1

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/

  • _“the site crashes”_ - meaning the same as the famous “blank page”? Then go enable proper PHP error reporting first of all, https://stackoverflow.com/questions/1475297/phps-white-screen-of-death – misorude Aug 13 '19 at 12:58
  • `echo $category[0]->cat_name;` try it – Alive to die - Anant Aug 13 '19 at 12:59
  • do `var_dump($categories);` after `$categories = get_the_category();` and show us what you got? (add in your question by editing it) – Alive to die - Anant Aug 13 '19 at 13:08
  • @misorude I mean I get this message: The site is experiencing technical difficulties. – Emil Dam Sørensen Aug 13 '19 at 13:11
  • @AnantSingh---AlivetoDie I just tried that. Can you please write the exact function, since I'm really new to this, just to make sure I'm doing it right. – Emil Dam Sørensen Aug 13 '19 at 13:11
  • _“The site is experiencing technical difficulties.”_ - that’s likely just a generic error document for a 500 error, so you need to go and check the server error log to find out what the actual error was. – misorude Aug 13 '19 at 13:14

1 Answers1

1

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