¿Cómo puedo mostrar publicaciones solo si meta_value no está vacío
-
-
¿Qué versión de WordPressestás usando?Which version of WordPress are you using?
- 0
- 2011-03-02
- MikeSchinkel
-
@MikeSchinkel - Lo siento Mike,no viesto - Es 3.1.@MikeSchinkel - Sorry Mike, didn't see this — It's 3.1.
- 0
- 2011-03-02
- robalan
-
WP 3.5 solucionaesteproblema y lepermite usar unmétodo de comparación diferenteWP 3.5 fixes this problem and lets you use a different compare method
- 0
- 2017-12-06
- Erenor Paz
-
7 respuestas
- votos
-
- 2011-03-02
Hola @Rob:×
La razónpor la quenopuede averiguar cómo hacerloesporquenoesposible,almenosno sin recurrir a SQL.Intente agregar lo siguiente al archivo
functions.php
de sutema:add_filter('posts_where','yoursite_posts_where',10,2); function yoursite_posts_where($where,$query) { global $wpdb; $new_where = " TRIM(IFNULL({$wpdb->postmeta}.meta_value,''))<>'' "; if (empty($where)) $where = $new_where; else $where = "{$where} AND {$new_where}"; return $where; }
Sitiene campospersonalizados
'featured_image'
con valores vacíos,lo anterior losfiltrará.Si suproblemaes otra cosa,tendremos que ver cómo se ven sus datospara resolverlo.Una cosa queme da curiosidad;¿Cómo obtuviste valores vacíospara
'featured_image'
?Lainterfaz de usuario de administraciónen WordPress 3.1 hacetodo loposibleparaevitar queingrese valores vacíos. Espero queesto ayude.Hi @Rob:
The reason you can't figure out how to do it is because it's not possible, at least not without resorting to SQL. Try adding the following to your theme's
functions.php
file:add_filter('posts_where','yoursite_posts_where',10,2); function yoursite_posts_where($where,$query) { global $wpdb; $new_where = " TRIM(IFNULL({$wpdb->postmeta}.meta_value,''))<>'' "; if (empty($where)) $where = $new_where; else $where = "{$where} AND {$new_where}"; return $where; }
If you have custom
'featured_image'
fields with empty values the above will filter them out. If you problem is something else, we'll have to see what your data looks like to solve it.One thing I'm curious about; how did you get empty values for
'featured_image'
? The admin UI in WordPress 3.1 does its best to keep you from entering empty values. Hope this helps.-
Gracias a Dios ... así queno somos solonosotros.Esbueno saberlo,supongo.Gracias @MikeSchinkel. Realmente deberíanponeresoen el códice ... Esperamos laexplicación.¡¡Gracias!!Thank god... so it's not just us. That's good to know, I suppose. Thank you @MikeSchinkel - They really ought to put that in the codex... Looking forward to the explanation. Thanks!!
- 0
- 2011-03-02
- robalan
-
@Rob:estabaperdiendomis conocimientos de 3.0 y ahora loestoyprobandoen 3.1 yparece quefunciona.Tengo dospublicaciones y una con un campopersonalizado `Featured_image` y su consultafuncionabien.Queestasencontrando¿Existe laposibilidad de que su consultaesté cargandopublicaciones quetienen un campopersonalizado `Featured_image`pero dondeel valor deese campoestá vacío?@Rob - So I was going off my 3.0 knowledge and now I'm testing it in 3.1 and it does seem to work. I have two posts and one with a `featured_image` custom field and your query works fine. What are you finding? Is there a chance your query is loading posts that do have a `featured_image` custom field but where the value for that field is empty?
- 0
- 2011-03-02
- MikeSchinkel
-
@MikeSchinkel - ¿Noesbroma?Sí,esoesexactamente lo queestá haciendo: cadapublicacióntiene el campo Featured_image,simplementenoestántodos configurados.Detodosmodos,está cargandotodas laspublicaciones.@MikeSchinkel - No kidding? Yes, that's exactly what it's doing — every post has the featured_image field, they're just not all set. It's loading up all posts anyway.
- 0
- 2011-03-02
- robalan
-
@Rob: veami respuesta actualizada.@Rob - See my updated answer.
- 0
- 2011-03-02
- MikeSchinkel
-
@MikeSchinkel - ¡Gracias!Pareceestarfuncionandoperfectamente,después de configurarelpost_typetambiénen la consulta.Los valores vacíostienen unpropósito:notodas laspublicacionestienen estaimagen destacada (y conozco laminiatura de lapublicación,simplementenoes unabuena opciónparaeste sitio).¡Muchasgracias!@MikeSchinkel - Thank you! It seems to be working perfectly, after setting the post_type in the query also. The empty values are purposeful — not every post has this featured image (and I know about the post thumbnail, it's just not a good option for this site). Thanks so much!
- 0
- 2011-03-02
- robalan
-
@MikeSchinkel - Me corrijo -funcionaen las consultas que quería,peroestá causando 404en todaspartes.Páginas depublicacionesindividuales,archivos ...: o \ ¿Algunaidea?@MikeSchinkel - I stand corrected - it works on the queries that I wanted it to, but it's causing 404's everywhere else. Single post pages, archives... :o\ Any ideas?
- 0
- 2011-03-02
- robalan
-
Enelejemplo de códigoen supregunta anterior,intente poner la llamada `add_filter ()`justo antes de su llamada `WP_Query ()`,luegoponga `remove_filter ('posts_where','yoursite_posts_where');`justo antes de llamar a `wp_reset_query () `.In the code sample in your question above, try putting the `add_filter()` call just before your `WP_Query()` call, then put `remove_filter('posts_where','yoursite_posts_where');` just before you call `wp_reset_query()`.
- 0
- 2011-03-02
- Dougal Campbell
-
¿Ese código verifica TODOS los campospersonalizadospara ver si ALGUNO deellosestá vacío?¿Qué sucede si quiero que la consulta solo verifique un campoespecial y vea siestá vacío sinimportar cuáles sean los otros?That code checks ALL custom fields to see if ANY of them are empty? What if I want the query to only check for one special field and see if that is empty no matter what the other ones are?
- 0
- 2011-05-31
- Jens Törnell
-
- 2011-03-04
Estoparecefuncionarpara obtenerel valoren la consulta,aunquenoestoy seguro de si obtiene resultados válidos ..
'meta_query' => array( array( 'key' => 'some_key', 'value' => array(''), 'compare' => 'NOT IN' ) )
Notuvetiempo de crear camposparaprobar los resultados,pero heestado observando consultas con las que hetrabajado hoy ynoté que
NOT IN
tomaráfelizmente unamatriz vacía.This seems to work for getting the value into the query, not sure about whether it pulls valid results though..
'meta_query' => array( array( 'key' => 'some_key', 'value' => array(''), 'compare' => 'NOT IN' ) )
Not had time to create fields to test the results, but i've been watching queries i've worked with today and noticed
NOT IN
will happily take an empty array.-
Sé queestaes una respuesta antigua,peropara aquellos quepruebanesteenfoque,funciona con `'compare'=> 'NOT LIKE'`en lugar de`' NOT IN` 'I know this is an old answer, but for those trying this apparoach, it works with `'compare' => 'NOT LIKE'` instead of `'NOT IN`'
- 0
- 2012-07-11
- handsofaten
-
Seguramentemáseficiente de usar!=En lugar denoestar onome gusta.Igual que http://wordpress.stackexchange.com/a/10286/32863 (setrata de clavesmeta,peroelmismoprincipio)Surely more efficient to use != instead of not in or not like. Same as http://wordpress.stackexchange.com/a/10286/32863 (that is about meta keys, but same principle)
- 3
- 2015-09-09
- Adam
-
Una solución aúnmás limpia: como ya dijo Adam.Es utilizar: `'valor'=> '', 'comparar'=> '!=' 'Even cleaner solution: like Adam stated already. Is to use: `'value' => '', 'compare' => '!=' `
- 5
- 2018-04-20
- Martijn van Hoof
-
Sinecesita verificarpara asegurarse de queno sea unamatriz vacía ... `'valor'=>matriz ('',matriz (),serializar (matriz ())),'comparar'=> 'NO EN'`If you need to check to make sure it's not an empty array... `'value' => array('', array(), serialize(array())), 'compare' => 'NOT IN'`
- 0
- 2018-08-14
- StephanieQ
-
- 2017-12-06
Estaes unapregunta antigua,peroparece que Wordpress ha solucionadoesta "funciónfaltante": ahora,de acuerdo con Wordpress Codex esposible verificar laexistencia (onoexistencia) de lameta clave,comoesta
'meta_query' => array( array( 'key' => 'featured_image', 'compare' => 'EXISTS', //or "NOT EXISTS", for non-existance of this key ) )
Estoestá disponible apartir de WP>=3.5.
This is an old question, but it seems Wordpress has fixed this "missing feature": now, according to Wordpress Codex is possible to check for existence (or non-existence) of the meta key, like this
'meta_query' => array( array( 'key' => 'featured_image', 'compare' => 'EXISTS', //or "NOT EXISTS", for non-existance of this key ) )
This is available as of WP >= 3.5.
-
`EXISTS`mostrará valores vacíos quenoes lo quebuscamos aquí.Lamejor soluciónes `` value '=>' ',' compare '=>'!='' En lo que respecta amispruebas.`EXISTS` will show empty values which is not what we're after here. The best solution is `'value' => '', 'compare' => '!=' ` as far as my testing goes.
- 0
- 2019-08-09
- Ben
-
@Ben Esoesexactamente lo queintentóel OP,peroparece quenotuvo éxito.Agreguémi soluciónpara asegurarme de que laspersonas quepasabanbuscando unmétodopara recuperarpublicacionesbasadasen laexistencia demeta_keypudieranencontrarlo.Dado queel valor de unmetapuede ser "algo","vacío" o "nulo" (en caso de queelmetanoexista),probablemente lamejor solución seríafusionar las dos opciones con una relación "Y"@Ben That's exactly what the OP tried, but without any success, it seems. I added my solution to make sure people passing by searching for a method to retrieve posts based on existence of meta_key could find it. Since the value of a meta can be "something", "empty" or "null" (in case the meta doesn't exist), probably the best solution would be to merge the two options with an "AND" relation
- 2
- 2019-08-09
- Erenor Paz
-
- 2018-01-10
Estaes la consulta queme funcionó.Muy similar a la comparaciónen la respuesta det31os de 2011,pero debido a que la clave/valormetaes solo una cadena detexto simple,nonecesita ser unamatrizmeta_query.
$args = array( 'posts_per_page' => 5,//replaced 'showposts' in version 2.1 'meta_key' => 'featured_image', 'meta_value' => array(''), 'meta_compare' => 'NOT IN' );
Porelmotivo que sea,usar 'meta_value'=> '' y 'meta_compare'=> '!=' o 'meta_compare'=> 'NOLIKE 'todavíame sacótodas laspublicaciones,peroprobablementetenga algo que ver conel hecho de que creémi meta valor usandoel complemento Advanced Custom Fields (ACF).
Obtengamásinformación sobre losparámetros de campopersonalizadosen el códice .
This is the query that worked for me. Very similar to the comparison in t31os's answer from 2011, but because the meta key/value is just a simple textstring, it doesn't need to be a meta_query array.
$args = array( 'posts_per_page' => 5,//replaced 'showposts' in version 2.1 'meta_key' => 'featured_image', 'meta_value' => array(''), 'meta_compare' => 'NOT IN' );
For whatever reason, using 'meta_value' => '' and 'meta_compare' => '!=' or 'meta_compare' => 'NOT LIKE' still pulled all posts for me, but it probably has something to do with the fact that I created my meta value using the Advanced Custom Fields (ACF) plugin.
-
- 2011-03-03
Estoestá arregladoen WP 3.2-alpha:
This is fixed in WP 3.2-alpha:
-
- 2014-01-24
¿Mefalta algo?
<?php $args = array( 'post_type' => 'post', 'posts_per_page' => -1, 'meta_key' => "featured_image" ); $the_query = new WP_Query( $args ); ?>
¿No será suficiente?
Am i missing something?
<?php $args = array( 'post_type' => 'post', 'posts_per_page' => -1, 'meta_key' => "featured_image" ); $the_query = new WP_Query( $args ); ?>
Won't that do it?
-
Editar: del códice: `` `$ query=new WP_Query ('meta_key=Featured_image');` ``mira aquí: http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_ParametersEdit: from the codex: ```$query = new WP_Query( 'meta_key=featured_image' );``` look here:http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
- 0
- 2014-01-24
- Infinity Media
-
Primero,siemprepuede [editar] unapregunta o respuestaen lugar de agregar un comentario.Segundo: No **mal uso ** de respuestasen lugar de comentarios.First, you can always [edit] a question or answer instead of adding a comment. Second: Don't **misuse** answers instead of comments.
- 0
- 2014-01-25
- kaiser
-
Sitiene unanuevapregunta,hágala haciendo clicen elbotón [Hacerpregunta] (http://wordpress.stackexchange.com/questions/ask).Incluya unenlace aestapregunta si ayuda aproporcionar contexto.If you have a new question, please ask it by clicking the [Ask Question](http://wordpress.stackexchange.com/questions/ask) button. Include a link to this question if it helps provide context.
- 0
- 2014-01-25
- kaiser
-
@kaiser -me parece queestaba respondiendo.Nopregunta si su códigoes válido,pero supongo que responde sarcásticamente a lapregunta con lo que cree quefuncionará.@kaiser - seems to me like he was answering. He's not asking if his code is valid, but I suppose sort of sarcastically answering the question with what he believes will work.
- 0
- 2016-09-05
- Nathan
-
@Nathan Paraestoestán los comentarios.@Nathan This is what comments are for.
- 0
- 2016-09-05
- kaiser
-
@kaiser,¿Los comentarios sonparapublicar respuestas y código?¿Cómopublicas códigoen un comentario?@kaiser, Comments are for posting answers and code? How do you post code in a comment?
- 0
- 2016-09-05
- Nathan
-
@Nathan Me refería a laparte sarcástica de la respuesta.El código debe ser una respuesta,incluida algunaexplicación.@Nathan I was referring to the sarcastic part of the answer. The code should be an answer – including some explanation.
- 0
- 2016-09-05
- kaiser
-
Hubo unerroren WordPresspero ahoraestá arreglado.Estaes laforma correcta de hacerlo.There was a bug in WordPress but now it's fixed. This is the correct way to do it.
- 0
- 2016-12-04
- Ryan Taylor
-
Trespersonas ya hanintentado resolveresto,yno llegamos anada. Quieromostrar solo laspublicaciones quetengan un valoren lameta_clave 'imagen_ destacada'
Entonces ... si 'Featured_image'noestá vacía,muestra lapublicación. Aquíestáel código:
Hemosprobado literalmentetodas las combinaciones que senos ocurren,las opciones obsoletasmeta_ *,query_posts,get_posts,en lugar de WP_Query ... Nada. Imprimió la declaración de selección,no semuestraningún campo de valormeta. Existe -para laspublicaciones (para cadapublicación) yexisteen labase de datos.
Hemos vistotodas laspublicaciones sobreeltemaen estemomento,incluidasestas:
query_posts ymostrar resultados solo si un campopersonalizadonoestá vacío
http://scribu.net/wordpress/advanced-metadata-queries.html
Zilch. Porfavor ayuda ...