Load More Functionality WP

User
$args = array(
'post_type' => 'resource',
'orderby' => 'date',
'order' => 'DESC',
);

$query = new WP_Query($args);
add limit to 8 and load more functionality

Assistant
To add a limit of 8 posts and a "Load More" functionality to your WordPress query, you can follow these steps:

### 1. **Modify the Query**
Set the `posts_per_page` parameter in your `$args` array to limit the query to 8 posts:

$args = array(
    'post_type'      => 'resource',
    'orderby'        => 'date',
    'order'          => 'DESC',
    'posts_per_page' => 8,
);

$query = new WP_Query($args);

### 2. **Frontend Button for "Load More"**
Add a button in your HTML where the posts are displayed:

<div id="resource-container">
    <!-- Posts will be loaded here -->
    <?php if ($query->have_posts()) : ?>
        <?php while ($query->have_posts()) : $query->the_post(); ?>
            <div class="resource-item">
                <h2><?php the_title(); ?></h2>
                <p><?php the_excerpt(); ?></p>
            </div>
        <?php endwhile; ?>
    <?php endif; ?>
</div>

<?php if ($query->max_num_pages > 1) : ?>
    <button id="load-more" data-page="1">Load More</button>
<?php endif; ?>

### 3. **AJAX for "Load More"**
Use WordPress AJAX to fetch more posts when the button is clicked.

#### **JavaScript**
Create or update your JavaScript file to handle the "Load More" functionality:

document.getElementById('load-more').addEventListener('click', function () {
    const button = this;
    const currentPage = parseInt(button.getAttribute('data-page'));
    const nextPage = currentPage + 1;

    const data = new FormData();
    data.append('action', 'load_more_resources');
    data.append('page', nextPage);

    fetch(ajaxurl, {
        method: 'POST',
        body: data,
    })
        .then((response) => response.text())
        .then((data) => {
            if (data.trim()) {
                document.getElementById('resource-container').insertAdjacentHTML('beforeend', data);
                button.setAttribute('data-page', nextPage);
            } else {
                button.style.display = 'none'; // Hide button if no more posts
            }
        })
        .catch((error) => console.error('Error:', error));
});

#### **PHP: AJAX Handler**
Add the following code to your theme's `functions.php` file to handle the AJAX request:

function load_more_resources() {
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;

    $args = array(
        'post_type'      => 'resource',
        'orderby'        => 'date',
        'order'          => 'DESC',
        'posts_per_page' => 8,
        'paged'          => $page,
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post(); ?>
            <div class="resource-item">
                <h2><?php the_title(); ?></h2>
                <p><?php the_excerpt(); ?></p>
            </div>
        <?php endwhile;
    endif;

    wp_die(); // Stop further processing
}
add_action('wp_ajax_load_more_resources', 'load_more_resources');
add_action('wp_ajax_nopriv_load_more_resources', 'load_more_resources');

### 4. **Localize Script**
Ensure `ajaxurl` is available by localizing your JavaScript:

In `functions.php`:

function enqueue_load_more_script() {
    wp_enqueue_script('load-more-resources', get_template_directory_uri() . '/js/load-more-resources.js', array('jquery'), null, true);

    wp_localize_script('load-more-resources', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'enqueue_load_more_script');

### 5. **Styling (Optional)**
Style your "Load More" button and posts container using CSS:

#load-more {
    display: block;
    margin: 20px auto;
    padding: 10px 20px;
    background: #0073aa;
    color: white;
    border: none;
    cursor: pointer;
}

.resource-item {
    margin-bottom: 20px;
}

This setup ensures only 8 posts are loaded initially, and additional posts are fetched via AJAX when the "Load More" button is clicked. Let me know if you need further assistance!

Leave a Comment

Your email address will not be published. Required fields are marked *