这是来自我正在处理的一个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>
标签,但我宁愿将其清理干净,并在主页上根本不创建任何内容。
如何才能最好地修改上面的代码来实现这一目标?
为什么不删除'else'并使用'if(!is_front_page()){'? OP只需要在该页面上不需要任何内容,因此回显空间是不必要的。 – Eric
OP看起来很困惑,所以我放弃了否定,也保留了冗余的空回声。它只是展示了结构。 – mario
哈哈感谢这个家伙。我其实想到做这样的事情,但并不认为你可以在html if/else语句中查找html。 'if(!is_front_page()){'似乎够简单,所以我会用它。干杯! – Jascination