2015-12-21 65 views
0

尋找您的幫助和建議。 我有一個在Wordpress中鏈接到single的列表。我只需將類active僅放置到活動頁面的li。將`active`類添加到當前單個頁面的wordpress內容

應該是這樣的形象enter image description here

上,但它是:

enter image description here

我的WP-代碼:

<ul class="inline-list medium-6 large-4 skill-items"> 
<?php 
    $id = get_the_ID(); 
    // echo $id; 
    $class; 
    $skills = new WP_Query(array(
     'post_type' => 'skills', 
     'order' => 'ASC' 
     )); 
    if ($skills->have_posts()) : while ($skills->have_posts()) : $skills->the_post(); 
    // echo $post->ID; 
    if($id == $post->ID) {$class = 'active';} else {$class = '';} 
    ?> 
    <li class="<?php echo $class; ?>"><a href="<?php echo esc_url(get_permalink()); ?>"><?php the_title(); ?></a></li> 
    <?php endwhile; endif; wp_reset_query(); 
?> 
</ul> 
+0

您是否嘗試過使用WordPress的類'current-menu-item' –

+0

甚至不考慮將您的導航菜單項存儲在CPT中並循環播放。只是使用標準的'nav_menu'和我提供的正確答案 – Trix

回答

2

這不是在Wordpress中執行菜單的正確方法。您應該使用wp_nav_menu而不是自定義WP_Query

首先,在的functions.php添加以下register a new menu

add_action('after_setup_theme', 'register_my_menu'); 
function register_my_menu() { 
    register_nav_menu('skills_menu', __('Skills menu', 'your-theme-name')); 
} 

然後登錄你的管理,你會看到在外觀>菜單新的菜單佈局。爲該展示位置創建一個新菜單 - 您可以自動將頂級新頁面添加到該菜單。

然後在你的模板中添加以下以顯示菜單:

<?php wp_nav_menu(array('theme_location' => 'skills_menu')); ?> 

Wordpress will automatically handle the active class加入current-menu-item到合適的li。不需要任何過濾器。

-1

你可以試試這個:

function my_alter_classes_on_li($classes, $item){ 
    global $post; 
    if(in_array($post->post_type, $classes)) $classes[] = 'current-menu-item'; 
    return $classes; 
} 
add_filter('nav_menu_css_class', 'my_alter_classes_on_li', 10, 2); 
+0

他沒有使用'wp_nav_menu' ... – vard

+0

找到答案使用jQuery,將發佈爲答案 – vladja

+0

@vard如果是這樣,他/她是錯誤的。沒有理由有人不使用這種有用的東西。我提供的答案並不需要這樣愚蠢的東西,jQuery等解決方法。如果他需要正確的答案,我提供了一個 – Trix

1

發現使用Javascript/jQuery

jQuery(document).ready(function($){ 
var pgurl = window.location.href; 
$("ul.skill-items li").each(function(){ 
    if($(this).find('a').attr("href") == pgurl || $(this).find('a').attr("href") == '') 
    $(this).addClass("active"); 
}) 
}); 

pgurl包含您目前的網址爲我的問題的答案。之後,我們正在尋找每個項目anchor及其鏈接。然後我們正在comapring這些鏈接,如果它們是相同的,我們將類active添加到li

相關問題