WordPress

Domyślny post pokazujący więcej niż zamierzano

  • 14 lutego, 2024
  • 5 min read
Domyślny post pokazujący więcej niż zamierzano


Mam skonfigurowaną konfigurację ajax, w której ładuję kategorie postów za pomocą żądania ajax po kliknięciu przycisku.

Mam domyślne zapytanie, które jest ładowane, gdy filtr ajax nie jest ustawiony, więc jest to stan domyślny.

Powinno być ustawione na 6 postów, ale ładuje cały mój post, oto mój stan domyślny.

    <?php 
$string = basename($wp->request); ;
$string = str_replace('-', '_', $string);
$new_string = $string;
$query_args = array(
   'posts_per_page' => 6,
    'post_status' => 'publish',
    'post_type' => $string
);

$the_query = new WP_Query($query_args);

if ($the_query->have_posts()) :
    while ($the_query->have_posts()) : $the_query->the_post();
        get_template_part('template-parts/posts-filter/single-post');
    endwhile;
    wp_reset_postdata();
endif;
?>

czy ktoś może zobaczyć, że domyślny stan to ładowanie wszystkich postów?

pobiera poprawny typ postu i opublikowany post, ale post_per_page pokazuje ponad 100.

Pełny zrzut kodu poniżej

     <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
     <script>
document.addEventListener('alpine:init', () => {
    
        attrs = $( 'body' ).attr( 'class' ).split( ' ' );
        jQuery( attrs ).each(function() {

            if ( 'post-type-' === this.substr( 0, 10 ) ) {
                postType = this.split( 'post-type-' );
                postType = postType[ postType.length - 1 ];
                return;
            }
        });
        
        postType = postType.replace('archive-', '');
    
    var post_id = postType;
    

Alpine.data("filterPosts", (adminURL) => ({
    posts: "",
    limit: 6,
    total: null,
    category: null,
    post_type_js: post_id,
    showDefault: true,
    showFiltered: false,
    offset: 0,
    
    filterPosts(id) {
        this.showDefault = false;
        this.showFiltered = true;
        this.category = id;
        this.offset = 0; // <-- reset offset to zero
        this.fetchPosts();
    },
    
    loadMore() {
        this.loadingMore = true;
        this.offset += 6;
        this.showFiltered = true;
        this.fetchPosts(true);
    },

    fetchPosts(append = false) {
        var formData = new FormData();
        formData.append("action", "filterPosts");
        formData.append("limit", this.limit);
        formData.append("post_type_js", this.post_type_js);
        formData.append("offset", this.offset); 

        if (this.category) {
            formData.append("category", this.category);
        }

    fetch(adminURL, {
        method: "POST",
        body: formData,
    })
    .then((res) => res.json())
    .then((res) => {
            if (append) {
                // Appends posts to the end of existing posts data
                this.posts = this.posts.concat(res.posts);
            } else {
                // Resets the posts data with new data
                this.posts = res.posts;
            }

            this.loading = false;
        });
    },
    
    getTotal() {
    var formData = new FormData();
    formData.append("action", "filterPosts");

    fetch(adminURL, {
        method: "POST",
        body: formData,
    })
    .then((res) => res.json())
    .then((res) => {
        this.total = res.total;
    });
},

init() {
    this.getTotal();
}

}));
})
     </script>
     
   
</head>
<body>
    <div x-data="filterPosts('<?php echo admin_url('admin-ajax.php'); ?>')">
<section <?php theme_section_attr_id() ?> <?php theme_section_attr_class('main-section js-posts') ?>>
  <div class="container">
    <div class="heading mx-0">
      <?php $before_title = get_sub_field('before_title');
      if ($before_title) : ?>
        <strong class="sub-title"><?php echo $before_title ?></strong>
      <?php endif ?>
      <?php $title = get_sub_field('title');
      if ($title) : ?>
        <h2><?php echo $title ?> </h2>
      <?php endif ?>
    </div>

      <div class="head js-posts-search-text">
        <?php if ($search_value) : ?>
          <h2 class="h5 fw-semibold"><?php printf(__('Showing results for “%s”', 'base'), $search_value) ?></h2>
        <?php endif ?>
      </div>
      
<!--alipne js dynamic post start-->
    <div class="has-filter row flex-md-row-reverse">
          <!-- Posts Column -->
        <div class="col-md-8 col-lg-9 js-posts-holder">
           <!-- Default posts query -->
            <div x-show.important="showDefault" class="row cards-area js-posts-items">
                <?php get_template_part( 'template-parts/posts-filter/default-query' ); ?>
            </div>
                <!-- Filtered posts -->
            <div x-show.important="showFiltered" class="row cards-area js-posts-items" x-html="posts">
            </div>
            <!-- Load More Posts -->
            
             <!-- Load More Posts -->
            <div @click="loadMore()" x-show="total > (limit + offset)"  class="text-center mt-12 pt-5">
                <button class="">
                    Load More
                </button>
            </div>
         </div>
            
        <!-- Filtered posts -->
        <div class="col-md-4 col-lg-3">
             <?php get_template_part( 'template-parts/posts-filter/filter-query' ); ?>
        <!-- Filtered end -->
         </div>   
    </div>
    </div>
<!--alipne js dynamic post end-->

</section>
</div>
</body>

kod ajaxowy

 <?php // the ajax function
add_action('wp_ajax_filterPosts', 'filterPosts');
add_action('wp_ajax_nopriv_filterPosts', 'filterPosts');

function filterPosts()
{
    $response = [
        'posts' => "",
    ];
    
    $all_args = array(
        'posts_per_page' => -1, // returns all posts
        'post_status' => 'publish',
    );
    
    $filter_args = array(
        'post_status' => 'publish',
    );
    
     if ($_POST['limit']) {
        $filter_args['posts_per_page'] = $_POST['limit'];
    }
    
    if (isset($_POST['offset'])) {                      
        $filter_args['offset'] = max (0, (int)$_POST['offset']);
    }

     if ($_POST['post_type_js']) {
        $filter_args['post_type'] = $_POST['post_type_js'];
    }

    if ($_POST['category']) {
        $filter_args['cat'] = $_POST['category'];
        
        // Get the total number of posts for the category
        $all_args['cat'] = $_POST['category'];

    }

    $filter_query = new WP_Query($filter_args);

    $all_query = new WP_Query($all_args);

    

    if ($filter_query->have_posts()) :
        while ($filter_query->have_posts()) : $filter_query->the_post();
            $response['posts'] .= load_template_part('/template-parts/posts-filter/single-post');
        endwhile;
        wp_reset_postdata();
    endif;

    echo json_encode($response);
    die();
}


Źródło

Warto przeczytać!  Opcja „Dodaj elementy menu” nie działa