Sumit Rai
Sumit Rai

Reputation: 13

Customizing the post before post pagination

I want to execute a script just before the post being paginated.

I also succeeded to achieve this by executing the script just before the data being paginated

if ( false !== strpos( $content, '<!--nextpage-->' ) )

in wp-includes/query.php

I need to change the post pages which is paginated according to some condition.

Lets say

if(condition == true){
    $paged_data = explode('<!--nextpage-->', $content);
    $i = 0;
    $allpages = "";
    foreach($paged_data as $p_data){
        if( ($i) % 3 != 0){
            $allpages = $allpages.$p_data;
        }
        else{
            $allpages = $allpages . '<!--nextpage-->' .$p_data;
        }
        $i++;
    }
    $content = $allpages;
}

But I need this to be achieved using some hooks or filter. So that the code won't be deleted when wordpress is being updated.

I've tried the_content hook but it executes after the post being paginated.

Even I've tried the_post hook but it only works with few themes.

Upvotes: 1

Views: 599

Answers (1)

birgire
birgire

Reputation: 11378

Here's an example how we can merge pages in chunks, when using content pagination:

Detail

Demo Plugin:

We can use the content_pagination to modify the content pagination:

/**
 * Content Pagination - Merge pages in chunks
 */
add_filter( 'content_pagination', function( $pages )
{
    // Nothing to do without content pagination
    if( count( $pages ) <= 1 )
        return $pages;

    // Number of pages per chunk    
    $pages_per_chunk = 3; // <-- Edit to your needs!

    // Create chunks of pages   
    $chunks = array_chunk( $pages, $pages_per_chunk );

    // Merge pages in each chunk
    $merged = [];
    foreach( (array) $chunks as $chunk )
        $merged[] = join( '', $chunk );

    return $merged;

} );

where we adjust the $pages_per_chunk as needed.

Upvotes: 1

Related Questions