WordPress Pagination Issue

User
$args = array(
'post_type' => 'resource',
'orderby' => 'date',
'order' => 'DESC',
'post_status'=>'publish',
'posts_per_page' => 8,
);
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
if(isset($_POST['page']))
$args['paged']=$_POST['page'];
above is still showing repeting when post per page 8 but when i increased it to 50 it shwos correctly
Assistant
The issue you are describing typically occurs because the `paged` parameter is not properly synchronized with the query, causing repeated posts on subsequent pages. Based on the code snippet, here are a few points and suggestions to fix the issue:

### 1. **Properly Set `paged` Parameter**
The `paged` parameter should always be set and properly synced with your query. You're already setting it conditionally, but there's a potential issue in the logic. Update your code as follows:

$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
$args = array(
    'post_type'      => 'resource',
    'orderby'        => 'date',
    'order'          => 'DESC',
    'post_status'    => 'publish',
    'posts_per_page' => 8,
    'paged'          => $paged, // Always set this
);

This ensures the `paged` parameter is always included in the `$args`, regardless of whether `$_POST['page']` exists or not.

### 2. **Check for Duplicates**
If your query still shows repeating posts, it might be due to how the posts are retrieved in relation to the pagination logic. Verify that:

– Your theme or plugin does not manipulate the `query` object unintentionally.
– There are no custom filters (like `pre_get_posts`) altering the query and causing incorrect pagination.

### 3. **Debug the Query**
You can debug the query to confirm the parameters being passed. Use this snippet:

$query = new WP_Query($args);
error_log(print_r($query->request, true)); // Logs the SQL query to debug

Check the generated SQL in the debug log to ensure it correctly includes the `LIMIT` and `OFFSET` for the pagination.

### 4. **Flush Rewrite Rules**
If you're using custom permalinks, flush the rewrite rules to ensure they aren't causing an issue. Go to **Settings > Permalinks** and click **Save Changes**.

### 5. **Check for Caching**
If a caching plugin or mechanism is active, it might serve stale content. Clear the cache to reflect the latest changes.

### 6. **Test with Posts per Page**
When you increase `posts_per_page` to 50, pagination becomes less noticeable, reducing the chance of showing duplicates. This doesn't necessarily mean the issue is resolved—it might indicate a problem with your pagination logic when dealing with smaller chunks.

### Final Working Example:
Here is the complete code snippet to ensure proper pagination:

$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;

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

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // Output post content here
    }
    wp_reset_postdata();
} else {
    echo 'No posts found';
}

This ensures correct pagination handling and eliminates duplicate results.

User
its still repeating posts
Assistant
If you're still seeing repeated posts even after adjusting the `paged` parameter, let's dig deeper. This could be due to a few potential issues in the WordPress query or related factors like caching, conflicts, or improper handling of pagination. Here's a systematic approach to resolve this:

### **1. Debugging the `paged` Parameter**
Ensure the `paged` value is being passed correctly. Add debugging code to verify the value:

$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;

error_log('Paged value: ' . $paged);

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

$query = new WP_Query($args);

error_log(print_r($query->request, true));

– Check your logs to confirm that the `paged` parameter and the SQL query are correct.
– Verify that `OFFSET` in the query matches `(paged – 1) * posts_per_page`.

### **2. Ensure Unique Posts**
If the `WP_Query` object retrieves repeated posts, verify the following:

– **Custom Filters**: Check if there are custom filters applied to `pre_get_posts` or any query modifications elsewhere in your theme or plugins. Look for:

add_filter('pre_get_posts', function ($query) {
      // Any custom modifications here
  });

Temporarily disable such filters to isolate the issue.

– **Sticky Posts**: By default, WordPress includes sticky posts at the top of the query. Exclude them explicitly:

'ignore_sticky_posts' => true

### **3. Disable Caching Temporarily**
Caching plugins or server-level caching can cause issues with paginated results. Clear all caches or temporarily disable caching plugins to test the issue.

### **4. Use a Unique `orderby` Field**
If multiple posts share the same `date` (e.g., they are published at the exact same time), WordPress may repeat results due to the lack of a secondary `orderby` field. Add a unique fallback field like `ID`:

'orderby' => array(
    'date' => 'DESC',
    'ID'   => 'DESC',
),

