Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Ajax w WordPress

28 stycznia 2023

AJAX (od ang. Asynchronous JavaScript and XML) to technologia pozwalająca na odświeżanie jedynie części strony, a nie jej całości, co odbywa się asynchronicznie. Dane są wówczas zaciągane z pliku XML lub txt zlokalizowanego na serwerze przy pomocy JavaScript albo innego skryptu.

Czym jest asynchroniczność?

Dzięki asynchroniczności działanie przeglądarki nie zostaje zablokowane przez skrypt, a przesyłanie danych traktuje się jako odrębny proces realizowany w tle. W ten sposób przeglądarka działa znacznie szybciej, niż miałoby to miejsce w przypadku działania synchronicznego.

jQUERY a AJAX

Warto wiedzieć, że jQuery i AJAX należą do najczęściej używanych technik przydatnych podczas tworzenia przyjaznego, interaktywnego środowiska w witrynach. Często łączy się je ze sobą, aby aplikacja działała szybciej, a tym samym była atrakcyjniejsza dla użytkownika.

Filtrowanie po kategoriach w wordpress

Stworzymy dynamiczne ładowanie wpisów bloga zależnie od kategorii wpisu. Za przykład działania niech posłuży strona główna tej strony 😋

Aby osiągnąć zamierzony efekt musimy pogrzebać w kilku plikach.

Functions.php

// KATEGORIE AJAX
function ajax_filterposts_handler() {
    $category = esc_attr( $_POST['category'] );
    $date = esc_attr( $_POST['date'] );

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'orderby' => 'date',
        'order' => 'DESC',
        'hide_empty' => 0,
    );

    if ( $category != 'all' )
        $args['cat'] = $category;
    if ( $date == 'new' ) {
        $args['order'] = 'DESC';
    } else {
        $args['order'] = 'ASC';
    }

    $posts = 'No posts found.';

    $the_query = new WP_Query( $args );
 
    if ( $the_query->have_posts() ) :
        ob_start();

        while ( $the_query->have_posts() ) : $the_query->the_post();
        
            get_template_part( 'template-parts/content-post' );
        endwhile;

        $posts = ob_get_clean();
    endif;

    $return = array(
        'posts' => $posts
    );

    wp_send_json($return);
}
add_action( 'wp_ajax_filterposts', 'ajax_filterposts_handler' );
add_action( 'wp_ajax_nopriv_filterposts', 'ajax_filterposts_handler' );

index.js

// AJAX
jQuery(document).ready(function($){
jQuery( ".js-category, .js-date" ).on( "change", function() {
	var category = $( '.js-category' ).val();
	var date = $( '.js-date' ).val();

	data = {
	  'action': 'filterposts',
	  'category': category,
	  'date': date,
	};

	$.ajax({
	  url : '/wp-admin/admin-ajax.php',
	  data : data,
	  type : 'POST',
	  beforeSend : function ( xhr ) {
		$('.filtered-posts').html( 'wczytywanie tresci..' );
		$('.js-category').attr( 'disabled', 'disabled' );
		$('.js-date').attr( 'disabled', 'disabled' );
	},
	  success : function( data ) {
		if ( data ) {
			$('.filtered-posts').html( data.posts );
			$('.js-category').removeAttr('disabled');
			$('.js-date').removeAttr('disabled');
		} else {
			$('.filtered-posts').html( 'Nie znaleziono wpisów.' );
				}
			}
		});
	});
});

template-part/content-post.php

<article id="post-id-<?php the_id(); ?>" <?php post_class('clearfiks archive-post'); ?>>
 <a href="<?php the_permalink() ?>">
   <h3><?php the_title(); ?></h3>
 </a>
</article>

index.php

// ELEMENTY SELECT OBSŁUGUJĄCE ZDARZENIE

<div class="filters">

// WYBÓR KATEGORII
   <div class="category">
       <div class="field-title">kategorie</div>
           <?php $get_categories = get_categories(array('hide_empty' => 1)); ?>
                <select class="js-category">
                    <option value="all">Wszystkie wpisy</option>
                    <?php
                    if ($get_categories) :
                        foreach ($get_categories as $cat) :
                    ?>
                         <option value="<?php echo $cat->term_id; ?>">
                            <?php echo $cat->name; ?>
                         </option>
                    <?php endforeach;
                    endif;
                    ?>
                </select>
            </div>

// WYBÓR OD NAJSTARSZEJ DO NAJNOWSZEJ
            <div class="date">
                <div class="field-title">czas</div>
                <select class="js-date">
                    <option value="new">Najnowsze</option>
                    <option value="old">Najstarsze</option>
                </select>
            </div>

        </div>

// WYŚWIETLANIE
<div class="filtered-posts">
    <?php
       if (have_posts()) :
          while (have_posts()) : the_post();
             get_template_part('template-parts/content-post');
          endwhile;
       endif;
     ?>
    </div>

Komentarze

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *

Dozwolone tagi i atrybuty HTML

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Następny wpis Bloki ACF

Zobacz również

Me, Myself & I

Newsletter

Subskrybuj biuletyn aby otrzymać powiadomienia o nowościach
To pole jest używane do walidacji i powinno pozostać niezmienione.