Reputation: 43
I am working off the TwentyTwelve theme and I have modified the index file by adding this snippet before the loop
get_header(); ?>
<div id="primary" class="site-content">
<div id="content" role="main" class="clearfix">
<?php
$terms = get_the_category();
$count = count($terms);
echo '<ul id="post-filter">';
echo '<li><a href="#all" title="">All</a></li>';
if ( $count > 0 ){
foreach ( $terms as $term ) {
$termname = strtolower($term->name);
$termname = str_replace(' ', '-', $termname);
echo '<li><a href="#'.$termname.'" title="" rel="'.$termname.'">'.$term->name.'</a></li>';
}
}
echo "</ul>";
?>
<div id="mwrapper">
<?php query_posts('cat=-6,-7'); ?>
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<div class="box">....
I'm trying to create a filter that will filter through the blog post. Like the demo here. Currently I have five categories: Agency Notes, Design Notes, Featured, Humor, Uncategorized. And there's at least one post per category but it seems to be pulling in Design Notes only.
I have also tried changing the get_the_category();
to wp_list_categories();
but that ended up showing all the categories.
Source I'm getting the snippet from.
Upvotes: 1
Views: 155
Reputation: 19750
First off, you want to get all categories. get_the_category() does not do this. You probably want get_categories() instead.
$terms = get_categories();
$count = count($terms);
echo '<ul id="post-filter">';
echo '<li><a href="#all" title="">All</a></li>';
if ( $count > 0 ) {
foreach ( $terms as $term ) {
echo '<li><a href="#" data-slug="'.$term->slug.'">'.$term->name.'</a></li>';
}
}
echo "</ul>";
I also made a few modifications: removed the hash and rel attribute. We can use data-attributes instead, which are more semantic.
The next part depends on your post HTML, but I'm assuming they have a class of post
and the category they're in. If they do, you can do something like this with jQuery:
$('a', '#post-filter').on('click', function(e) {
e.preventDefault();
$('.post').hide().filter('.' + $(this).attr('data-slug')).show();
});
Which will hide all posts, and only show the ones in the selected category. I'll leave it to you to sort out the animations.
Upvotes: 0
Reputation: 13354
get_the_category()
grabs the current post's category/ies information, not the list of categories in the full WP installation.
I think what you're looking for is the get_categories()
function (more info here at the codex: http://codex.wordpress.org/Function_Reference/get_categories)
<?php
$categories=get_categories( array( 'order' => 'ASC', 'orderby' => 'name' ) );
$count = count($terms);
[...]
Upvotes: 2