Disable pagination in posts and pages

I need to solve duplicating of posts and pages caused by unexpected paging. I am trying to disable the paging with this function, but it seems I miss something:

function wpse_disable_pagination( $query ) {
  if( $query-is_single()  $query-is_page() ) {
    $query-set('nopaging', 1 );
  }
}
add_action( 'pre_get_posts', 'wpse_disable_pagination' );

Topic paged pagination pages posts Wordpress

Category Web


I found the right solution, thanks to Jeff Morris:

global $posts, $numpages;

    $request_uri = $_SERVER['REQUEST_URI'];

    $result = preg_match('%\/(\d)+(\/)?$%', $request_uri, $matches);

    $ordinal = $result ? intval($matches[1]) : FALSE;

    if(is_numeric($ordinal)) {

        // a numbered page was requested: validate it
        // look-ahead: initialises the global $numpages

        setup_postdata($posts[0]); // yes, hack

        $redirect_to = ($ordinal < 2) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE);

        if(is_string($redirect_to)) {

            // we got us a phantom
            $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);

            // if page = 0 or 1, redirect permanently
            if($ordinal < 2) {
                header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');
            } else {
                header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found');
            }

            header("Location: $redirect_url");
            exit();

        }
    }

function wpse_disable_pagination( $query ) {
  if( $query->is_single() && $query->is_page() ) {
    $query->set( 'nopaging' , true );
  }
}
add_action( 'pre_get_posts', 'wpse_disable_pagination' );

NOTE: nopaging (boolean) - show all posts or use pagination. Default value is 'false', use paging.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.