A
A
Artem Gvozdev2019-02-25 15:25:53
WordPress
Artem Gvozdev, 2019-02-25 15:25:53

Ajax loading custom post types?

There is a custom post type, how to make ajax loading when clicking on the "Show more?"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bodrosh, 2019-02-25
@Bodrosh

add an event to the button, in the script. in handler

jQuery(document).on('click', '#get-new-custom-posts', function () {
        jQuery.ajax({
            url: myajax.url,
            type: 'POST',
            data: {
                action: 'get_full_posts'
            },
            success: function (data) {
                jQuery('.br-posts-content').html(data);
            }

        });
    });

Where get_full_posts is the function for getting posts
br-posts-content - where to insert the result
function get_full_posts() {

    $args = array(
        'post_type'  => 'br_company'
    );

    $full_posts = new WP_Query( $args );

    while ( $full_posts ->have_posts() ) {
        $full_posts ->the_post();
        // выводим посты
    }

    wp_reset_postdata();

    die;

}

add_action( 'wp_ajax_get_full_posts', 'get_full_posts' ); // wp_ajax_{ЗНАЧЕНИЕ ПАРАМЕТРА ACTION!!}
add_action( 'wp_ajax_nopriv_get_full_posts', 'get_full_posts' );  // wp_ajax_nopriv_{ЗНАЧЕНИЕ ACTION!!}

И переменную для ajax нужно задать
// Добавляем переменную для ajax

add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
    // Первый параметр 'jquery' означает, что код будет прикреплен к скрипту с ID 'jquery'
    // 'jquery' должен быть добавлен в очередь на вывод, иначе WP не поймет куда вставлять код локализации
    wp_localize_script( 'jquery', 'myajax',
        array(
            'url' => admin_url('admin-ajax.php')
        )
    );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question