【问题标题】:Wordpress - Add "active" class if current page is activeWordpress - 如果当前页面处于活动状态,则添加“活动”类
【发布时间】:2012-05-21 19:22:11
【问题描述】:
<?php
          if($post->post_parent)
          $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
          else
          $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
          if ($children) {
        $parent_title = get_the_title($post->post_parent);?>

        <li><a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo $parent_title;?></a></li>
          <?php echo $children; ?>
    <?php } ?>

上面的代码在一个列表中列出了父页面和所有子页面。

父页面
子页面
子页面 class="活动"
子页面
子页面

我想在当前活动页面中添加一个“活动”类。任何帮助是极大的赞赏。谢谢

【问题讨论】:

    标签: php css wordpress


    【解决方案1】:

    要查找特定页面并向其添加活动类,您可以尝试使用 is_page 并定义页面的 URL/slug。

    <a  class="<?php if (is_page('name-of-page')) echo 'active'; ?>" href="#">Link</a>
    

    【讨论】:

      【解决方案2】:

      您可以通过检查$post-&gt;post_title 和$item-&gt;title 来轻松添加活动类和其他类

      function addLinkClassesWithActive( $atts, $item, $args ) {
          global $post;
          // check if the item is in the primary menu
          if( $args->theme_location == 'main-nav' ) {
              // add the desired attributes:
              $atts['class'] = $post->post_title === $item->title ? 'mdl-layout__tab is-active' : 'mdl-layout__tab';
          }
          return $atts;
      }
      add_filter( 'nav_menu_link_attributes', 'addLinkClassesWithActive', 10, 3 );
      

      我自己使用它并去掉包装容器、ul 和 li 标签,这样我就只有一个链接。请参见下面的示例。

      <nav role="navigation" class="mdl-navigation mdl-layout--large-screen-only" itemscope itemtype="http://schema.org/SiteNavigationElement">
          <div class="mdl-tabs mdl-js-tabs mdl-js-ripple-effect">
              <?php
              $primaryMenu = array(
                  'container' => false,
                  'theme_location' => 'main-nav',
                  'items_wrap' => '%3$s',
                  'echo' => false,
              );
              echo strip_tags( wp_nav_menu( $primaryMenu ), '<a>' );
              ?>
          </div>
      </nav>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多