【发布时间】:2014-10-21 17:29:50
【问题描述】:
需要帮助理解使用“if elseif else”语句的正确方法。下面的代码 A 有效,但它正确吗?我可以用“elseif”结束陈述吗?还是“if”语句应该以“endif”或“else”结尾?
代码 A:此代码有效
但请注意,它不以“endif”或“else”结尾。
if ( is_page( 'contact' ) ) { get_template_part('inc/contact'); }
elseif ( is_page( 'policy' ) ) { get_template_part('inc/policy'); }
elseif ( is_page( 'about' ) ) { get_template_part('inc/about'); }
elseif ( is_page( 'terms' ) ) { get_template_part('inc/terms'); }
?>
.
所有“if 语句”都应该以“endif”结尾吗?如果是的话,你能告诉我代码吗?
在下面的代码 B 中使用“endif”会导致白屏错误。
代码 B:endif 不起作用
if ( is_page( 'contact' ) ) { get_template_part('inc/contact'); }
elseif ( is_page( 'policy' ) ) { get_template_part('inc/policy'); }
elseif ( is_page( 'about' ) ) { get_template_part('inc/about'); }
elseif ( is_page( 'terms' ) ) { get_template_part('inc/terms'); }
endif;
?>
.
最后一个“elseif”应该是“else”吗?如果是的话,你能告诉我代码吗?
在下面的 CODE C 中使用“else”会导致白屏错误。
代码 C:“else”而不是“elseif”不起作用
if ( is_page( 'contact' ) ) { get_template_part('inc/contact'); }
elseif ( is_page( 'policy' ) ) { get_template_part('inc/policy'); }
elseif ( is_page( 'about' ) ) { get_template_part('inc/about'); }
else ( is_page( 'terms' ) ) { get_template_part('inc/terms'); }
?>
【问题讨论】:
-
您是否考虑过为此使用开关?它会更容易阅读!
-
您也可以使用数组将页面映射到路径,这样会更容易维护。
-
@joroen 你能告诉我如何将 CODE A 转换为“将页面映射到路径的数组”吗?我不知道该怎么做
标签: php wordpress if-statement