Publicaciones pegajosas excede las publicaciones por límite de página

20

Estoy usando pre_get_posts para ajustar el número de publicaciones que se muestran en mi página de inicio.

function lifelounge_query_adjust( $query ) {
    if ( is_home() ) {
        set_query_var( 'posts_per_page', 12 );
        return;
    }
}
add_filter( 'pre_get_posts', 'lifelounge_query_adjust' );

Pero me estoy topando con un problema con publicaciones pegajosas. Básicamente, si tengo publicaciones adhesivas, la consulta mostrará más que las 12 publicaciones que he especificado, porque mostrará 12 más cualquier publicación pegajosa. Podría, por supuesto, ignorar las publicaciones pegajosas:

function lifelounge_query_adjust( $query ) {
    if ( is_home() ) {
        set_query_var( 'posts_per_page', 1 );
        set_query_var( 'ignore_sticky_posts', 1 );
        return;
    }
}
add_filter( 'pre_get_posts', 'lifelounge_query_adjust' );

Pero no creo que esto sea ideal. Creo que las publicaciones adhesivas deben estar incluidas en el límite de 12 publicaciones, y no agregadas al límite. Eso es lo que tiene más sentido para mí. ¿Hay una manera de lograr eso? ¿He cometido un error digno de la palma de la mano?

Bastante un duplicado de: Sticky Posts & Publicaciones por página pero eso se cerró de forma extraña porque estaba demasiado localizado. No estoy de acuerdo, obviamente porque estoy buscando una respuesta, pero también porque es una cuestión de por qué WordPress no parece respetar el posts_per_page límite si está usando publicaciones pegajosas. Si quieres 12 publicaciones por página, deberías obtener 12, no 13, que es lo que obtendrías si tuvieras una única publicación adhesiva.

    
pregunta helgatheviking 19.12.2012 - 17:00

3 respuestas

11

Este es un enfoque para tener en cuenta las publicaciones adhesivas obteniendo el número de publicaciones adhesivas (si las hay) e incluirlo en el parámetro de cálculo posts_per_page :

add_action('pre_get_posts', 'ad_custom_query');
function ad_custom_query($query) {

    if ($query->is_main_query() && is_home()) {

        // set the number of posts per page
        $posts_per_page = 12;
        // get sticky posts array
        $sticky_posts = get_option( 'sticky_posts' );

        // if we have any sticky posts and we are at the first page
        if (is_array($sticky_posts) && !$query->is_paged()) {

            // counnt the number of sticky posts
            $sticky_count = count($sticky_posts);

            // and if the number of sticky posts is less than
            // the number we want to set:
            if ($sticky_count < $posts_per_page) {
                $query->set('posts_per_page', $posts_per_page - $sticky_count);

            // if the number of sticky posts is greater than or equal
            // the number of pages we want to set:
            } else {
                $query->set('posts_per_page', 1);
            }

        // fallback in case we have no sticky posts
        // and we are not on the first page
        } else {
            $query->set('posts_per_page', $posts_per_page);
        }
    }
}

Editar

En el caso de que la cantidad de publicaciones por página que deseamos establecer sea menor o igual a la cantidad de publicaciones adhesivas, he establecido posts_per_page en uno y eso dará como resultado 13 o más publicaciones $sticky_count + 1 (en este caso) solo en la primera página (las siguientes páginas tendrán 12 publicaciones). Tal vez eso esté bien ya que este caso es raro y la publicación de +1 en la primera página puede no ser tan significativa.

Esto se debe a que Wordpress mostrará todas las publicaciones adhesivas primero y en una página (la primera página) incluso si su cuenta es mayor que el parámetro posts_per_page , por lo que configuramos el posts_per_page en este caso en la cantidad mínima posible que es 1 , porque los valores 0 y negativos deshabilitarán el parámetro posts_per_page y eso hará que Wordpress muestre todas las publicaciones en la primera página.

    
respondido por el Ahmad M 19.12.2012 - 20:07
3

