加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 创建多个WordPress类别div

发布时间:2020-12-13 15:56:11 所属栏目:PHP教程 来源:网络整理
导读:我有一个Wordpress网站,它使用图像替换类别文本.它被设置为有一个post div(填充:20%0;对于一致的响应高度)然后有一个div定位绝对,vert / horiz居中于这个div. HTML div class="indx-img" style="background-image:url('...');" ?php $testStyle = ""; if(h
我有一个Wordpress网站,它使用图像替换类别文本.它被设置为有一个post div(填充:20%0;对于一致的响应高度)然后有一个div定位绝对,vert / horiz居中于这个div.

HTML

<div class="indx-img" style="background-image:url('...');">

        <?php 
        $testStyle = "";

        if(has_category( 'update' ) || has_category( 'uncategorized' )) {
            $testStyle = "style="background-image:url('".get_bloginfo('template_directory')."/img/logo.png')"";
        } elseif(has_category( 'event' )) {
            $testStyle = "style="background-image:url('".get_bloginfo('template_directory')."/img/logo.png')"";
        }
        ?>

            <div class="test" <?php echo $testStyle; ?>></div>

</div>

CSS

.indx-img {
  position: relative;
  padding: 20% 0;
}

.test {
   position: absolute;
   left: 50%;
   margin-left: -5em;
   transform: translateY(-50%);
   -webkit-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
  height: 10em;
  width: 10em;
}

这是一个用于测试的背景图像.这样做的问题是,如果帖子上有多个类别,则只会显示一个.

理想情况下,我希望在“测试”中为应用于具有类别图像的帖子的每个类别创建一个div,彼此相邻.

解决方法

通过您的代码,我猜您的HTML div代码正在运行单个帖子.当您使用has_category检查单个类别时,它将仅为您提供类别.

要获得任何帖子的所有类别,您需要wp_get_post_categories函数.

$post_categories = wp_get_post_categories( $post_id );
$cats = array();

foreach($post_categories as $c){
    $cat = get_category( $c );
    $cats[] = array( 'name' => $cat->name,'slug' => $cat->slug );
}

通过这种方式,您可以获得类别列表,并可以相应地应用样式代码.有关wp_get_post_categories用法的详细信息,请参阅https://codex.wordpress.org/Function_Reference/wp_get_post_categories.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读