2012-10-16 72 views
0

这是来自我正在处理的一个WordPress站点,但不是一个WP特定的问题。用PHP编写div if/else语句

我有一个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

您需要移动代码。如果您不希望在首页上打印前导<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 
    } 
?> 

这里唯一有趣的事情是,你附上else开幕{}大括号之间的HTML代码+一滴。

+1

为什么不删除'else'并使用'if(!is_front_page()){'? OP只需要在该页面上不需要任何内容​​,因此回显空间是不必要的。 – Eric

+0

OP看起来很困惑,所以我放弃了否定,也保留了冗余的空回声。它只是展示了结构。 – mario

+0

哈哈感谢这个家伙。我其实想到做这样的事情,但并不认为你可以在html if/else语句中查找html。 'if(!is_front_page()){'似乎够简单,所以我会用它。干杯! – Jascination

0

把你的回声到一个变量,而不是将它们打印的,然后经过你的if语句做

回声(是$ var ==“”)? '':''。$ var。'';

最后2组单引号之间的Html标签

+0

-1/2:这不是一个非常可读的方式来做到这一点。 –