WordPress: perché la funzione query_posts() non dovrebbe essere usata mai

WordPress: perché la funzione query_posts() non dovrebbe essere usata mai

La funzione di WordPress query_posts è in assoluto una delle funzioni più usate per gestire il Loop di WordPress. Tuttavia su questa funzione esiste ancora oggi della confusione su cui è necessario fare chiarezza.

query_posts() modifica il Loop, non ne crea uno nuovo

Questa funzione altera il Loop di WordPress sostituendone i parametri con quelli specificati. Come afferma la documentazione ufficiale:

query_posts() is a way to alter the main query that WordPress uses to display posts. I t does this by putting the main query to one side, and replacing it with a new query. To clean up after a call to query_posts, make a call to wp_reset_query(), and the original main query will be restored.

In tal senso query_posts() si comporta come un filtro sul Loop. Ad esempio:


query_posts( 'posts_per_page=5' );

Ma potremmo anche scrivere:


function display_posts_on_homepage( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', '5' );
    }
}
add_action( 'pre_get_posts', 'display_posts_on_homepage' );

query_posts() crea problemi di performance

La documentazione di WordPress è molto chiara in merito:

It should be noted that using this to replace the main query on a page can increase page loading times, in worst case scenarios more than doubling the amount of work needed or more. While easy to use, the function is also prone to confusion and problems later on.

Tempi di caricamento più lunghi, raddoppiamento del lavoro richiesto sulle pagine, confusione nell'uso: credo basti questo a dare un'idea dei rischi insiti nell'uso di questa funzione.

Torna su