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:
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:
Next we`ll need a JS or jQuery-script like this:
$('#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:
.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!