【问题标题】:Wordpress - Adding special classes to a specific term loopWordpress - 向特定术语循环添加特殊类
【发布时间】:2016-08-01 22:38:44
【问题描述】:

我想遍历所有帖子以获取自定义帖子类型,但是在循环它们的同时将一个类添加到带有特定术语标记的帖子。

我目前有以下功能,但这只会抓取具有特定术语的帖子,而不是所有的帖子。

/**
 * Get posts of particular termID
*/

function post_type_tax_query($post_type=null, $taxonomy=null, $term_id=null){

    $args = array(
        'posts_per_page'  => -1,
        'post_type'       => $post_type,
        'orderby'         => 'post_date',
        'order'           => 'DESC',
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'field' => 'id',
                'terms' => $term_id
            )
        )
    );

    $the_query = new \WP_Query( $args );
    $queryitems = $the_query->get_posts();

    return $queryitems;

}

我当前的循环与上述

            $projects_posts = post_type_tax_query('projects', 'locked', '5');
                if($projects_posts){ ?>
                    <ul class="full-width projects-grid grid list-style-none">
                    <?php $counter = 1; ?>
                    <?php foreach ($projects_posts as $project):
                            $project_title = get_field('project_title', $project->ID ); // get all the rows
                            $project_image_thumbnail = get_field('project_thumbnail_image', $project->ID); ?>
                            <li class="animation-element bounce-up delay-motion-<?php echo $counter; ?> col-lg-4 col-xs-12 col-sm-6">
                                <a href="<?php echo the_permalink($project->ID); ?>" target="_blank">
                                    <figure class="effect-milo">
                                        <img src="<?php echo $project_image_thumbnail; ?>"/>
                                        <h4><?= $project_title; ?></h4>
                                    </figure>
                                </a>
                            </li>
                    <?php $counter++; ?>
                    <?php endforeach; ?>
                    </ul>
            <?php } ?>  

只是想知道如何编辑上面的内容以确保它循环遍历所有帖子,但将一个类应用于具有术语 5 的特定帖子。这是出于样式目的。

谢谢,

维度

【问题讨论】:

    标签: php wordpress loops posts


    【解决方案1】:

    foreach 循环中,您可以使用has_term() 函数来检查帖子是否属于某个类别。如果是,则添加类或您要执行的任何操作。

    $special_class='';
    if( has_term( $term_id', $taxonomy, $post_id ) ) {
        # in your case term_id = 5
        $special_class='CLASS_YOU_WANT_ADD';
        # Print $special_class into the li class
        # OR Whatever you want to do
    }
    

    【讨论】:

      【解决方案2】:

      我不知道我是否正确理解了这个问题,但可能是这样的:

      <?php if ($term === 'theTerm') :?>
          <div class="classfortheterm"></div>
      <?php endif ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-29
        • 1970-01-01
        • 2018-05-15
        • 1970-01-01
        相关资源
        最近更新 更多