$ GLOBALS ['wp_the_query'] frente a $ wp_query global
-
-
¡Diría `global $ wp_query` solopara responder supreguntaen una línea!I would say `global $wp_query` just to answer your question in one line!
- 2
- 2016-03-14
- Sumit
-
¿Cuáles la diferencia?What is the difference?
- 0
- 2016-03-14
- Nathan Powell
-
3 respuestas
- votos
-
- 2016-03-14
Te hasperdido uno,
$GLOBALS['wp_query']
. Atodos losefectos,$GLOBALS['wp_query'] === $wp_query
.$GLOBALS['wp_query']
es,sinembargo,mejorpara la legibilidad y debe usarseen lugar de$wp_query
,PERO,eso sigue siendo unapreferenciapersonalAhora,en unmundoperfecto donde los unicorniosgobiernanelmundo,
$GLOBALS['wp_the_query'] === $GLOBALS['wp_query'] === $wp_query
. Por defecto,esto debería ser cierto. Simiramos dónde seestablecenestosglobales (wp-settings.php
),verá queel objeto de consultaprincipalestá almacenadoen$GLOBALS['wp_the_query']
y$GLOBALS['wp_query']
es solo una copia duplicada de$GLOBALS['wp_the_query']
/** * WordPress Query object * @global WP_Query $wp_the_query * @since 2.0.0 */ $GLOBALS['wp_the_query'] = new WP_Query(); /** * Holds the reference to @see $wp_the_query * Use this global for WordPress queries * @global WP_Query $wp_query * @since 1.5.0 */ $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
La razónpara hacerlo deestamaneraesporque WordPress vio la llegada de
query_posts
en la versión 1.5.function query_posts($query) { $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); }
Comopuede ver,
query_posts
estableceel objeto de consultaprincipalen la consultapersonalizada actual que seestáejecutando. Esto rompe laintegridad del objeto de consultaprincipal,lo que leproporciona datosincorrectos,por lo que cualquier cosa que sebaseen el objeto de consultaprincipal se rompe debido a datosincorrectos.Unaforma de contrarrestarestofue crear otroglobalpara almacenarel objeto de consultaprincipal,
$GLOBALS['wp_the_query']
que seintrodujoen la versión 2.0.0. Estenuevoglobal contieneel objeto de consultaprincipal y$GLOBALS['wp_query']
solo una copia. Através dewp_reset_query()
,ahorapodríamos restablecer$GLOBALS['wp_query']
al objeto de consultaprincipal originalpara restaurar suintegridad.Peroestenoes unmundoperfecto,y
query_posts
sonelmismo diablo. Aunque haymiles de advertencias,lagente todavía usaquery_posts
. Además de romper la consultaprincipal,vuelve aejecutar la consultaprincipal,haciéndolamuchomás lenta que una consultapersonalizadanormal conWP_Query
. Muchagente tampoco restablece la consultaquery_posts
conwp_reset_query()
cuandotermina,lo que hace quequery_posts
sea aúnmásmaligno.Porquenopodemos hacernada al respecto,ynopodemosevitar que los complementos ytemas usen
query_posts
ynuncapodremos saber si una consulta dequery_posts
se restableció conwp_reset_query()
,necesitamos una copiamás confiable del objeto de consultaprincipal que sabemos quenos dará un 99,99999% de datos correctos yfiables. Ahíes donde$GLOBALS['wp_the_query']
es útil ya queningún código relacionado con WordPresspuede cambiar su valor (excepto através de losfiltros y acciones dentro deWP_Query
mismo ).Prueba rápida,ejecute lo siguiente
var_dump( $GLOBALS['wp_the_query'] ); var_dump( $GLOBALS['wp_query'] ); query_posts( 's=crap' ); var_dump( $GLOBALS['wp_the_query'] ); var_dump( $GLOBALS['wp_query'] );
y verifique los resultados.
$GLOBALS['wp_the_query']
no cambió,y$GLOBALS['wp_query']
sí. Entonces,¿cuálesmás confiable?Notafinal,
$GLOBALS['wp_the_query']
NO es un reemplazo dewp_reset_query()
.wp_reset_query()
debe siempre usarse conquery_posts
,yquery_posts
nunca debe usarse usado.PARA CONCLUIR
Sinecesita un código confiable que casi siemprefallará,use
$GLOBALS['wp_the_query']
,si confía y creeen los complementos yel código deltema y cree quenadie usaquery_posts
o loestá usando correctamente,use$GLOBALS['wp_query']
o$wp_query
EDICIÓN IMPORTANTE
Alestar respondiendopreguntasen este sitio durante unpar de años,vi amuchos usuarios usar
$wp_query
como variable local,que a su veztambién rompeel objeto de consultaprincipal. Esto aumenta aúnmás la vulnerabilidad del$wp_query
.Comoejemplo,algunaspersonas aesto
$wp_query = new WP_Query( $args );
queen esenciaesexactamente lomismo que
query_posts
están haciendoYou have missed one,
$GLOBALS['wp_query']
. For all purposes,$GLOBALS['wp_query'] === $wp_query
.$GLOBALS['wp_query']
is however better for readability and should be used instead of$wp_query
, BUT, that remains personal preferenceNow, in a perfect world where unicorns rule the world,
$GLOBALS['wp_the_query'] === $GLOBALS['wp_query'] === $wp_query
. By default, this should be true. If we look at where these globals are set (wp-settings.php
), you will see the main query object is stored in$GLOBALS['wp_the_query']
and$GLOBALS['wp_query']
is just a duplicate copy of$GLOBALS['wp_the_query']
/** * WordPress Query object * @global WP_Query $wp_the_query * @since 2.0.0 */ $GLOBALS['wp_the_query'] = new WP_Query(); /** * Holds the reference to @see $wp_the_query * Use this global for WordPress queries * @global WP_Query $wp_query * @since 1.5.0 */ $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
The reason for doing it this way, is because WordPress saw the arrival of
query_posts
in version 1.5.function query_posts($query) { $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); }
As you can see,
query_posts
sets the main query object to the current custom query beign run. This breaks the integrity of the main query object, which gives you incorrect data, so anything that relies on the main query object is broken due to wrong data.A way to counter this was to create another global to store the main query object,
$GLOBALS['wp_the_query']
which was introduced in version 2.0.0. This new global hold the main query object and$GLOBALS['wp_query']
just a copy. Throughwp_reset_query()
, we could now reset$GLOBALS['wp_query']
back to the original main query object to restore its integrity.But this is not a perfect world, and
query_posts
are the devil himself. Although thousands of warnings, people still usequery_posts
. Apart from breaking the main query, it reruns the main query, making it much slower as a normal custom query withWP_Query
. Many people also do not reset thequery_posts
query withwp_reset_query()
when done, which makesquery_posts
even more evil.Because we cannot do anything about that, and cannot stop plugins and themes from using
query_posts
and we can never know if aquery_posts
query was reset withwp_reset_query()
, we need a more reliable copy of the main query object which we know will give us 99.99999% reliable, correct data. That is where$GLOBALS['wp_the_query']
is useful as no WordPress related code can change it's value (except through the filters and actions insideWP_Query
itself).Quick proof, run the following
var_dump( $GLOBALS['wp_the_query'] ); var_dump( $GLOBALS['wp_query'] ); query_posts( 's=crap' ); var_dump( $GLOBALS['wp_the_query'] ); var_dump( $GLOBALS['wp_query'] );
and check the results.
$GLOBALS['wp_the_query']
did not change, and$GLOBALS['wp_query']
has. So which is more reliable?Final note,
$GLOBALS['wp_the_query']
is NOT a replacement forwp_reset_query()
.wp_reset_query()
should always be used withquery_posts
, andquery_posts
should never be used.TO CONCLUDE
If you need reliable code which will almost always never fail, use
$GLOBALS['wp_the_query']
, if you trust and believe plugins and theme code and believe no one usesquery_posts
or is using it correctly, use$GLOBALS['wp_query']
or$wp_query
IMPORTANT EDIT
Being answering questions on this site now for a couple of years, I saw many users using
$wp_query
as a local variable, which in turn also breaks the main query object. This further increases the vulnerabilty of the$wp_query
.As example, some people to this
$wp_query = new WP_Query( $args );
which is in essence the exactly the same as what
query_posts
are doing-
[query_posts ()] (https://developer.wordpress.org/reference/functions/query_posts/) cambia `global $ wp_query`.`global $ wp_the_query` contiene la referencia a ** [la consultaprincipal] (https://developer.wordpress.org/reference/classes/wp_query/is_main_query/) **[query_posts()](https://developer.wordpress.org/reference/functions/query_posts/) changes `global $wp_query`. `global $wp_the_query` holds the reference to **[the main query](https://developer.wordpress.org/reference/classes/wp_query/is_main_query/)**
- 1
- 2016-03-15
- Evan Mattson
-
Mi comentarionopretendía ser una corrección,así queme disculpo si lo hizo.Simplementeestaba resumiendo (TL; DR si lo desea)mientras señalaba lo que creo quees uno de los aspectosmás significativos de `$ wp_the_query`en lo que respecta almétodo` WP_Query ::is_main_query () `,queno semencionó:reMy comment wasn't intended as a correction, so my apologies if it did. I was merely summarizing (TL;DR if you will) while pointing out what I believe is one of the most significant aspects of `$wp_the_query` as it pertains to the `WP_Query::is_main_query()` method, which was not mentioned :D
- 0
- 2016-03-16
- Evan Mattson
-
@EvanMattson Disculpas,entendímaltuprimer comentario ;-).Sí,`is_main_query ()`,quees un contenedorpara `WP_Query ::is_main_query ()` que comparael objeto de consulta actual conel objeto de consultaprincipalguardadoen `$ GLOBALS ['wp_the_query']`.Estoesmuyimportante cuandoejecuta acciones `pre_get_posts` y solo quiere apuntar a la consultaprincipal ;-)@EvanMattson Apologies, I misunderstood your first comment ;-). Yes, `is_main_query()`, which is a wrapper for `WP_Query::is_main_query()` which checks the current query object against the main query object saved in `$GLOBALS['wp_the_query']`. This is quite important when you run `pre_get_posts` actions and just want to target the main query ;-)
- 0
- 2016-03-16
- Pieter Goosen
-
¡Respuestabastantebien hecha!@EvanMattson Eso debería haber sido un [editar].Pretty well done answer! @EvanMattson That should have been an [edit].
- 0
- 2016-04-06
- kaiser
-
¿Puedeincluir unamención de lafunción `is_main_query`en la sección * EDICIÓN IMPORTANTE?Estaba usando `pre_get_posts` hoy yencontré absolutamente útil usaresafunción ya queestabamirando` $ wp_query`.Can you include mention of `is_main_query` function in the *IMPORTANT EDIT section? I was using `pre_get_posts` today and found it utterly useful to use that function since I was looking at `$wp_query`.
- 0
- 2017-03-18
- Nathan Powell
-
- 2016-03-14
Lapalabra claveglobalimporta la variable al ámbito local,mientras que $ GLOBALS solo le otorga acceso a la variable.
Para ampliar,si usa
global $wp_the_query;
puede usar$wp_the_query
dentro del ámbito local sin usar lapalabraglobalnuevamente.Entonces,básicamente,global $wp_the_query
sepuede comparar con$wp_the_query = $GLOBALS['wp_the_query']
<×EDIT×
Leímal wp_querypara wp_the_query,por lo quemi respuestanoes una respuesta completa a lapregunta,pero aúnproporcionainformacióngeneral sobre la diferenciaentre
global $variable
y$GLOBALS['variable']
The global keyword imports the variable into the local scope, while $GLOBALS just grants you access to the variable.
To elaborate, if you use
global $wp_the_query;
you can use$wp_the_query
inside the local scope without using the word global again. So basicallyglobal $wp_the_query
can be compared to$wp_the_query = $GLOBALS['wp_the_query']
EDIT
I misread wp_query for wp_the_query so my answer isn't a complete answer to the question but still provides general information about the difference between
global $variable
and$GLOBALS['variable']
-
Porfavor,envíe un [editar] ya queesto realmentenoes una respuesta a lapregunta original.Solopara suinformación,`$ GLOBALS ['foo']`permite _anular_ o desarmar la variabletambién.Así quees un _bit_más de lo que describe aquí.Please, file an [edit] as this really is not an answer to the original question. Just FYI `$GLOBALS['foo']` allows _overriding_ or unsetting the variable as well. So it's a _bit_ more than what you describe here.
- 0
- 2016-04-06
- kaiser
-
- 2016-03-14
Básicamente,unoes copia del otro.Consulte
wp-settings.php
,líneas 292-305:$GLOBALS['wp_the_query'] = new WP_Query(); $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
Basically one is copy of the other. Check out
wp-settings.php
, lines 292-305:$GLOBALS['wp_the_query'] = new WP_Query(); $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
¿Cuáles la diferenciaentre
$GLOBALS['wp_the_query']
yglobal $wp_query
?¿Por quépreferir uno sobreel otro?