### **5. Test Without AJAX**
Remove the AJAX handling to ensure the issue is not related to data sent via `$_POST`. For example:

$paged = get_query_var('paged') ? get_query_var('paged') : 1;

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

Visit the pagination links manually (`?paged=2`, `?paged=3`, etc.) and confirm correct behavior.

### **6. Ensure Proper AJAX Implementation**
In your JavaScript, ensure the correct `page` number is being sent to your PHP script. For example:

jQuery(document).on('click', '.load-more', function(e) {
    e.preventDefault();
    let page = parseInt(jQuery(this).data('page')) || 1;
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'load_more_posts',
            page: page,
        },
        success: function(response) {
            // Append or update posts
        },
    });
});

In your PHP function, verify that the `page` value is passed correctly.

### **7. Rebuild Query with `offset`**
If all else fails, try using `offset` explicitly to control the results:

$posts_per_page = 8;
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
$offset = ($paged - 1) * $posts_per_page;

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

$query = new WP_Query($args);

Using `offset` ensures unique results even if the `paged` parameter behaves unexpectedly.

### **8. Complete Example**
Here’s a complete implementation considering all the fixes:

$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;

$args = array(
    'post_type'           => 'resource',
    'orderby'             => array(
        'date' => 'DESC',
        'ID'   => 'DESC',
    ),
    'order'               => 'DESC',
    'post_status'         => 'publish',
    'posts_per_page'      => 8,
    'paged'               => $paged,
    'ignore_sticky_posts' => true,
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        echo '<h2>' . get_the_title() . '</h2>';
    }
    wp_reset_postdata();
} else {
    echo 'No posts found';
}

Let me know how it goes! If the issue persists, we might need to explore other environmental factors, such as your hosting setup or plugins.

User
$filters=$_POST['filters'];
$taxTopic=[];$taxFormat=[];$taxProduct=[];
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
foreach ($filters as $filter)
{
$taxf=explode(':',$filter);
if($taxf[1]=='topic')
$taxTopic[]=$taxf[0];
else if($taxf[1]=='format')
$taxFormat[]=$taxf[0];
else if($taxf[1]=='product')
$taxProduct[]=$taxf[0];
}
// $alltopic=array_search('all:topic',$filters);
// $allformats=array_search('all:format',$filters);
// $allproducts=array_search('all:product',$filters);

$args = array(
'post_type' => 'resource',
'orderby' => 'date',
'order' => 'DESC',
'post_status'=>'publish',
'ignore_sticky_posts' => true,
'posts_per_page' => 8,
);
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
if(isset($_POST['page']))
$args['paged']=$_POST['page'];
// Initialize the tax_query array
$tax_query = array('relation' => 'AND');
if(count($taxTopic)>0)
{
$tax_query[] = array(

'taxonomy' => 'topic',
'field' => 'slug',
'terms' => $taxTopic,
'operator' => 'IN'

);
}
if(count($taxFormat)>0)
{
$tax_query[] =
array(
'taxonomy' => 'format',
'field' => 'slug',
'terms' => $taxFormat,
'operator' => 'IN'

);
}
if(count($taxProduct)>0)
{
$tax_query[] = array(

'taxonomy' => 'product',
'field' => 'slug',
'terms' => $taxProduct,
'operator' => 'IN'

);
}
if (count($tax_query) > 1) {
$args['tax_query']=$tax_query;

}
// echo json_encode($args);
// die;
$query = new WP_Query($args);
if ($query->have_posts()) {
$knowledgePosts='';
while( $query->have_posts() ):
$query->the_post();
$id = get_the_ID();
ob_start();
include(NTPATH.'/resources/views/knowledge-ajax-tmpl.blade.php');

$knowledgePosts.= ob_get_contents();
ob_get_clean();
endwhile;
echo $knowledgePosts;
wp_reset_postdata();
}else
{
echo 'nomorepost';
}

wp_die();
above is the actual query

Assistant
The query you provided appears to handle filtering based on taxonomy and pagination correctly, but the issue of repeated posts may stem from a few areas. Let’s analyze the code step-by-step and suggest potential fixes and improvements.

### Key Areas to Check and Fix

1. **Setting the `paged` Parameter:**
You are correctly setting the `paged` parameter twice. You only need to set it once, so you can clean up this part.

