Как я могу принести петлю названия почты через Ajax?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/9233

  •  16-10-2019
  •  | 
  •  

Вопрос

У меня есть список самых последних названий постов в sidebar.php. Анкет Вот пример того, как выглядит этот код:

<?php $args = array('posts_per_page' => 20); ?>
<?php $sidebar = new WP_Query($args); ?>
<?php if ( $sidebar->have_posts() ) : ?>
<?php while ( $sidebar->have_posts() ) : $sidebar->the_post(); ?>

<div class="story">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
  <?php the_title(); ?> - <?php the_time("F j, Y h:i A"); ?>
</a>
</div>

<?php endwhile; ?>
<?php endif; ?>

Эта часть работает отлично. Он отображает 20 последних названий публикаций и время поста, завернутых в постоянные ссылки. Тем не менее, я пытаюсь сделать немного больше. Я хочу создать кнопку загрузки больше внизу, чтобы получить следующие 20 титулов. Я знаю свой jQuery, и это не проблема.

Мне нужна помощь в выяснении, как создать пользовательский цикл в новом пользовательском .php Файл шаблона, который генерирует только HTML выше. Этот файл должен иметь возможность принять параметр для номера страницы, чтобы мой javascript может приносить увеличенный URL каждый раз.

Я был бы признателен за любую помощь, спасибо!

Это было полезно?

Решение

Вы можете обернуть свою функцию и подключить ее к Ajax Call так:

//if you want only logged in users to access this function use this hook
add_action('wp_ajax_more_links', 'my_AJAX_more_links_function');
//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_more_links', 'my_AJAX_more_links_function');

function my_AJAX_more_links_function(){
    check_ajax_referer('more_links');
    $success_response = new WP_Ajax_Response();
    $args = array('posts_per_page' => 20 , 'offset' => $_POST['offset']);
    $sidebar = new WP_Query($args);
    if ( $sidebar->have_posts() ){ 
         while ( $sidebar->have_posts() ) {
            $sidebar->the_post(); 
            $out .= '<div class="story">';
            $out .= '<a href="' . the_permalink().'" title="'. the_title'.">' . the_title().' - '.the_time("F j, Y h:i A") .'</a></div>';
        }
        $success_response->add(array(
                    'what' => 'has',
                    'data' => array('html' => $out, 'offset' => $_POST['offset']
        ));
    }else{
        $out = __('Sorry but No more!');
        $success_response->add(array(
                    'what' => 'none',
                    'data' => $out
                ));
    }

    $success_response->send();      
    exit;   
}

Затем добавьте это к функции боковой панели в конце

<span class="more_links"></span>
<span class="get_more">
    <input type="hidden" name="offset" id="offset" value="20">
    <input type="submit" name="more" id="more" value="Get more links">
</span>
<script type="text/javascript" >
jQuery(document).ready(function($) {
    jQuery('#more').click(function() { 
        var data = {
            action: 'more_links',
            offset: jQuery( '#offset' ).val(),
            _ajax_nonce: <?php echo wp_create_nonce( 'more_links' ); ?>
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            var res = wpAjax.parseAjaxResponse(response, 'ajax-response');
            jQuery.each( res.responses, function() { 
                if (this.what == 'has') {
                    //insert links
                    jQuery(".more_links").append( this.data.html ); 
                    //update offset value
                    jQuery("#offset").val(this.data.offset);
                    jQuery(".more_links").fadeIn("fast");
                }else{
                    //no more links found
                    jQuery(".more_links").append( this.data.html );
                    jQuery(".get_more").remove();

                }
                //end if
                });//end each


        });

        return false;
    })
});
</script>

И вот и вы, о, подождите, вам нужно добавить wp-ajax-response, так что

add_action('wp_head','add_scripts_121');
function add_scripts_121(){
    wp_enqueue_script('wp-ajax-response');
}

и вы настроены

Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top