【问题标题】:Wordpress: Modifying the content functionWordpress:修改内容功能
【发布时间】:2015-09-15 01:22:36
【问题描述】:

有没有办法修改 the_content() 函数?我想在显示自定义分类负和正分类时添加一个 CSS 类。

例子:

<p class="positive">this is a content for the positive taxonomy</p>
<p class="positive">this is a content for the positive taxonomy</p>
<p class="negative">this is a content for the negative taxonomy</p>

我想在author.php代码中应用它:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
                  <?php the_content(); ?>
                <?php endwhile; else: ?>
                <p><?php _e('No posts by this author.'); ?></p>
              <?php endif; ?> 

带有function.php

add_action( 'pre_get_posts', function ( $q ) {

    if( !is_admin() && $q->is_main_query() && $q->is_author() ) {

        $q->set( 'posts_per_page', 100 );
        $q->set( 'post_type', 'custom_feedback' );

    }

});

PS:我在这里使用自定义帖子类型和自定义分类法,分为正面和负面两类。

【问题讨论】:

    标签: php css wordpress custom-taxonomy


    【解决方案1】:

    您可以使用has_term() 来测试帖子是否具有特定术语。或者,您可以使用get_the_terms 获取附加到帖子的条款,并在您的 css 类中使用术语 slug 作为值。如果帖子附加了多个术语,这有点不可靠

    解决方案 1

    <?php
        $class = '';
        if ( has_term( 'positive', 'custom_taxonomy' ) ) {
            $class = 'positive';
        } elseif ( has_term( 'negative', 'custom_taxonomy' ) ) {
            $class = 'negative';
        } 
    ?>
    
    <div class="entry-content ><?php echo $class ?>">
        <?php the_content(); ?>
    </div>
    

    解决方案 2

    <?php
    $terms = get_the_terms( $post->ID, 'custom_taxonomy' );
    $class = $terms ? $terms[0]->slug : 'normal';
    ?>
    
    <div class="entry-content ><?php echo $class ?>">
        <?php the_content(); ?>
    </div>
    

    用法

    您现在可以使用 CSS 选择器来定位您的内容

    .entry-content positive {}
    .entry-content negative {}
    

    【讨论】:

    • 哇..太棒了!代码不是那么长,但它可以工作。你是天才兄弟。非常感谢。致敬!!
    • 我的荣幸。享受:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多