AJAX 加载更多自定义帖子类型WordPress

cx6n0qe3  于 2023-01-16  发布在  WordPress
关注(0)|答案(1)|浏览(117)

我试图加载更多的职位调用自定义职位类型与分类数组排序出特定职位或所有杂志端口。如果你点击加载更多,没有职位返回,用户将收到一条消息。截至目前,当我点击“加载更多”按钮,它似乎只是循环与不返回3个职位。
下面我已经写了我已经采取的步骤来执行WordPress的 AJAX 加载更多的职位功能。

**第一步:**创建了一个名为taxonomy-magazine-category.php的页面模板,该模板位于我的主题文件夹中,并带有显示3篇文章的标记,以及加载更多按钮功能,每次单击都会返回3篇文章,直到所有文章都返回为止。

<div class="post row">

    <?php
    $paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
    $latests = new WP_Query(array(
    'posts_per_page' => 3,
    'post_type' => 'magazine',
    ));

    while($latests->have_posts()): $latests->the_post();    //put the post card here ?>
        <div class="col-12 col-sm-12 col-md-7 col-xl-9">

                <div class="blog-article-cards list-articles">
                    <?php
                        get_template_part('/components/magazine-article-card', null, array( 'magazines' => $magazines[$i], 'style' => 'regular'));
                 ?>
                </div>
        </div>
     <?php  endwhile; ?>

</div>

<script>
    var limit = 3,
        page = 1,
        type = 'latest',
        category = '',
        max_pages_latest = <?php echo $latests->max_num_pages ?>
</script>
<?php if ( $latests->max_num_pages > 1 ){
    echo '<div class="load_more text-center">
                    <a href="#" class="btn btn-circle btn-inverse btn-load-more">Load More</a> 
                </div>';
} else { ?>
    <article>
        <h1>Sorry...</h1>
        <p><?php _e('Sorry, No Posts Available !'); ?></p>
    </article>

<?php } wp_reset_query(); ?>


<?php get_footer(); ?>

**第二步:**在functions.php文件的底部开发了脚本的函数过滤器片段,该文件位于/themes/understrap-child中。顶部的函数加载WordPress安装中的 AJAX 文件,包括我在第三步中创建的自定义Ajax文件。第二个函数从ajax处理程序返回帖子。

function bsubash_load_more_scripts() {
    wp_enqueue_script('jquery');
    wp_register_script( 'loadmore_script', get_stylesheet_directory_uri() . '/js/ajax.js', array('jquery') );
    wp_localize_script( 'loadmore_script', 'loadmore_params', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    ) );

    wp_enqueue_script( 'loadmore_script' );
}

add_action( 'wp_enqueue_scripts','bsubash_load_more_scripts' );

function bsubash_loadmore_ajax_handler(){
    $type = $_POST['type'];
    $category = isset($_POST['category']) ? $_POST['category']: '';
    $args['paged'] = $_POST['page'] + 1;
    $args['post_status'] = 'publish';
    $args['posts_per_page'] =  $_POST['limit'];
    if($type == 'archive'){
        $args['category_name'] = $category;
    }
    query_posts( $args );
    if( have_posts() ) :
        while(have_posts()): the_post();
//write your single post card
            the_title();
            the_excerpt();
        endwhile;
    endif;
    die;
}
add_action('wp_ajax_loadmore','bsubash_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore','bsubash_loadmore_ajax_handler');

**最后一步:**创建了一个ajax.js文件,它位于我的主题文件夹/js/ajax. js中,你将在第二步的函数中看到它。在你点击“加载更多”后,ajax将不会返回帖子,包括显示加载和加载更多静态消息。这似乎工作得很好。

