PHP foreach 中的 if 语句检查 WordPress 页面

PHP if statement inside foreach to check WordPress pages

我有一个 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.. . 如果 link 是当前页面中的那个。

这似乎是一个愚蠢的问题,但我是一名 PHP 经验很少的前端开发人员,每次我尝试添加 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;
}
?>

希望这对您有所帮助...