2. **Taxonomy Query Construction:**
Ensure that the taxonomies are being passed correctly. The logic for building the `tax_query` seems fine, but you might want to double-check the values passed in `$_POST['filters']`.

3. **Ensure Unique Posts:**
If there are overlapping posts due to taxonomy filters, ensure that your taxonomies are correctly set up in WordPress, and there are no overlaps causing the same posts to show across different queries.

4. **Reset Post Data:**
You are using `wp_reset_postdata()` correctly, which is good. Make sure it is called after your loop to reset the global `$post`.

5. **AJAX and Frontend Behavior:**
If you are using AJAX to load these posts, ensure that the `page` value sent is incremented correctly with each request, as improper handling of this value can lead to repeated posts.

### Revised Code
Here's a revised version of your query logic with some optimizations and comments:

$filters = $_POST['filters'];
$taxTopic = [];
$taxFormat = [];
$taxProduct = [];
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1; // Only set paged once

// Process filters to categorize them
foreach ($filters as $filter) {
    $taxf = explode(':', $filter);
    switch ($taxf[1]) {
        case 'topic':
            $taxTopic[] = $taxf[0];
            break;
        case 'format':
            $taxFormat[] = $taxf[0];
            break;
        case 'product':
            $taxProduct[] = $taxf[0];
            break;
    }
}

// Prepare query arguments
$args = array(
    'post_type' => 'resource',
    'orderby'   => 'date',
    'order'     => 'DESC',
    'post_status' => 'publish',
    'ignore_sticky_posts' => true,
    'posts_per_page' => 8,
    'paged' => $paged, // Set paged here
);

// Initialize the tax_query array
$tax_query = array('relation' => 'AND');
if (count($taxTopic) > 0) {
    $tax_query[] = array(
        'taxonomy' => 'topic',
        'field'    => 'slug',
        'terms'    => $taxTopic,
        'operator' => 'IN',
    );
}
if (count($taxFormat) > 0) {
    $tax_query[] = array(
        'taxonomy' => 'format',
        'field'    => 'slug',
        'terms'    => $taxFormat,
        'operator' => 'IN',
    );
}
if (count($taxProduct) > 0) {
    $tax_query[] = array(
        'taxonomy' => 'product',
        'field'    => 'slug',
        'terms'    => $taxProduct,
        'operator' => 'IN',
    );
}
if (count($tax_query) > 1) {
    $args['tax_query'] = $tax_query; // Only add if there are filters
}

// Execute the query
$query = new WP_Query($args);
if ($query->have_posts()) {
    $knowledgePosts = '';
    while ($query->have_posts()) {
        $query->the_post();
        ob_start();
        include(NTPATH . '/resources/views/knowledge-ajax-tmpl.blade.php');
        $knowledgePosts .= ob_get_contents();
        ob_end_clean(); // Corrected from ob_get_clean() to ob_end_clean()
    }
    echo $knowledgePosts;
    wp_reset_postdata(); // Reset post data after loop
} else {
    echo 'nomorepost'; // No posts found
}

wp_die(); // End AJAX request

### Additional Steps to Diagnose Repeated Posts

1. **Debugging Output:**
Add debugging output to verify what posts are being queried:

error_log(print_r($query->posts, true)); // Check the returned posts

2. **Check for Overlapping Taxonomies:**
Ensure the posts you expect are indeed different for each taxonomy filter. Check your taxonomy setup in WordPress.

3. **Manual Query Testing:**
Try running a similar query manually via the WordPress loop to see if it yields different results outside of AJAX context:

$test_args = array(
       'post_type' => 'resource',
       'posts_per_page' => 8,
       'paged' => 1,
       'tax_query' => $args['tax_query'], // Use the same tax_query for testing
   );
   $test_query = new WP_Query($test_args);

4. **Evaluate Frontend Pagination Handling:**
Make sure that when you load more posts or navigate through pages on the frontend, the correct `page` parameter is being sent to your AJAX handler.

5. **Plugin Conflicts:**
Disable all plugins temporarily (except the necessary ones) to rule out conflicts.

6. **Theme Functions:**
Check your theme's functions.php for any custom filters or actions that might interfere with your query.

If you go through these suggestions and continue to experience issues, please provide details about the taxonomy structure, or the specific filters being sent in the AJAX request, as that could help further isolate the problem.

