F
F
freeman02042022-01-14 19:24:18
AJAX
freeman0204, 2022-01-14 19:24:18

How to make separate loading of posts on ajax in tabs?

With the loading of posts on ajax, I generally understand, here , and if there are, for example, 3 tabs and each tab has posts and its own button to load more, how can I separate these tabs in terms of loading new posts? Display ID in each tab and pass it to ajax js? I still don't understand how to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2022-01-15
@freeman0204

In ajax, pass the parameter you need, for example, post_type

jQuery(document).ready(function ($) {

  $('a.tab').on('click', function (e) {

    $.ajax({
      type: 'POST',
      url: wpz_ajax_obj.ajaxurl, // Путь к файлу admin-ajax.php
      data: {
        'action': 'wpz_ajax_request', // Событие к которому будем обращаться
        'post_type': $(e.currentTarget).attr('data-type'), // Передаём тип записи
        'security': wplb_ajax_obj.nonce, // Используем nonce для защиты
      }
    })

    e.preventDefault();

  });
});

In php, use the specified parameter to request posts and return them with a functionwp_send_json_success()
function wpz_ajax_request() {

  if ( isset( $_POST ) ) {

    // Проверяем nonce, а в случае если что-то пошло не так, то прерываем выполнение функции
    if ( !wp_verify_nonce( $_POST['security'], 'wpz-nonce' ) ) {
      wp_die( 'Базовая защита не пройдена' );
    }

    // заказываем посты из базы
    if ( isset( $_POST['post_type'] ) ) {

      $args = array(
        'post_type' => sanitize_text_field( $_POST['post_type'] ),
        'posts_per_page' => 1,
      );

      $post_query = new WP_Query( $args );

      if ( $post_query ) {
        # если записи есть, возвращаем в wp_send_json_success() html-постов
      } else {
        # если записей нет, возвращаем в wp_send_json_success() информацию о том, что их нет
      }

    } else {
      wp_send_json_error();
    }

  } // end if isset( $_POST )

  wp_die();
}

PS. It is advisable to check in advance that there are still posts to download, otherwise hide their download button

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question