在WordPress中获取类别名称-高效或";坏的”;密码


Get the Category Name in WordPress - efficient or "bad" code?

这是一个更多关于代码最佳实践的问题:

$cat_name = get_the_category()[0]->name;

不需要用几个变量,只需几个步骤:

$cat = get_the_category();
$cat_name = $cat[0]->name;

这被认为是不良做法吗?还是有任何问题?如果是,为什么?同样,我的问题是关于代码,而不是结果。

我认为这取决于您是否将php设置为显示通知,以及您是否关心未定义的偏移通知。问题是(国际海事组织)。查看功能的开始:

function get_the_category( $id = false ) {
    $categories = get_the_terms( $id, 'category' );
    if ( ! $categories || is_wp_error( $categories ) )
        $categories = array();

您可以看到,如果没有类别或"发生"错误,该方法将返回一个空数组。正在进行快速测试。。。

<?php
$categories = array();
echo $categories[0]->name;

我们得到

Notice: Undefined offset: 0 in test.php on line 5
Notice: Trying to get property of non-object in test.php on line 5

看到问题了吗?

可能最好:

$cat = get_the_category();
if ($cat)
{
    $cat_name = $cat[0]->name;
}