User
$filters=$_POST['filters'];
$taxTopic=[];$taxFormat=[];$taxProduct=[];
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
foreach ($filters as $filter)
{
$taxf=explode(':',$filter);
if($taxf[1]=='topic')
$taxTopic[]=$taxf[0];
else if($taxf[1]=='format')
$taxFormat[]=$taxf[0];
else if($taxf[1]=='product')
$taxProduct[]=$taxf[0];
}
// $alltopic=array_search('all:topic',$filters);
// $allformats=array_search('all:format',$filters);
// $allproducts=array_search('all:product',$filters);

$args = array(
'post_type' => 'resource',
'orderby' => 'date',
'order' => 'DESC',
'post_status'=>'publish',
'posts_per_page' => 8,
);
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1;
if(isset($_POST['page']))
$args['paged']=$_POST['page'];
// Initialize the tax_query array
$tax_query = array('relation' => 'AND');
if(count($taxTopic)>0)
{
$tax_query[] = array(

'taxonomy' => 'topic',
'field' => 'slug',
'terms' => $taxTopic,
'operator' => 'IN'

);
}
if(count($taxFormat)>0)
{
$tax_query[] =
array(
'taxonomy' => 'format',
'field' => 'slug',
'terms' => $taxFormat,
'operator' => 'IN'

);
}
if(count($taxProduct)>0)
{
$tax_query[] = array(

'taxonomy' => 'product',
'field' => 'slug',
'terms' => $taxProduct,
'operator' => 'IN'

);
}
if (count($tax_query) > 1) {
$args['tax_query']=$tax_query;

}
// echo json_encode($args);
// die;
$query = new WP_Query($args);
if ($query->have_posts()) {
$knowledgePosts='';
while( $query->have_posts() ):
$query->the_post();
$id = get_the_ID();
ob_start();
//include(NTPATH.'/resources/views/knowledge-ajax-tmpl.blade.php');

$knowledgePosts.= $id.'—';
ob_get_clean();
endwhile;
echo $knowledgePosts;
wp_reset_postdata();
}else
{
echo 'nomorepost';
}

wp_die();
above code returns 16 ids even we set 8 post per page

Assistant
If your code is returning 16 post IDs instead of the expected 8, it indicates that the pagination might not be functioning as intended, or the query could be misconfigured in a way that retrieves more posts than specified. Here’s a systematic approach to debug and fix the issue:

### Possible Issues and Fixes

1. **Verify the Pagination Logic:**
Ensure that the `paged` parameter is being set correctly. In your code, the `paged` parameter is derived from the `$_POST['page']`. If this value is not being updated correctly on the frontend, it could lead to unexpected results.

$paged = isset($_POST['page']) ? intval($_POST['page']) : 1; // Ensure this is set correctly

2. **Check `posts_per_page`:**
You have set `'posts_per_page' => 8`, which is correct. Ensure that this is not being overridden elsewhere in your code or by a filter.

3. **Debugging the Query:**
To gain more insight into what's happening with your query, you can output the generated SQL. This can be helpful for understanding if the pagination is being applied correctly:

global $wpdb;
   $query = new WP_Query($args);
   error_log($query->request); // Log the SQL query for debugging

4. **Inspect the Tax Query:**
If your taxonomy filters return a broader set of posts than expected, they could be causing more posts to show than the pagination setting can handle. Ensure that the taxonomy terms you are filtering by are not overlapping or excessively broad.

5. **Review the Filtering Logic:**
Make sure that your filter handling does not inadvertently include too many posts. If there are posts that match multiple filters, they will be counted multiple times.

6. **Use `ob_end_clean()`:**
It looks like you were previously using `ob_get_clean()` in the loop, which both retrieves and cleans the output buffer. However, you are currently using `ob_get_clean()` incorrectly after building the `$knowledgePosts`. Instead, just end the output buffer after appending:

ob_end_clean(); // Clean the output buffer properly after use

7. **AJAX Request Handling:**
If you’re using AJAX, ensure that the `page` parameter is being sent correctly from the client-side. For example, make sure you increment the page number appropriately when loading more posts.

### Revised Code Example
Here’s your code with some adjustments:

$filters = $_POST['filters'];
$taxTopic = [];
$taxFormat = [];
$taxProduct = [];
$paged = isset($_POST['page']) ? intval($_POST['page']) : 1; // Set pagination

