WordPress: creare la paginazione di una galleria in AJAX

In WordPress possiamo creare la paginazione di una galleria in AJAX.

La soluzione รจ la seguente:


function my_ajax_gallery() {
    $post_id = (int) $_GET['id'];
    $gallery = get_post_gallery( $post_id, false );
    $image_ids = explode( ',', $gallery['ids'] );
    $images = array();
    
    foreach( $image_ids as $image_id ) {
        $full = wp_get_attachment_image_src( $image_id, 'full' );
        $thumb = wp_get_attachment_image_src( $image_id, 'thumbnail' );
        $images[] = array(
           'thumb' => $thumb[0],
            'full' => $full[0]
        );
    }

    $total = count( $images );
    $page = (int) $_GET['page'];
    $per_page = 10;
    $offset = $page * $per_page;
    $start = $offset - $per_page;
    
    if( $offset <= $total ) {
        $images = array_slice( $images, $start, $per_page );
        $html = '';
        foreach( $images as $image ) {
             $html .= '<figure>';
             $html .= '<a href="' . $image['full'] . '">';
             $html .= '<img src="' . $image['thumb'] . '">';
             $html .= '</a>';
             $html .= '</figure>';  
        }
        echo $html;
        exit();
    }
}

add_action( 'wp_ajax_my_ajax_gallery', 'my_ajax_gallery' );
add_action( 'wp_ajax_nopriv_my_ajax_gallery', 'my_ajax_gallery' );