How to create filters for categories with php and html to use in WordPress page? [closed]

1

Hello,

I would like to create a filter for categories of posts in WP. Like in this example link .

But I do not handle a lot of php, so I do not know how to do it, so when I click the 'category1' button only posts from that category appear. And when you click on 'Everyone' appear the posts of all categories ..

My code is like this, for now.

<?php get_header(); ?>

<?php
/* 
Template Name: Arquivo Posts
*/
?>
<div class="container">
    <h1 style="text-align: center; color: white; margin-bottom: 30px;">Noticias</h1>
    <div class="filtro" style="text-align: center;">
        <a href="<?php get_posts('orderby=date&order=DESC&category_name=categoria1'); ?>">Categoria 1</a> 
        <a>Categoria 2</a> <a>Todos</a> </div>

<div class="row">

        <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <div class="col-xs-12 col-sm-6 col-md-4 " style="text-align: center;">
            <a href="<?php the_permalink(); ?>">
            <div class="imgPost"><?php the_post_thumbnail(); ?></div>
            <h2><?php the_title(); ?></a></h2>
            <p><em><?php echo ucfirst(get_the_time('l, j \d\e F \d\e Y')); ?></em></p>
            <hr>
        </div>

        <?php endwhile; else: ?>
            <p><?php _e('Desculpe, não há posts a serem exibidos.'); ?></p>
        <?php endif; ?>
</div>
</div>

<?php get_footer(); ?>

Does anyone know how to help me?

Thank you

    
asked by anonymous 25.12.2018 / 15:38

2 answers

1

Caroline, how are you?

I needed to do a filter type like this once, and I managed to do it with a few steps.

Come on:

1 - First you should download the Isotope plugin and then insert it inside some folder of your Wordpress theme ( link );

2 - Then insert this code below into the functions.php of your Wordpress theme:

if (!is_admin()) add_action( 'wp_enqueue_scripts', 'add_jquery_to_my_theme' );

function add_jquery_to_my_theme() {
// scrap WP jquery and register from google cdn - load in footer
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js", false, null, true );    
// load jquery
wp_enqueue_script('jquery');
}

if (!is_admin()) add_action( 'wp_enqueue_scripts', 'load_isotope' );

function load_isotope() {
// script will load in footer
wp_enqueue_script( 'isotope-js',  get_stylesheet_directory_uri() . '/path/to/jquery.isotope.min.js', true );
}

The first if you add jQuery to your theme, and the second if you call the Isotope plugin. Remember to correctly define the exact path of the plugin in your theme.

3 - Then in your page template in the theme, you should add this code below:

<ul id="filtros">
    <?php
        $terms = get_terms("category");
        $count = count($terms);
            echo '<li><a href="javascript:void(0)" title="" data-filter=".all" class="active">Todos</a></li>';
        if ( $count > 0 ){

            foreach ( $terms as $term ) {

                $termname = strtolower($term->name);
                $termname = str_replace(' ', '-', $termname);
                echo '<li><a href="javascript:void(0)" title="" data-filter=".'.$termname.'">'.$term->name.'</a></li>';
            }
        }
    ?>
</ul>

<div id="post">

   <?php 
   $args = array( 'post_type' => 'post', 'posts_per_page' => -1 );
   $loop = new WP_Query( $args );
   while ( $loop->have_posts() ) : $loop->the_post(); 

      $terms = get_the_terms( $post->ID, 'category' );                      
      if ( $terms && ! is_wp_error( $terms ) ) : 

          $links = array();

          foreach ( $terms as $term ) {
              $links[] = $term->name;
          }

          $tax_links = join( " ", str_replace(' ', '-', $links));          
          $tax = strtolower($tax_links);
      else :    
      $tax = '';                    
      endif; 
      ?>

      <div class="all post-item <?php echo $tax; ?>">
          <a href="<?php the_permalink(); ?>">
              <div class="imgPost"><?php the_post_thumbnail(); ?></div>
              <h2><?php the_title(); ?></h2>
              <p><em><?php echo ucfirst(get_the_time('l, j \d\e F \d\e Y')); ?></em></p>
          </a>
      </div>

    <?php endwhile; ?>

4 - Now you will insert, within the header or the footer of your theme (test), the function that makes the filter feature work:

<script>
    (function($){

    var $container = $('#post');

    // create a clone that will be used for measuring container width
    $containerProxy = $container.clone().empty().css({ visibility: 'hidden' });   

    $container.after( $containerProxy );  

    // get the first item to use for measuring columnWidth
    var $item = $container.find('.post-item').eq(0);

    $container.imagesLoaded(function(){
        $(window).smartresize( function() {

            // calculate columnWidth
            var colWidth = Math.floor( $containerProxy.width() / 2 ); // Change this number to your desired amount of columns

            // set width of container based on columnWidth
            $container.css({
                width: colWidth * 2 // Change this number to your desired amount of columns
            })
            .isotope({

                // disable automatic resizing when window is resized
                resizable: false,

                // set columnWidth option for masonry
                masonry: {
                    columnWidth: colWidth
                }
            });

        // trigger smartresize for first time
        }).smartresize();
    });

    // filter items when filter link is clicked
    $('#filtros a').click(function(){

        var selector = $(this).attr('data-filter');
        $container.isotope({ filter: selector, animationEngine : "css" });
        $('#filtros a.active').removeClass('active');
        $(this).addClass('active');
        return false;

    });

} ) ( jQuery );
</script>

5 - Finally, add the css:

/**** Isotope Filtering ****/

.isotope-item {
  z-index: 2;
}

.isotope-hidden.isotope-item {
  pointer-events: none;
  z-index: 1;
}

/**** Isotope CSS3 transitions ****/

.isotope,
.isotope .isotope-item {
  -webkit-transition-duration: 0.8s;
     -moz-transition-duration: 0.8s;
      -ms-transition-duration: 0.8s;
       -o-transition-duration: 0.8s;
          transition-duration: 0.8s;
}

.isotope {
  -webkit-transition-property: height;
     -moz-transition-property: height;
      -ms-transition-property: height;
       -o-transition-property: height;
          transition-property: height;
}

.isotope .isotope-item {
  -webkit-transition-property: -webkit-transform, opacity;
     -moz-transition-property:    -moz-transform, opacity;
      -ms-transition-property:     -ms-transform, opacity;
       -o-transition-property:      -o-transform, opacity;
          transition-property:         transform, opacity;
}

/**** disabling Isotope CSS3 transitions ****/

.isotope.no-transition,
.isotope.no-transition .isotope-item,
.isotope .isotope-item.no-transition {
  -webkit-transition-duration: 0s;
     -moz-transition-duration: 0s;
      -ms-transition-duration: 0s;
       -o-transition-duration: 0s;
          transition-duration: 0s;
}

From there, it's all up to work. Then it would be at your discretion then to improve the look to suit your needs.

If it still does not work, check the path of your plugin if it is accurate or do more testing by removing the code from the first if in step 2 as it may be jQuery conflict.

I hope I have helped.

    
26.12.2018 / 15:03
-2

Using only PHP is difficult to make this functionality happen. Basically when doing a looping we pass the parameter of the category that we want to filter ...

First it's important to understand that you need to be on a template page "category.php" and have a looping of your categories. This looping is basically an array that could contain all your categories registered in Wordpress.

In this situation when you select an item from this list Wordpress will reload the page by passing the chosen parameter to the URL and displaying the posts on this page.

But to do the exchange of posts without the page reload is necessary to use Ajax.

I've already used something close to this example: link

There are some plugins that make it much easier to add this functionality to the theme.

I already used this plugin and it worked very well: link

    
25.12.2018 / 21:28