SOFT
SPRINT

softsprint.net
Shop

Filter posts by categories in WordPress

Вибачте цей текст доступний тільки в “англійська і “російська”.

Here is the task: to show the works from portfolio, which belong to WordPress category only, while clicking on the WordPress link in the menu, i.e. to filter the posts by categories:

Obviously, when you click on PrestaShop, you should see the works that belong only to the PrestaShop category, etc.

Solution
Actually, here are our links:

We need to pay attention to the next string only:

  • Body of the function the_category_unlinked() is located in the file functions.php:
    1
    
    <!--?php function the_category_unlinked($separator = ' ') { $categories = (array) get_the_category(); $thelist = ''; foreach($categories as $category) { // concate $thelist .= $separator . $category->category_nicename; } echo $thelist; } ?-->

    What do we get as a result? We request the corresponding categories for each post in the cycle and add them to the class of the tag we need. In our case, we get the following output HTML:
    html-code

    Next we`ll need a JS or jQuery-script like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    $('#works .links a').on( "click", function(event) {
     event.preventDefault();
     var $attrName = $(this).attr('href');
     $('#works #da-thumbs li').each(function(index, element){
      $(element).removeClass("worktohide");
      if(!$(element).hasClass($attrName)) {
       $(this).addClass("worktohide");
      }
     })
    })

    Script logic:, read the link`s attribute href (for example, wordpress) when clicking on it and check the entire array of posts (our works from the portfolio) for the condition: if this post does not have a wordpress class, then it needs to be hidden. In our case, we hide the posts by adding the class with the corresponding styles:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    .worktohide {
     opacity: 0.15;
     filter: grayscale(100%); /* Current draft standard */
     -webkit-filter: grayscale(100%); /* New WebKit */
     -moz-filter: grayscale(100%);
     -ms-filter: grayscale(100%); 
     -o-filter: grayscale(100%); /* Not yet supported in Gecko, Opera or IE */ 
     filter: url(resources.svg#desaturate); /* Gecko */
     filter: gray; /* IE */
     -webkit-filter: grayscale(1); /* Old WebKit */
    }

    Finally we get this result (I duplicate the first image of this article):

    Presented algorithm allows to avoid AJAX use for showing the necessary category posts only and allows to tune the styles more flexible!

КОНТАКТИ
Cookies | Privacy Policy | Terms and ConditionsSoftSprint ©