从帖子ID获取Wordpress类别名称不起作用

时间:2014-03-18 00:41:35

标签: php wordpress

问题在于我无法显示帖子的类别:

http://screencast.com/t/hdQjpSV0Q

我在function.php文件中有以下代码:

// GET FEATURED IMAGE
function ST4_get_featured_image($post_ID) {
    $custom_meta = get_post_custom(get_the_ID());
    return $custom_meta["lumen_portfolio_preview_image_image"][0];
}
add_filter('manage_posts_columns', 'ST4_columns_head');
add_action('manage_posts_custom_column', ('ST4_columns_content'), 10, 2);

// ADD NEW COLUMN
function ST4_columns_head($defaults) {

    $defaults['featured_image'] = 'Featured Image';
    $defaults['categories_portfolio'] = 'Category';
    return $defaults;
}

// SHOW THE FEATURED IMAGE
function ST4_columns_content($column_name, $post_ID) {

    if ($column_name == 'featured_image') {
        $post_featured_image = ST4_get_featured_image($post_ID);
        if ($post_featured_image) {
            echo '<img style="width:300px;height:200px;" src="' . $post_featured_image . '" />';
        }
    }
    elseif ($column_name == 'categories_portfolio') {
        $terms = get_the_terms( $post->ID , 'category' ); 
        foreach ( $terms as $term ) {
            $term_link = get_term_link( $term, 'category' );
                if( is_wp_error( $term_link ) )
                    continue;
                echo '<a href="' . $term_link . '">' . $term->name . '</a>';
        } 
    }
}

我有空结果,NULL,但我希望有post类别字段。我使用了很多wordpress功能,但没有成功。

2 个答案:

答案 0 :(得分:0)

我注意到你在get_the_terms函数中使用$ post-&gt; ID作为参数,无论如何我认为问题是你无法检索帖子的类别,我建议使用{{ 3}}代替代码中的get_the_terms函数:

// SHOW THE FEATURED IMAGE
function ST4_columns_content($column_name, $post_ID) {

    if ($column_name == 'featured_image') {
        $post_featured_image = ST4_get_featured_image($post_ID);
        if ($post_featured_image) {
            echo '<img style="width:300px;height:200px;" src="' . $post_featured_image . '" />';
        }
    }
    elseif ($column_name == 'categories_portfolio') {
        //replace this $terms = get_the_terms( $post->ID , 'category' );
        $terms = get_the_category($post_ID); //should you be using this instead of $post->ID?
        foreach ( $terms as $term ) {
            //replace this $term_link = get_term_link( $term, 'category' );
                 $term_link = get_category_link($term->term_id);
                if( is_wp_error( $term_link ) )
                    continue;
                echo '<a href="' . $term_link . '">' . $term->name . '</a>';
        } 
    }
}

您可以执行var_dump($terms)以进一步查看此功能返回的值,希望它有所帮助,欢呼!

答案 1 :(得分:0)

我认为您使用的是自定义帖子类型&#34; Portfolio&#34;如附带的屏幕截图所示。

使用wp_get_post_terms而不是get_the_terms

更新以下代码:

$terms = get_the_terms( $post->ID , 'category' );

$terms = wp_get_post_terms( $post->ID , 'category', array("fields" => "all") );

请注意,第二个参数是您在注册分类时使用的分类名称。

请参阅下面的示例,其中包括“推荐书” - “cat&#39;用于注册分类法。

register_taxonomy('testimonials-cat', 'testimonials', $args);

以上分类法的代码为:

$terms = wp_get_post_terms($post->id, 'testimonials-cat', array("fields" => "all"));