【问题标题】:Echo a class if current page matches the li name in wordpress如果当前页面与 wordpress 中的 li 名称匹配,则回显一个类
【发布时间】:2015-06-25 17:57:35
【问题描述】:

我试图找到一些逻辑,只有当当前页面标题与 li 中的标题匹配时才会回显一个类。我无法提出一个不适用于此查询中所有 li 的“if”语句。

这是在 wordpress 中。

这是上下文:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
   <li><a href="<?php the_permalink(); ?>" <?php if(NEED LOGIC HERE) echo 'class="current"'; ?>><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); endif; ?>

任何帮助将不胜感激!

【问题讨论】:

  • 你到底在哪里使用这个?使用nav menu 可能更相关吗? -然后会“自动”添加许多有用的类...
  • 是的,导航菜单在大多数情况下可能会做到这一点,但我正在从头开始为其他一些自定义功能构建它。 wp_nav 往往会妨碍某些自定义。

标签: php wordpress class if-statement echo


【解决方案1】:

如果您知道您在某种single 上(即页面、帖子或类似内容),那么我想您可以在自定义循环之前保存该 ID 并比较一下:

global $post;
//Make sure you are on a single, otherwise you'll get funny results
if (is_single()) {
    $saved_id = $post->ID;
} else {
    $saved_id = false;
}

if (have_posts()) {
    while (have_posts()) {
        the_post();
        echo '<li><a href="' . get_the_permalink() . '"';
        if($saved_id === $post->ID) {
            echo 'class="current"';
        }
        echo '>';
        the_title();
        echo '</a></li>';
    }
    wp_reset_query();
 }

...抱歉完全更改了代码样式,我无法使用模板标签使其可读。

哦,当然你可以比较标题,如果这实际上更可取(尽管显然不太精确),只需使用 get_the_title()$post-&gt;post_title 而不是 $post-ID

【讨论】:

  • 是的,这也有效。我在下面的答案中做了类似但不同的事情。感谢您的帮助!
【解决方案2】:

好的,我想通了。我需要跳出循环来创建一个有效的 if 语句来读取查询中的链接和当前页面。注意 $titleID。

<?php
    $titleID = (get_the_title());
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $parentID = (wp_get_post_parent_id( $post_ID ));
    $args= array(
        'posts_per_page' => -1,
        'post_type' => 'page',
        'post_parent' => $parentID,
        'paged' => $paged
        );
        query_posts($args);
    ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?> 
        <li><a href="<?php the_permalink(); ?>" <?php if(get_the_title() == $titleID ) echo 'class="current"'; ?>><?php the_title(); ?></a></li>            
    <?php endwhile; wp_reset_query(); endif; ?>

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多