简体   繁体   English

如何编写仅显示一个类别的函数?

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

I want my wordpress page to show recent posts, with just one category. 我希望我的wordpress页面仅显示一个类别,显示最近的帖子。 I'm new to PHP and wordpress, so please bear with me. 我是PHP和wordpress的新手,请耐心等待。

$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. 当我将此代码粘贴到我的functions.php中时,该站点崩溃了。

You can see the site here: http://2016.sv.emil2518.mguro.sde.dk/skatersmag/ 您可以在此处查看该站点: 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. 发送帖子ID,检查帖子所属的类别有多少,如果有多个类别,则返回false,如果类别只有一个,则返回类别。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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