【问题标题】:Custom Post Type active link - Wordpress自定义帖子类型活动链接 - Wordpress
【发布时间】:2016-01-18 20:42:07
【问题描述】:

我的 wordpress 网站上有一个名为“学校”的自定义帖子类型。当您将鼠标悬停在学校选项卡上时,子菜单中会显示学校列表。这些是我用不同学校名称创建的页面。现在,当您单击其中一个学校页面时,我有一个包含所有学校的侧边栏,因此他们可以从侧边栏浏览不同的学校,而不是使用菜单。

我使用以下 sn-p 填充侧边栏。

while( $shools_loop->have_posts() ) : $schools_loop->the_post();

  $content .= '<li class="schools-list">';
  $content .= '<a href="'.get_permalink().'">'.get_the_title().'</a>';
  $content .= '</li>';

endwhile;

这非常有效,我可以通过侧边栏毫无问题地浏览所有学校。当我通过侧边栏或导航查看学校时,我试图找到一种方法,当我在活动页面上时,我会为活动页面的 li 创建一些 CSS 样式。我已经想出了如何使用导航菜单来做到这一点。但在侧边栏菜单上需要帮助。由于正在填充侧边栏列表菜单,我不确定如何检查自定义帖子类型链接是否处于活动状态并对应于 /schools/get-title 页面。

我在网上找到了类似的东西并尝试对其进行编辑,但我不确定这是否仅适用于导航菜单

add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'services',
    array(
      'labels' => array(
        'name' => __( 'Services' ),
        'singular_name' => __( 'Services' )
      ),
    'public' => true,
    'has_archive' => true,
    'rewrite' => array('slug' => 'services'),
    )
  );
}

// highlight active custom post page in nav
add_filter( 'nav_menu_css_class', 'namespace_menu_classes', 10, 2 );
function namespace_menu_classes( $classes , $item ){
  if ( get_post_type() == 'services' ) {
    // remove unwanted classes if found
    $classes = str_replace( 'current_page_parent', '', $classes );
    // find the url you want and add the class you want
    if ( $item->url == 'services/physical-therapy-services/' ) {
      $classes = str_replace( 'menu-item', 'menu-item current_page_parent', $classes );
    }
  }
  return $classes;
  }

基本上需要找到一种方法来检查自定义帖子类型是否处于活动状态。

【问题讨论】:

  • “服务”应改为“学校”

标签: php jquery css wordpress


【解决方案1】:

您可以在主模板页面中使用当前帖子的 ID 设置 global 变量,然后在侧边栏循环中,您可以检索该 global 变量并使用 get_the_ID() 将其与当前帖子的 ID 进行比较函数,然后执行必要的操作。

例子:

single-cpt.php

// Inside the loop
global $post_id = get_the_ID();

sidebar-cpt.php

$post_id = isset($_GLOBALS['post_id']) ? $_GLOBALS['post_id'] : 0;
while( $shools_loop->have_posts() ) : $schools_loop->the_post();
  if($post_id == get_the_ID()){
      // This is the active link
      $content .= '<li class="schools-list selected">';

  } else {
      $content .= '<li class="schools-list">';

  }

  $content .= '<a href="'.get_permalink().'">'.get_the_title().'</a>';
  $content .= '</li>';

endwhile;

【讨论】:

  • 你能给我一个粗略的例子吗?
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2012-04-10
  • 2018-07-03
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
相关资源
最近更新 更多