foreach ($filters as $filter) {
    $taxf = explode(':', $filter);
    if ($taxf[1] == 'topic') {
        $taxTopic[] = $taxf[0];
    } elseif ($taxf[1] == 'format') {
        $taxFormat[] = $taxf[0];
    } elseif ($taxf[1] == 'product') {
        $taxProduct[] = $taxf[0];
    }
}

// Prepare the query arguments
$args = array(
    'post_type' => 'resource',
    'orderby'   => 'date',
    'order'     => 'DESC',
    'post_status' => 'publish',
    'posts_per_page' => 8,
    'paged' => $paged, // Ensure paged is set here
);

// Initialize the tax_query array
$tax_query = array('relation' => 'AND');
if (count($taxTopic) > 0) {
    $tax_query[] = array(
        'taxonomy' => 'topic',
        'field'    => 'slug',
        'terms'    => $taxTopic,
        'operator' => 'IN',
    );
}
if (count($taxFormat) > 0) {
    $tax_query[] = array(
        'taxonomy' => 'format',
        'field'    => 'slug',
        'terms'    => $taxFormat,
        'operator' => 'IN',
    );
}
if (count($taxProduct) > 0) {
    $tax_query[] = array(
        'taxonomy' => 'product',
        'field'    => 'slug',
        'terms'    => $taxProduct,
        'operator' => 'IN',
    );
}
if (count($tax_query) > 1) {
    $args['tax_query'] = $tax_query; // Only add if there are filters
}

// Execute the query
$query = new WP_Query($args);
if ($query->have_posts()) {
    $knowledgePosts = '';
    while ($query->have_posts()) {
        $query->the_post();
        $id = get_the_ID();
        $knowledgePosts .= $id . '---<br>';
    }
    echo $knowledgePosts;
    wp_reset_postdata(); // Reset post data after loop
} else {
    echo 'nomorepost'; // No posts found
}

wp_die(); // End AJAX request

### Additional Checks

– Ensure that the AJAX request is sending the correct page number. You might want to log the request data to confirm.
– If using JavaScript for pagination, ensure you increment the page count properly when requesting more posts.
– Monitor the `error_log` output for any unexpected behavior in the SQL query.

If the issue persists after these adjustments, it would be helpful to inspect the raw data being sent in `$_POST['filters']` and the exact AJAX requests made to identify potential discrepancies.

User
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts JOIN wp_icl_translations wpml_translations ON wp_posts.ID = wpml_translations.element_id AND wpml_translations.element_type = CONCAT('post_', wp_posts.post_type) WHERE 1=1 AND wp_posts.post_type = 'resource' AND ((wp_posts.post_status = 'publish')) AND ( ( ( wpml_translations.language_code = 'de' OR ( wpml_translations.language_code = 'de' AND wp_posts.post_type IN ( 'post','page','e-landing-page','elementor_library','contact','success_story' ) AND ( ( ( SELECT COUNT(element_id) FROM wp_icl_translations WHERE trid = wpml_translations.trid AND language_code = 'de' ) = 0 ) OR ( ( SELECT COUNT(element_id) FROM wp_icl_translations t2 JOIN wp_posts p ON p.id = t2.element_id WHERE t2.trid = wpml_translations.trid AND t2.language_code = 'de' AND ( p.post_status = 'publish' OR p.post_status = 'private' OR ( p.post_type='attachment' AND p.post_status = 'inherit' ) ) ) = 0 ) ) ) ) AND wp_posts.post_type IN ('post','page','attachment','wp_block','wp_template','wp_template_part','wp_navigation','e-landing-page','elementor_library','contact','event','resource','success_story' ) ) OR wp_posts.post_type NOT IN ('post','page','attachment','wp_block','wp_template','wp_template_part','wp_navigation','e-landing-page','elementor_library','contact','event','resource','success_story' ) ) ORDER BY wp_posts.post_date DESC LIMIT 8, 811809—
11608—
11452—
11413—
11275—
11261—
9254—
9225—
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts JOIN wp_icl_translations wpml_translations ON wp_posts.ID = wpml_translations.element_id AND wpml_translations.element_type = CONCAT('post_', wp_posts.post_type) WHERE 1=1 AND wp_posts.post_type = 'resource' AND ((wp_posts.post_status = 'publish')) AND ( ( ( wpml_translations.language_code = 'de' OR ( wpml_translations.language_code = 'de' AND wp_posts.post_type IN ( 'post','page','e-landing-page','elementor_library','contact','success_story' ) AND ( ( ( SELECT COUNT(element_id) FROM wp_icl_translations WHERE trid = wpml_translations.trid AND language_code = 'de' ) = 0 ) OR ( ( SELECT COUNT(element_id) FROM wp_icl_translations t2 JOIN wp_posts p ON p.id = t2.element_id WHERE t2.trid = wpml_translations.trid AND t2.language_code = 'de' AND ( p.post_status = 'publish' OR p.post_status = 'private' OR ( p.post_type='attachment' AND p.post_status = 'inherit' ) ) ) = 0 ) ) ) ) AND wp_posts.post_type IN ('post','page','attachment','wp_block','wp_template','wp_template_part','wp_navigation','e-landing-page','elementor_library','contact','event','resource','success_story' ) ) OR wp_posts.post_type NOT IN ('post','page','attachment','wp_block','wp_template','wp_template_part','wp_navigation','e-landing-page','elementor_library','contact','event','resource','success_story' ) ) ORDER BY wp_posts.post_date DESC LIMIT 8,

