Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- HTML / PHP
- <section id="info">
- <div class="container">
- <?php $categories = get_categories(); ?>
- <ul class="cat-list">
- <li>
- <a class="cat-list_item active" href="#!" data-slug="">All projects</a>
- </li>
- <?php foreach($categories as $category) : ?>
- <li>
- <a class="cat-list_item" href="#!" data-slug="<?= $category->slug; ?>">
- <?= $category->name; ?>
- </a>
- </li>
- <?php endforeach; ?>
- </ul>
- <?php
- $posts = new WP_Query([
- 'posts_per_page' => -1,
- 'order_by' => 'date',
- 'order' => 'desc',
- ]);
- ?>
- <?php if($posts->have_posts()): ?>
- <ul class="project-tiles">
- <?php
- while($posts->have_posts()) : $posts->the_post();
- include('components/project-list-item.php');
- endwhile;
- ?>
- </ul>
- <?php wp_reset_postdata(); ?>
- <?php endif; ?>
- </div>
- </section>
- JS / JQuery
- jQuery(function($){
- $.ajax({
- type: 'POST',
- url: '/wp-admin/admin-ajax.php',
- dataType: 'html',
- data: {
- action: 'filter_posts',
- category: $(this).data('slug'),
- type: $(this).data('type'),
- },
- success: function(res) {
- $('.project-tiles').html(res);
- }
- });
- });
- $('.cat-list_item').on('click', function(e) {
- e.preventDefault();
- console.log('clicked');
- $('.cat-list_item').removeClass('active');
- $(this).addClass('active');
- });
- Functions.php
- // AJAX filter for projects
- function filter_posts() {
- $catSlug = $_POST['category'];
- $ajaxposts = new WP_Query([
- 'posts_per_page' => -1,
- 'category_name' => $catSlug,
- 'orderby' => 'date',
- 'order' => 'desc',
- ]);
- $response = '';
- if($ajaxposts->have_posts()) {
- while($ajaxposts->have_posts()) : $ajaxposts->the_post();
- $response .= get_template_part('components/project-list-item');
- endwhile;
- } else {
- $response = 'empty';
- }
- echo $response;
- exit;
- }
- add_action('wp_ajax_filter_posts', 'filter_posts');
- add_action('wp_ajax_nopriv_filter_posts', 'filter_posts');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement