【问题标题】:if/else in php and echo html codephp 中的 if/else 和 echo html 代码
【发布时间】:2016-02-11 09:47:30
【问题描述】:

在下面的代码中,我正在检查如果我在网站的主页上,那么我会将列向右移动 2,对于所有其他页面,我不应该有任何偏移.我正在尝试实现这一点,但出现错误。如果您能给我一个提示,那就太好了。谢谢!

    <?php if (is_front_page() ) {
        echo '<div class="col-md-8 la-content-inside col-md-offset-2">';
        while ( have_posts() ) { the_post(); }
    } else {
        echo '<div class="col-md-8 la-content-inside">';
        while ( have_posts() ) { the_post(); }
    }
    ?>

                <?php get_template_part( 'content', 'page' ); ?>

            <?php endwhile; // end of the loop. ?>
        </div>

【问题讨论】:

  • 尝试将while ( have_posts() ) : the_post();更改为while ( have_posts() ) { the_post(); }并请描述错误
  • 我认为您正在使用三元 while 并没有结束。它应该像“while (have_posts()) : the_post(); endwhile;”
  • 我的原始代码是:--->
    -------------- 我想让这部分代码只在其他页面而不是主页上工作。对于主页,我想要 2 的列偏移量

标签: php html wordpress if-statement echo


【解决方案1】:

在您的代码中,您在ifelse 块中打开while 块并在条件块之后关闭endwhile

尝试使用

<?php  
if (is_front_page() ) {
    echo '<div class="col-md-8 la-content-inside col-md-offset-2">';
    while (have_posts()) : the_post(); 
        get_template_part( 'content', 'page' );
    endwhile; // end of the loop.
}else {
    echo '<div class="col-md-8 la-content-inside">';
    while (have_posts()) : the_post();
        get_template_part( 'content', 'page' );
    endwhile; // end of the loop. 
}
?>

【讨论】:

  • 无法正常工作,因为您的格式不正确
  • 答案已更新,感谢@FerryKobus。我复制了提问者提供的代码,忘记删除花括号。
  • 欢迎您@RaviKrishna。如果您对我的回答投赞成票,我将非常感激您,谢谢
【解决方案2】:

让我们从清理代码开始。我将代码写在几行上,因此对于提出问题的人来说仍然可以理解。 (是的,你可以写得更高效)

<?php
echo '<div class="col-md-8 la-content-inside';
// frontpage exception
if(is_front_page()) {
     echo ' col-md-offset-2';
}
echo '>';

while(have_posts()) {
    the_post();
    get_template_part( 'content', 'page' );
}
echo '</div>';
?>

如果这会产生错误。请将错误复制粘贴到此答案中作为注释。

【讨论】:

    【解决方案3】:

    试试下面的短代码..将为您服务..

    <div class="col-md-8 la-content-inside <?php echo (is_home() ? 'col-md-offset-2' : '' );?> ">
     <?php while (have_posts()) : the_post(); 
          get_template_part( 'content', 'page' );
       endwhile; // end of the loop.
     ?>
     </div>
    

    您需要使用is_home() 函数.. 用于首页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多