首页 文章

将自定义分类法作为类名添加到自定义帖子类型的存档页面,wordpress

提问于
浏览
0

我认为这很容易,虽然它证明非常困难 . 我的最终目标是将jQuery同位素整合到我的wordpress组合中 . 我已经让同位素在wordpress之外工作了,但是我很难将自定义分类法作为类名分配 . 所以我不需要同位素的帮助,只需将分类法分配为类 .

我有一个自定义的职位类型的投资组合

该投资组合有2个自定义分类,我想用它来过滤我在存档页面上的结果 . 一种分类是“媒体”,另一种是“运动”

因此,如果我将“打印”的媒体分类和“本地”的广告系列分配给投资组合中的帖子,我希望存档页面上的输出是这样的:

<div id="post-34" class="print local">...</div>

但是我现在有这个

<div id="post-34" class>...</div>

我遵循了get_the_terms上的codex指令 . 我将此代码添加到我的functions.php文件中:

<?php // get taxonomies terms links
function custom_taxonomies_terms_links() {
    global $post, $post_id;
    // get post by post id
    $post = &get_post($post->ID);
// get post type by post
    $post_type = $post->post_type;
// get post type taxonomies
    $taxonomies = get_object_taxonomies($post_type);
    foreach ($taxonomies as $taxonomy) {
        // get the terms related to post
        $terms = get_the_terms( $post->ID, $taxonomy );
        if ( !empty( $terms ) ) {
            $out = array();
            foreach ( $terms as $term )
                $out[] = '<a href="' .get_term_link($term->slug, $taxonomy) .'">'.$term->name.'</a>';
        $return = join( ', ', $out );
    }
}
return $return;
} ?>

然后我在echo-portfolio.php页面的循环中将echo调用放入类调用中,如下所示:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

        <div id="post-<?php the_ID(); ?>" class="<?php echo custom_taxonomies_terms_links(); ?>">

任何帮助将不胜感激 . 这让我疯狂,我无法弄清楚这一点 .

1 回答

  • 1

    wordpress有一个干净的方式输出帖子项的类名 - 使用 post_class 所以在你的情况下首先将div设置为

    <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>...</div>
    

    并将分类法名称添加到类中,您必须添加过滤器 . 因此,在您的functions.php中将其删除(将YOUR_TAXO_NAME更改为自定义分类的名称):(取自here

    add_filter( 'post_class', 'custom_taxonomy_post_class', 10, 3 );
    
        if( !function_exists( 'custom_taxonomy_post_class' ) ) {
    
            function custom_taxonomy_post_class( $classes, $class, $ID ) {
    
                $taxonomy = 'YOUR_TAXO_NAME';
    
                $terms = get_the_terms( (int) $ID, $taxonomy );
    
                if( !empty( $terms ) ) {
    
                    foreach( (array) $terms as $order => $term ) {
    
                        if( !in_array( $term->slug, $classes ) ) {
    
                            $classes[] = $term->slug;
    
                        }
    
                    }
    
                }
    
                return $classes;
    
            }
    
        }
    

    (对于多个分类法添加数组)

    $taxonomy = array('YOUR_TAXO_NAME_1', 'YOUR_TAXO_NAME_2');
    

    并且应该将帖子类型名称以及标记的分类法添加到div类中

相关问题