用PHP if / else语句编写div

时间:2012-10-16 03:39:39

标签: php if-statement

这是来自我正在研究的wordpress网站,但不是特定于WP的问题。

我有一个if / else PHP语句,用于检查用户是否正在查看我站点的主页。如果他们正在查看主页,我希望代码什么都不做。如果它们不是,我希望它在配置中显示页面标题。

我目前的代码是:

<div class="page-header">
  <h1>
    <?php
    if ( is_front_page()){
        echo ' ';
    }
    elseif (is_home()) {
        if (get_option('page_for_posts', true)) {
          echo get_the_title(get_option('page_for_posts', true));
        } else {
          _e('Latest Posts', 'roots');
        }
      } elseif (is_archive()) {
        $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
        if ($term) {
          echo $term->name;
        } elseif (is_post_type_archive()) {
          echo get_queried_object()->labels->name;
        } elseif (is_day()) {
          printf(__('Daily Archives: %s', 'roots'), get_the_date());
        } elseif (is_month()) {
          printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
        } elseif (is_year()) {
          printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
        } elseif (is_author()) {
          global $post;
          $author_id = $post->post_author;
          printf(__('Author Archives: %s', 'roots'), get_the_author_meta('display_name', $author_id));
        } else {
          single_cat_title();
        }
      } elseif (is_search()) {
        printf(__('Search Results for %s', 'roots'), get_search_query());
      } elseif (is_404()) {
        _e('File Not Found', 'roots');
      } else {
        the_title();
      }
    ?>
  </h1>
</div>

我知道echo ' ';可能是关闭的,但我是一个绝对的php初学者!目前,这会创建一个空的<div><h4>标记,但我宁愿清理它并在主页上根本不创建任何内容。

如何才能最好地修改上面的代码来实现这个目标?

2 个答案:

答案 0 :(得分:3)

您需要移动代码。如果您不希望在首页上打印前导<div><h1>,请在此之前移动if检查。添加else,然后打印<div><h1>,大if / else代码blob和结束</div>等。

另请阅读switching in and out of PHPs code and html mode 尽管如此,最好通过展示来解释:

<?php
    if ( is_front_page()){
        echo ' ';
    }
    else {
?>
<div class="page-header">
  <h1>
    <?php

    if (is_home()) {
        if (get_option('page_for_posts', true)) {
          echo get_the_title(get_option('page_for_posts', true));

       /*

           ...

       */

      } else {
        the_title();
      }
    ?>
  </h1>
</div>
<?php
     }
?>

这里唯一有趣的是你将html +代码blob包含在else的开头{和结束}大括号之间。

答案 1 :(得分:0)

将你的回声放入变量而不是打印它们,然后在你的if语句之后

echo($ var =='')? '':''。$ var。'';

最后两组单引号之间的Html标记