【问题标题】:Wordpress - How to fix the if / else codeWordpress - 如何修复 if / else 代码
【发布时间】:2016-10-06 19:21:06
【问题描述】:

我正在尝试根据当前类别显示不同的样式。所以我正在尝试使用 if/else 来做到这一点。但是,当我加载页面时,什么都没有出现......

提前致谢。

<?php 

if (have_posts()) : while (have_posts()) : the_post(); 
$current_section = single_cat_title(); 

     if ($current_section == "music") {
?>

        <li class="music_post"><a href="<?php the_permalink(); ?>">
           <h1><?php the_title(); ?></h1>
        </a></li>

<?php 
     } 
     elseif ($current_section == "blog") 
     {
?>

        <li class="blog_post"><a href="<?php the_permalink(); ?>">
           <h1><?php the_title(); ?></h1>
        </a></li>


 <?php 
      } 
 ?>
 <? endwhile;?>
 <? endif; ?>

【问题讨论】:

  • 你到底想做什么,会发生什么?您尝试了哪些方法,为什么不起作用?
  • $current_section 是音乐还是博客?将另一个 else 添加到默认值
  • 我正在尝试为博客类别和音乐类别展示不同的风格。所以,我添加了 if/else,但没有任何反应......

标签: php html wordpress


【解决方案1】:

你需要这样理解条款:

 global $post;
 $terms = get_the_terms($post->id, 'name_of_taxonomy');

这会返回一个有用值的数组,您可以在其中使用:

$currentTerm = $terms[0]->slug;

现在你可以检查了

if ($currentTerm == 'music'){
 // ...
}else{
//...
}

对不起,改用这个:

$terms = $wp_query->queried_object;;
echo $terms->slug;

【讨论】:

  • 您好!它显示了一个致命错误:致命错误:无法在第 60 行的 /home/landserver/jorgeferreiro/wp-content/themes/jorge_ferreiro/category.php 中使用类型为 WP_Error 的对象作为数组
【解决方案2】:

试试这个

<?php 

if (have_posts()) : while (have_posts()) : the_post(); 
global $post;
$terms = get_the_terms($post->id, 'name_of_taxonomy');
$current_section = $terms[0]->slug;
if ($current_section != "") {
?>

<li class="<?php if ($current_section == "music") { ?>music_post<?php } elseif ($current_section == "blog") {?>blog_post<?php } ?>"><a href="<?php the_permalink(); ?>">
   <h1><?php the_title(); ?></h1>
</a></li>

<?php } ?>

 <? endwhile;?>
 <? endif; ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多