создать loadmore для Wordpress с ajax и пользовательским типом записи? - PullRequest
0 голосов
/ 08 ноября 2019

У меня возникли некоторые проблемы с AJAX. Кто может мне помочь.

У меня есть код

<button class="load-more">More</button>

Функция

add_action('wp_ajax_loadmore', 'get_post_loadmore');
add_action('wp_ajax_nopriv_loadmore', 'get_post_loadmore');
function get_post_loadmore() {
    $offset = isset($_POST['offset']) ? (int)$_POST['offset'] : 0;
    $getposts = new WP_query(); $getposts->query('post_type=event&post_status=publish&showposts=5&offset='.$offset);
    global $wp_query; $wp_query->in_the_loop = true; 
    while ($getposts->have_posts()) : $getposts->the_post(); ?>
        <?php do_action('postthumb1')?>
    <?php endwhile; wp_reset_postdata();
    die(); 
}

js

<script>
    $(document).ready(function(){
        var offset = 4;
        $('.load-more1').click(function(event) {
            $.ajax({
                type : "post",
                dataType : "html",
                async: false,
                url : '<?php echo admin_url('admin-ajax.php');?>',
                data : {
                    action: "loadmore",
                    offset: offset, 
                },
                beforeSend: function(){

                },
                success: function(response) {
                    $('.list-new').append(response);
                    offset = offset + 5; 
                },
                error: function( jqXHR, textStatus, errorThrown ){
                    console.log( 'The following error occured: ' + textStatus, errorThrown );
                }
           });
        });
    });
</script>

Код работает нормально, но загружаетсятолько post_type событие. Я хочу установить переменную, которая может использоваться для всех пользовательских типов записей. Я попытался установить переменную, но код не работает. Кто-нибудь, кто имеет опыт работы с ajax, может мне помочь?

1 Ответ

1 голос
/ 08 ноября 2019

Это даст вам все пользовательские типы записей на сайте:

$args = array(
   'public'   => true,
   '_builtin' => false,
);

$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'

$post_types = get_post_types( $args, $output, $operator ); 

$args = array(  
    'post_type' => $post_types,
    'post_status' => 'publish',
    'posts_per_page' => 5, 
    'offset' => $offset
);

$getpost = new WP_Query( $args ); 

Если вы ищете определенный тип post_type, переданный вызовом ajax:


<script>
    $(document).ready(function(){
        var offset = 4;
        $('.load-more1').click(function(event) {
            $.ajax({
                type : "post",
                dataType : "html",
                async: false,
                url : '<?php echo admin_url('admin-ajax.php');?>',
                data : {
                    action: "loadmore",
                    offset: offset, 
                    posttype: posttype //Where ever you want to get this from
                },
                beforeSend: function(){

                },
                success: function(response) {
                    $('.list-new').append(response);
                    offset = offset + 5; 
                },
                error: function( jqXHR, textStatus, errorThrown ){
                    console.log( 'The following error occured: ' + textStatus, errorThrown );
                }
           });
        });
    });
</script>

Функция:

add_action('wp_ajax_loadmore', 'get_post_loadmore');
add_action('wp_ajax_nopriv_loadmore', 'get_post_loadmore');

function get_post_loadmore() {
    $offset = isset($_POST['offset']) ? (int)$_POST['offset'] : 0;
    $posttype = isset($_POST['posttype']) ? $_POST['posttype'] : 'post';

    $args = array(  
       'post_type' => $posttype,
       'post_status' => 'publish',
       'posts_per_page' => 5, 
       'offset' => $offset
    );
    $getposts = new WP_query($args); 

    global $wp_query; 
    $wp_query->in_the_loop = true; 

    while ($getposts->have_posts()) : $getposts->the_post(); 
         do_action('postthumb1');
    endwhile;

    wp_reset_postdata();
    die(); 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...