Hay un problema si las publicaciones adhesivas están en la primera página.

La solución es reducir el número de publicaciones adhesivas para las publicaciones adhesivas que forman parte de la primera página.

function fix_posts_per_page_with_sticky_posts( $query ) {

    if ( $query->is_main_query() ) {

        // set the number of posts per page
        $posts_per_page = 12;

        // get sticky posts array
        $sticky_posts = get_option( 'sticky_posts' );

        // get queried post ids array
        $ids = array();
        $args = array(
            'post_type' => 'post',
            'post_per_page' => $posts_per_page,
            'paged' => 1
        );

        $posts = get_posts( $args );

        foreach ( $posts as $post ) {
            $ids[] = $post->ID;
        }

        // if we have any sticky posts and we are at the first page
        if ( is_array( $sticky_posts ) && ! $query->is_paged() ) {

            // count the number of sticky posts
            $sticky_count = count( $sticky_posts );

            foreach ( $sticky_posts as $sticky_post ) {
                if ( in_array( $sticky_post, $ids ) ) {
                    // decrement sticky posts count if the sticky post in on the page
                    $sticky_count--;
                }
            }

            // and if the number of sticky posts is less than
            // the number we want to set:
            if ( $sticky_count < $posts_per_page ) {
                $query->set( 'posts_per_page', $posts_per_page - $sticky_count );

            // if the number of sticky posts is greater than or equal
            // the number of pages we want to set:
            } else {
                $query->set( 'posts_per_page', 1 );
            }

        // fallback in case we have no sticky posts
        // and we are not on the first page
        } else {
            $query->set( 'posts_per_page', $posts_per_page );
        }
    }
}
add_action( 'pre_get_posts', 'fix_posts_per_page_with_sticky_posts'  );

Espero que te ayude

    
respondido por el csag 28.11.2014 - 15:49
0

Limpié las dos respuestas anteriores en una sola para que no cargue WP_Query innecesario, corrige si el adhesivo en la primera página, reduce el tiempo para procesar la información con un código más rápido y más limpio.

function modify_main_query( $query ) {
   if ( ( $query->is_home() || is_front_page() ) && $query->is_main_query() ) {
         // set the number of posts per page
        $posts_per_page = 12;
        // get sticky posts array
        $sticky_posts = get_option( 'sticky_posts' );
        // if we have any sticky posts and we are at the first page
        if (is_array($sticky_posts) && !$query->is_paged()) {
            // make a second query to make sure the sticky posts will still work 
            // correctly when on the first page
            // Only reply with the ID's as that is all that is needed
            $args = [
                'post_type' => 'post',
                'post_per_page' => $posts_per_page,
                'paged' => 1,
                'fields' => 'ids'
            ];
            // Array flip to reduce the time taken by 
            // using isset and not in_array
            $posts = array_flip( get_posts( $args ) );

            // count the number of sticky posts
            $sticky_count = count($sticky_posts);

            // loop the posts from the 2nd query to see if the ID's of the sticky posts
            // sit inside it.
            foreach ( $sticky_posts as $sticky_post ) {
                if(isset($posts[$sticky_post])){
                    $sticky_count--;
                }
            }
            // and if the number of sticky posts is less than
            // the number we want to set:
            if ($sticky_count < $posts_per_page) {
               $query->set('posts_per_page', $posts_per_page - $sticky_count);
            } else {
                // if the number of sticky posts is greater than or equal
                // the number of pages we want to set:
                $query->set('posts_per_page', 1);
            }
        // fallback in case we have no sticky posts
        // and we are not on the first page
        } else {
            $query->set('posts_per_page', $posts_per_page);
        }
    } 
}

add_action( "pre_get_posts", 'modify_main_query' );
    
respondido por el Andrew Killen 01.08.2018 - 09:59

Lea otras preguntas en las etiquetas