Ottenere i post con Ajax

29 apr 2018, 10:11:12
Visualizzazioni: 34K
Voti: 4

Voglio ottenere i post con ajax tramite una funzione click.

jQuery

$(".get-posts").click(function(){

  $.ajax({  
    type: 'POST',  
    url: '<?php echo admin_url('admin-ajax.php');?>',  
    data: { action : 'get_ajax_posts' },  
    success: function(response){  
       // Gestisci qui la risposta
    }
  });  
});

PHP

function get_ajax_posts() {
    // Argomenti della Query
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // La Query
    $ajaxposts = new WP_Query( $args );

    // Il Loop
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
                get_template_part('products');
        }
    } else {
        get_template_part('none');
    }
    /* Ripristina i Dati Post Originali */
    wp_reset_postdata();
}
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');

Sono bloccato qui.

3
Commenti

leggi questo http://api.jquery.com/jQuery.ajax/. e poi usa .done(... e leggi cosa c'è in data.

mmm mmm
29 apr 2018 10:25:01

E qual è la domanda?? PS. Non devi fare wp_reset_postdata() nelle callback AJAX, ma devi assolutamente fare die lì dentro.

Krzysiek Dróżdż Krzysiek Dróżdż
29 apr 2018 10:39:25

Come posso stampare template_part? Con echo?

wpdev wpdev
29 apr 2018 10:51:37
Tutte le risposte alla domanda 1
3
11

Opzione 1

Il modo semplice - restituire tutti i post in formato JSON e ciclarli in JavaScript

PHP:

function get_ajax_posts() {
    // Argomenti della Query
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // La Query
    $ajaxposts = get_posts( $args ); // cambiato da wp_query a get_posts, perché `get_posts` restituisce un array

    echo json_encode( $ajaxposts );

    exit; // termina la chiamata AJAX (altrimenti restituirà informazioni inutili nella risposta)
}

// Azione AJAX per utenti loggati e non loggati
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

JavaScript:

$.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php');?>',
    dataType: "json", // aggiungi il tipo di dati
    data: { action : 'get_ajax_posts' },
    success: function( response ) {
        $.each( response, function( key, value ) {
            console.log( key, value ); // questi sono i dati dei post.
        } );
    }
});

Opzione 2

Ottieni il contenuto HTML e stampalo a schermo.

PHP:

function get_ajax_posts() {
    // Argomenti della Query
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // La Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // La Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            $response .= get_template_part('products');
        }
    } else {
        $response .= get_template_part('none');
    }

    echo $response;

    exit; // termina la chiamata AJAX
}

// Azione AJAX per utenti loggati e non loggati
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

JavaScript:

   $.ajax({
        type: 'POST',
        url: '<?php echo admin_url('admin-ajax.php');?>',
        dataType: "html", // aggiungi il tipo di dati
        data: { action : 'get_ajax_posts' },
        success: function( response ) {
            console.log( response );

            $( '.posts-area' ).html( response ); 
        }
    });

Nel secondo esempio, cambia il selettore .posts-area con quello in cui vuoi stampare il contenuto.

Il console.log serve solo per vedere le informazioni restituite dalla chiamata AJAX nella console. Dovresti rimuoverlo una volta terminato.

29 apr 2018 11:58:14
Commenti

Inoltre, nel caso in cui non desideri mischiare linguaggi PHP e Javascript negli stessi file (cosa che dovresti evitare), puoi passare gli URL per le richieste AJAX utilizzando wp_localize_script (https://codex.wordpress.org/Function_Reference/wp_localize_script)

Tom Tom
31 gen 2019 14:13:35

nell'opzione 1 c'è un errore con new nella riga $ajaxposts = new get_posts( $args ); che dovrebbe invece essere $ajaxposts = get_posts( $args );

jopfre jopfre
28 nov 2019 14:26:05

@jopfre aggiornato.

kirillrocks kirillrocks
15 dic 2021 17:28:49