jQuery(function($) {
    $('.btn-load-more').click(function(e) {
        e.preventDefault();
        var button = $(this),
            data = {
                'action': 'loadmore',
                'limit': limit,
                'page': page,
                'type': type,
                'category': category
            };

        $.ajax({
            url: loadmore_params.ajaxurl,
            data: data,
            type: 'POST',
            beforeSend: function(xhr) {
                button.text('Loading...'); // change the button text, you can also add a preloader image
            },
            success: function(data) {
                if (data) {
                    $(".latest_posts_wrapper").append(data);
                    page++;
                    button.text('Load More');
                    if (page == max_pages_latest)
                        button.remove(); // if last page, remove the button
                } else {
                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });

});

一切就绪
**我的模板文件中有什么?**在我的页面模板的顶部,我有其他帖子显示为精选帖子。这些帖子是从代理返回的。我只是指出这一点,以便您也知道我的文件中有什么。这不会影响我的问题。

$magazines = [];

$wp_query = new WP_Query(
    array(
        'post_type' => 'Magazine',
        'tax_query' => array(
            array (
                'taxonomy' => 'magazine_categories',
                'field' => $categoryId,
                'terms' => $category,
                'posts_per_page' => $postsPerPage,
            )
        ),
    )
);

while ($wp_query->have_posts()) : $wp_query->the_post();

    //$blogProxy = new BlogProxy(get_the_ID());
    $magazine = new Magazine();
    $magazine->title = get_the_title();
    $magazine->featured_image = get_the_post_thumbnail_url(get_the_ID());
    $magazine->preview_text = get_the_excerpt();
    $magazine->permalink = get_the_permalink();
    $magazine->date = get_the_date();

    array_push($magazines, $magazine);

endwhile;

wp_reset_postdata();

?>

我的目标是使用 AJAX 开发一个自定义帖子类型的加载更多按钮。如果你按照上面的步骤操作,你应该会看到一个激活的功能,在单击加载更多按钮后不会返回帖子。

xwbd5t1u

xwbd5t1u1#

/* myloadmore.js */

jQuery(function($){ // use jQuery code inside this to avoid "$ is not defined" error
    $('.misha_loadmore').click(function(){
 
        var button = $(this),
            data = {
            'action': 'loadmore',
            'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
            'page' : misha_loadmore_params.current_page
        };
 
        $.ajax({ // you can also use $.post here
            url : misha_loadmore_params.ajaxurl, // AJAX handler
            data : data,
            type : 'POST',
            beforeSend : function ( xhr ) {
                button.text('Loading...'); // change the button text, you can also add a preloader image
            },
            success : function( data ){
                if( data ) { 
                    button.text( 'More posts' ).prev().before(data); // insert new posts
                    misha_loadmore_params.current_page++;
 
                    if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page ) 
                        button.remove(); // if last page, remove the button
 
                    // you can also fire the "post-load" event here if you use a plugin that requires it
                    // $( document.body ).trigger( 'post-load' );
                } else {
                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });
});
/* To style the button the according way use CSS below. */

.misha_loadmore{
    background-color: #ddd;
    border-radius: 2px;
    display: block;
    text-align: center;
    font-size: 14px;
    font-size: 0.875rem;
    font-weight: 800;
    letter-spacing:1px;
    cursor:pointer;
    text-transform: uppercase;
    padding: 10px 0;
    transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out, color 0.3s ease-in-out;  
}
.misha_loadmore:hover{
    background-color: #767676;
    color: #fff;
}
This is the AJAX handler function. Insert it to your functions.php file.

/* Enqueue jQuery and myloadmore.js. Pass query parameters to the script. */

function misha_my_load_more_scripts() {
 
    global $wp_query; 
 
    // In most cases it is already included on the page and this line can be removed
    wp_enqueue_script('jquery');
 
    // register our main script but do not enqueue it yet
    wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') );
 
    // now the most interesting part
    // we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
    // you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
    wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
        'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
        'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
        'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
        'max_page' => $wp_query->max_num_pages
    ) );
 
    wp_enqueue_script( 'my_loadmore' );
}
 
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );

function misha_loadmore_ajax_handler(){
 
    // prepare our arguments for the query
    $args = json_decode( stripslashes( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
    $args['post_status'] = 'publish';
 
    // it is always better to use WP_Query but not here
    query_posts( $args );
 
    if( have_posts() ) :
 
        // run the loop
        while( have_posts() ): the_post();
 
            // look into your theme code how the posts are inserted, but you can use your own HTML of course
            // do you remember? - my example is adapted for Twenty Seventeen theme
            get_template_part( 'template-parts/post/content', get_post_format() );
            // for the test purposes comment the line above and uncomment the below one
            // the_title();
 
 
        endwhile;
 
    endif;
    die; // here we exit the script and even no wp_reset_query() required!
}
 
 
 
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}

相关问题