returning 2 queries

Assistant
The SQL queries you've shared indicate that the same query is being executed twice, and they both seem to be retrieving post IDs from the `wp_posts` table, along with translations from the `wp_icl_translations` table. This can lead to unexpected results, especially if the pagination is not working correctly. Here are some suggestions to troubleshoot and resolve the issue:

### 1. Review Your Code Logic

Check if the `WP_Query` or any other part of your code is being called twice, leading to duplicate queries. This can happen if the AJAX request triggers multiple callbacks or if the code is executed in a loop unintentionally.

### 2. Debugging

Add debugging statements to track where the duplicate queries are coming from. For instance, you can log when the query is initiated:

error_log("Running query with args: " . json_encode($args));

### 3. Ensure Unique Posts

If the same post is being retrieved multiple times, ensure that the `post_type` is correctly set in your arguments and that there are no overlaps in taxonomy filters causing repeated results.

### 4. Check the Pagination

Ensure that the `paged` argument is being set correctly in your query. The `LIMIT` clause in your SQL should reflect the correct offset based on the current page:

– For page 1, it should be `LIMIT 0, 8`
– For page 2, it should be `LIMIT 8, 8`
– For page 3, it should be `LIMIT 16, 8`, and so on.

Make sure that your `$paged` variable is being calculated and passed correctly.

### 5. Adjust the Query for Translation

The queries involve translations, which could complicate the retrieval of unique posts. You might want to simplify the translation checks or ensure that the correct language is being applied.

### 6. Optimize Your Query

If you're using `SQL_CALC_FOUND_ROWS`, ensure you're also using `SELECT FOUND_ROWS()` after your main query to get the total count of rows for pagination. This can help in understanding how many posts are available regardless of pagination.

### Example of Adjusted Query

Here's a snippet of how you can adjust your `WP_Query` setup:

$args = array(
    'post_type' => 'resource',
    'orderby'   => 'date',
    'order'     => 'DESC',
    'post_status'=> 'publish',
    'posts_per_page' => 8,
    'paged'     => $paged, // Ensure paged is included
);

// Check for tax_query if necessary
if (count($tax_query) > 1) {
    $args['tax_query'] = $tax_query;
}

// Execute the query
$query = new WP_Query($args);

// Debugging the generated SQL
error_log("Query executed: " . json_encode($query->request));

// Process the results
if ($query->have_posts()) {
    $knowledgePosts = '';
    while ($query->have_posts()) {
        $query->the_post();
        $id = get_the_ID();
        $knowledgePosts .= $id . '---<br>';
    }
    echo $knowledgePosts;
    wp_reset_postdata();
} else {
    echo 'nomorepost';
}

wp_die();

### Conclusion

If after these adjustments you're still encountering issues, consider simplifying your query by temporarily removing any complex filters or joins (like the translations) to isolate the problem. Once you confirm that the basic query works as expected, gradually add back the additional complexity until you identify the specific cause of the duplicate posts or excessive query execution.

If you continue to experience issues, please share any additional code or context, and I'll be glad to help further!

Leave a Comment

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