自定义发布类型和分类重写错误

时间:2011-08-29 作者:Evan Yeung

以下代码改编自Jan Fabry的回答。Mixing custom post type and taxonomy rewrite structures?

<?php
add_filter(\'post_type_link\', \'client_area_permalink\', 10, 4);
function client_area_permalink($post_link, $post, $leavename, $sample) {
    if ( false !== strpos( $post_link, \'%client_category%\' ) ) {
        $glossary_letter = get_the_terms( $post->ID, \'client_category\' );
        $post_link = str_replace( \'%client_category%\', array_pop( $glossary_letter )->slug, $post_link );
    }
    return $post_link;
}
?>
当我去添加新帖子时,array_pop 引发错误。我相信这是因为这篇文章还没有相关的分类法。array_pop error

如何修复此错误?我考虑过使用get_post_permalink 作为基地,因为那是post_type_link 被钩住了。

1 个回复
最合适的回答,由SO网友:Drew Gourley 整理而成

为了避免这样的错误,您必须检查$glossary\\u letter的值是否为数组。由于get\\u the\\u terms()在失败时返回false,因此您只需检查$glossary\\u letter是否为false,并将其设置为空数组,以平息array\\u pop()的错误。

<?php
add_filter(\'post_type_link\', \'client_area_permalink\', 10, 4);
function client_area_permalink($post_link, $post, $leavename, $sample) {
    if ( false !== strpos( $post_link, \'%client_category%\' ) ) {
        $glossary_letter = get_the_terms( $post->ID, \'client_category\' );

        // adding check and reset
        if ( !$glossary_letter ) { $glossary_letter = array(); }
        // continue as you were

        $post_link = str_replace( \'%client_category%\', array_pop( $glossary_letter )->slug, $post_link );
    }
return $post_link;
}
?>

结束

相关推荐