我有一个foreach语句,它循环遍历WordPress安装的所有页面,并将它们列在div中(使用get_pages()函数)。
它目前看起来像这样:
<?php
$pages = get_pages();
foreach ( $pages as $page ) {
$linkPage = '<a class="order" href="' . get_page_link( $page->ID ) . '">';
$linkPage .= $page->post_title;
$linkPage .= '</a>';
echo $linkPage;
}
?>
我现在需要做的是添加一个 if 语句,该语句在 class="order... 如果链接是来自当前页面的链接,则在 class="order... 之后插入字符串"current"。
这似乎是一个愚蠢的问题,但我是一个几乎没有PHP经验的前端开发人员,每次我尝试添加if.if我遇到语法错误时,都声称有一个意外的if语句。
我希望我把自己说清楚了。如果可以提供任何帮助,将不胜感激。
<?php
//get id of your current page
$post_id = $post[0]->ID;
$pages = get_pages();
foreach ( $pages as $page ) {
$current = $post_id == $page->ID ? ' current' : '';
$linkPage = '<a class="order '.$current.'" href="' . get_page_link( $page->ID ) . '">';
$linkPage .= $page->post_title;
$linkPage .= '</a>';
echo $linkPage;
}
?>
检查一下,我不确定$post_id = $post[0]->ID
是否适用于您的 wp 版本,但 if 语句逻辑是正确的并且会起作用。尝试回声$post_id
,如果有什么问题,$current
。
试试这段代码:
<?php
//get id of your current page
$post_id = get_the_ID();
$pages = get_pages();
foreach ( $pages as $page ) {
//Condition statement to add the class current
$current = $post_id == $page->ID ? 'current' : '';
$linkPage = '<a class="order '.$current.'" href="' . get_page_link( $page->ID ) . '">';
$linkPage .= $page->post_title;
$linkPage .= '</a> <br> ';
echo $linkPage;
}
?>
希望这对您有所帮助...