【问题标题】:PHP if statement inside foreach to check WordPress pagesPHP if 语句在 foreach 中检查 WordPress 页面
【发布时间】:2015-03-19 12:10:57
【问题描述】:

我有一个 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... 之后插入字符串 "current"从当前页面。

这似乎是一个愚蠢的问题,但我是一个前端开发人员,几乎没有 PHP 经验,每次我尝试添加 if 时都会遇到语法错误,声称出现了意外的 if 语句。

我希望我说清楚了。 如果能提供任何帮助,将不胜感激。

【问题讨论】:

  • 添加带有错误 if 语句的完整代码 :)

标签: php html wordpress content-management-system wordpress-theming


【解决方案1】:
<?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]-&gt;ID 是否适用于您的 wp 版本,但 if 语句逻辑是正确的并且会起作用。如果有问题,请尝试回显$post_id$current

【讨论】:

  • 谢谢,我唯一要做的就是将 $post_id = $post[0]->ID; 更改为 $post_id = $post->ID ;,而且效果很好。
【解决方案2】:

试试这个代码:

<?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;
}
?>

希望对你有所帮助...

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多