$ Globals ['wp_the_query'] vs global $ wp_query
-
-
Eu diria "Global $ WP_Query" apenaspara responder suaperguntaem uma linha!I would say `global $wp_query` just to answer your question in one line!
- 2
- 2016-03-14
- Sumit
-
Qual é a diferença?What is the difference?
- 0
- 2016-03-14
- Nathan Powell
-
3 respostas
- votos
-
- 2016-03-14
Vocêperdeu um,
$globals ['wp_query']
. Paratodos osfins,$ Globals ['WP_Query']===$ WP_Query
.$ Globals ['WP_Query']
é,noentanto,melhorpara a legibilidadee deve ser usadoem vez de$ wp_query
,mas,quepermanecepreferencialpessoalAgora,em ummundoperfeito onde os unicórniosgovernam omundo,
$globals ['wp_the_query']===$ Globals ['WP_Query']===$ WP_Query
. Porpadrão,isso deve ser verdadeiro. Se olharmos ondeestesglobaisestão definidos (WP-Settings.php
),você verá o objeto de consultaprincipal será armazenadoem$globals ['wp_the_query']
e$ Globals ['WP_Query']
é apenas uma cópia duplicada de$globals ['wp_the_query']
/** * Objeto de consulta do WordPress * @global wp_query $ wp_the_query * @Since 2.0.0. */ $ Globals ['WP_THE_QUERY']=NOVO WP_Query (); /** * Detém a referênciapara @see $ wp_the_query * Useesteglobalpara consultas do WordPress * @global wp_query $ wp_query * @Since 1.5.0. */ $ Globals ['WP_Query']=$ Globals ['WP_THE_QUERY'];
A razãoparafazerisso dessamaneira,éporque o WordPress viu a chegada de
query_posts
Query_posts ($ consulta) { $ Globals ['WP_Query']=NOVO WP_Query (); Retornar $ Globals ['WP_Query'] - > consulta ($ consulta); }
Como vocêpode ver,
Query_Posts
Define o objeto de consultaprincipalpara a consultapersonalizada atual Run. Isso quebra aintegridade do objeto de consultaprincipal,quefornece dadosincorretos,então qualquer coisa que dependano objeto de consultaprincipal é quebrado devido a dadoserrados.Umamaneira de contadorfoi criar outroglobalpara armazenar o objeto de consultaprincipal,
$globals ['wp_the_query']
quefoiintroduzidona versão 2.0.0. Estenovo Globalmantém o objeto de consultaprincipale$globals ['wp_query']
apenas uma cópia. Através dewp_reset_query ()
,agorapoderíamos redefinir$ Globals ['WP_Query']
Voltarpara o objeto de consultaprincipal originalpara restaurar suaintegridade.Masestenão é ummundoperfeitoe
query_posts
é opróprio diabo. Emboramilhares de avisos,aspessoas ainda usamquery_posts
. Além de quebrar a consultaprincipal,representa a consultaprincipal,tornando-amuitomais lenta como uma consultapersonalizadanormal comwp_query
. Muitaspessoastambémnão redefinem oQuery_Posts
com WP_Reset_Query ()
quando concluído,o quefazquery_posts
aindamaismal.Porquenãopodemosfazernada sobreisso,e não épossívelparar ospluginse ostemas do uso
Query_posts
e nuncapodemos saber se umQuery_Posts
Queryfoi redefinido comWP_RESET_QUERY ()
,precisamos de uma cópiamais confiável do objeto de consultaprincipal que sabemosnos dará 99,99999% confiáveis,dados corretos. É aí que é um código ['wp_the_query'] é útil,poisnenhum código relacionado ao WordPresspode alterar seu valor (,exceto através dosfiltrose ações dentrowp_query
em si ).Quick Proof,execute o seguinte
var_dump ($globais ['wp_the_query']); var_dump ($globais ['wp_query']); query_posts ('S=CRAP'); var_dump ($globais ['wp_the_query']); var_dump ($globais ['wp_query']);
e verifique os resultados.
$ Globals ['WP_THE_QUERY']
nãofoi alteradoe$ Globals ['WP_Query']
tem. Então,o que émais confiável?notafinal,
$globals ['wp_the_query']
é não um substitutoparawp_reset_query ()
.wp_reset_query ()
devesempre ser usado com query_posts
equery_posts
deve nunca ser usava.para concluir
Se vocêprecisar de um código confiável,que quase semprenuncafalhará,use
$globals ['wp_the_query']
,se você confiare acreditarpluginse código detemae acreditar queninguém usaquery_posts
ou é usá-lo corretamente,use$globals ['wp_query']
ou$ wp_query
Editarimportante
Sendo respondendo aperguntasneste site agorapor alguns anos,vimuitos usuários usando
$ wp_query
como uma variável local,quepor sua veztambém quebra o objeto de consultaprincipal. Isso aumenta aindamais a vulnerabilty do$ WP_Query
.Comoexemplo,algumaspessoasparaeste
$ WP_Query=New WP_Query ($ args);
Qual é oessencialexatamente omesmo que o
query_posts
estáfazendoYou 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/) alterações `Global $ WP_Query.`Global $ WP_The_Query 'mantém a referência a ** [a 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
-
Meu comentárionãofoipretendido como uma correção,entãominhas desculpas seisso acontecesse.Euestava apenas resumindo (TL; DR se você quiser) Ao apontar o que acredito é um dos aspectosmais significativos de `$ wp_the_query` como se refere aométodo` wp_query ::is_main_query () ',quenãofoimencionado:D.My 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 desculpas,euentendimal seuprimeiro comentário ;-).Sim,"IS_MAIN_QUERY ()",que é um wrapperfor `WP_Query ::is_main_query ()` que verifica o objeto de consulta atual contra o objeto de consultaprincipal salvoem `$globals ['wp_the_query']`Isso émuitoimportante quando vocêexecuta ações `Pre_Get_Posts`e só quer segmentar a 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
-
Respostamuitobem feita!@Evanmattson que deveriater sido um [editar].Pretty well done answer! @EvanMattson That should have been an [edit].
- 0
- 2016-04-06
- kaiser
-
Vocêpodeincluirmencionar afunção `is_main_query`na seção *importanteeditar?Euestava usando `pre_get_posts 'hojee acheitotalmente útil usaressafunção desde queeuestava olhandopara" $ 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
Apalavra-chaveglobalimporta a variávelpara oescopo local,enquanto $ Globals apenas concede ao acesso à variável.
Paraelaborar,se você usar
global $wp_the_query;
Vocêpode usar$wp_the_query
dentro doescopo local sem usar apalavraglobalnovamente.Então,basicamente,global $wp_the_query
pode ser comparado com$wp_the_query = $GLOBALS['wp_the_query']
editar
i MisRead WP_Querypara WP_The_Query,então aminha respostanão é uma resposta completapara apergunta,mas aindaforneceinformaçõesgerais sobre a diferençaentre
global $variable
e$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,arquivo [editar] comoesta realmentenão é uma respostapara apergunta original.Apenasfyi `$ Globals ['foo']`permite que _OverRiding_ ou desblementando a variáveltambém.Então é um _bit_mais do que você descreve aqui.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
Basicamente,é uma cópia do outro.Check-out
wp-settings.php
,linhas 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'];
Qual é a diferençaentre
$GLOBALS['wp_the_query']
eglobal $wp_query
?Por queprefere um sobre o outro?