Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have three different levels on articles, Level1, level2 and level3. In the main section of my homepage, I show all three types of articles, but I want the user to have the option to hide/remove Level3-articles.

The Levels are saved in the database as a meta_value. Each post got its level as a class; <article class="news-entry Level3">

So, to the question: How can I let visitors toogle to show/hide the Level3-articles? Preferabbly without reloading the page. Perhaps a simple display:none, but I do not know how to make this.

Thanks!

share|improve this question

1 Answer 1

up vote 1 down vote accepted

JavaScript is your friend! More specifically jQuery is your friend.

You can us wp enqueue script and do something like this:

Add this to your themes functions.php

<?php
function my_scripts_method() {
    wp_enqueue_script('jquery');            
}    

add_action('wp_enqueue_scripts', 'my_scripts_method'); //
?>

Then either in your header or by writing a custom .js file then enquiring it use the following

jQuery(document).ready(function($) {
     $('.hide_level3_button').click(function(){
          $('.Level3').toggle();
         return false;
   });
});

Then just give your toggle button a class of hide_level3_button and you're good to go.

JS Fiddle: http://jsfiddle.net/BandonRandon/nzE7F/

UPDATE: You can also use fadeToggle() to mak them fad out which may look better http://jsfiddle.net/BandonRandon/nzE7F/1/

EDIT To add make it work on page load I would add the jQuery cookie plugin and change the javascript to this:

    jQuery(document).ready(function($) {
    if ($.cookie("hide_level3") == "true") { //check for cookie
        $('.Level3').hide(); //hide the level
    }

    $('.hide_level3_button').click(function() {
        $('.Level3').fadeToggle(); //toggle level
        $.cookie('hide_level3', 'true'); //set the cookie
        return false;
    });
});

http://jsfiddle.net/BandonRandon/nzE7F/3/

share|improve this answer
    
Thanks, that solved it! :) Always forgetting the easiest solution.. –  Martin Aleksander Dec 27 '11 at 18:08
    
Now, just a follow-up question. How much work would it be to add this to a session? So that the user don't have to click it again on every pageload? –  Martin Aleksander Dec 27 '11 at 18:26
    
It works for hiding Level3 and cookie. But if I hide, and show and then reload, it hides Level3. –  Martin Aleksander Dec 27 '11 at 19:39
    
Just unset it if they click the link again: jsfiddle.net/BandonRandon/nzE7F/6 –  BandonRandon Dec 27 '11 at 20:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.