[转]How to query posts filtered by custom field values
Description
It is often necessary to query the database for a list of posts based on a custom field value. This guide will demonstrate how it is possible using the native WP functions
Requirements
- Understanding of the get_posts() function
- Understanding of the WP_Query arguments
Example 1
Compare with a single custom field value
In this example, we will find all posts that have a post_type of ‘event’ where the custom field ‘location’ is equal to ‘Melbourne’. The custom field ‘ location’ in this case could be a text field, radio button or select field (something that saves a single text value)
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_key' => 'location',
'meta_value' => 'Melbourne'
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
Example 2
Compare with multiple custom field values (text based values)
In this example, we will find all posts that have a post_type of ‘event’ where the custom field ‘location’ is equal to ‘Melbourne’ and the custom field ‘attendees’ is higher than 100. The custom field ‘ attendees’ in this case could be a number field, text field, radio button or select field (something that saves a single text value)
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'location',
'value' => 'Melbourne',
'compare' => '='
),
array(
'key' => 'attendees',
'value' => 100,
'type' => 'NUMERIC',
'compare' => '>'
)
)
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
Example 3
Compare with multiple custom field values (array based values)
In this example, we will find all posts that have a post_type of ‘event’ where the custom field ‘location’ is equal to ‘Melbourne’ or ‘Sydney’. The custom field ‘ location’ in this case could be a multi-select or checkbox field (something that saves a serialized array value)
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'location',
'value' => 'Melbourne',
'compare' => 'LIKE'
),
array(
'key' => 'location',
'value' => 'Sydney',
'compare' => 'LIKE'
)
)
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
Example 4
Query based on repeater field values
In this example, we will find all posts that have a post_type of ‘event’ which have at least 1 row of data for the ‘images’ repeater field. The custom field ‘images’ in this case is a repeater field containing a sub field called ‘image’.
Due to the nature that the repeater field saves it’s data, it can be thought of that the value for ‘images’ is a number containing the number of rows. You can read more about the repeater field data here
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_query' => array(
array(
'key' => 'images',
'value' => 0,
'type' => 'NUMERIC',
'compare' => '>'
)
)
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php // load 'images' repeater field data. Please see repeater field for code examples ?>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
Example 5
Compare with sub custom field values
In this example, we will find all posts that have a post_type of ‘event’ where the custom field ‘images’ has a sub field ‘type’ with a value of ‘Speaker’. The custom field ‘images’ is a repeater field containing 2 sub fields; ‘image’ (image field) and ‘type’ (a select field containing choices such as ‘Speaking’, ‘Performance’, ‘Music’, ‘Dance’). This situation could be found in a blog that captures an event’s photographs. Each photograph for an event is loaded into the repeater field and a ‘type’ of image is selected in the same row.
For sub field querying to work, we need to remember that the row number is not known (where the image is of type ‘Speaker’). Therefore, we must use a LIKE clause in our SQL query to allow for a WILDCARD in the meta_key search. To do this, we create a custom filter to replace the standard ‘=’ with ‘LIKE’. You can see this below
<?php
// custom filter to replace '=' with 'LIKE'
function my_posts_where( $where )
{
$where = str_replace("meta_key = 'images_%_type'", "meta_key LIKE 'images_%_type'", $where);
return $where;
}
add_filter('posts_where', 'my_posts_where');
// args
$args = array(
'numberposts' => -1,
'post_type' => 'event',
'meta_query' => array(
array(
'key' => 'images_%_type',
'value' => 'type_1',
)
)
);
// get results
$the_query = new WP_Query( $args );
// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
Notes
Please note that some plugins / themes will hook in and modify any WP_Query attributes. To avoid this potential conflict, you can add another setting to the $args array called 'suppress_filters' => false
[转]How to query posts filtered by custom field values的更多相关文章
- redmine computed custom field formula tips
项目中要用到Computed custom field插件,公式不知道怎么写,查了些资料,记录在这里. 1.http://apidock.com/ruby/Time/strftime 查看ruby的字 ...
- JIRA Plugin Development——Configurable Custom Field Plugin
关于JIRA Plugin开发的中文资料相当少,这可能还是由于JIRA Plugin开发在国内比较小众的原因吧,下面介绍下自己的一个JIRA Plugin开发的详细过程. 业务需求 创建JIRA IS ...
- Add custom field in Material Master
1.Add fields in the Append Structure of table MARA. 2.Configure SPRO IMG -> Logistics General -&g ...
- SharePoint Development - Custom Field using Visual Studio 2010 based SharePoint 2010
博客地址 http://blog.csdn.net/foxdave 自定义列表的时候有时候需要自定义一些字段来更好地实现列表的功能,本文讲述自定义字段的一般步骤 打开Visual Studio,我们还 ...
- Query DSL for elasticsearch Query
Query DSL Query DSL (资料来自: http://www.elasticsearch.cn/guide/reference/query-dsl/) http://elasticsea ...
- Yii的学习(3)--查询生成器 (Query Builder)
原文地址:http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder 不过原文是英文的,Yii的官网没有翻译这一章,自己就尝 ...
- yii Query Builder (yii 查询构造器) 官方指南翻译
/**** Query Builder translated by php攻城师 http://blog.csdn.net/phpgcs Preparing Query Builder 准备 Quer ...
- FluentData -Micro ORM with a fluent API that makes it simple to query a database 【MYSQL】
官方地址:http://fluentdata.codeplex.com/documentation MYSQL: MySQL through the MySQL Connector .NET driv ...
- 数据库之Query Builder
Yii的查询构造器提供了一个用面向对象的方法来构造SQL语句.他让开发人员可以用类的方法,属性来作为SQL语句的一部分.然后把不同部分组装到一个正确的SQL语句中,调用DAO的方法来执行.下面的例子演 ...
随机推荐
- javascript面向对象系列第五篇
<style> .test{height: 50px;width: 50px;background-color: pink;position:absolute;} #test2{left: ...
- [ 转载 ] Okhttp的用法
Android中OkHttp的使用 LuckyXiang 简书作者 02018-01-18 19:04 打开App Android中OkHttp的使用 官方网站 | Javadoc 1 简介 OkHt ...
- 排序算法之冒泡排序Java实现
排序算法之冒泡排序 舞蹈演示排序: 冒泡排序: http://t.cn/hrf58M 希尔排序:http://t.cn/hrosvb 选择排序:http://t.cn/hros6e 插入排序:ht ...
- 转MySQL常见错误分析与解决方法总结
一.Can't connect to MySQL server on 'localhost' (10061)翻译:不能连接到 localhost 上的mysql分析:这说明“localhost”计算机 ...
- Windows Server 2008 R2的web服务器nginx和Apache的比较
因为很喜欢nginx,所以也想尝试在Windows下使用nginx,前面安装配置都挺顺利,把域名解析尽量后,通过域名代理访问jboss,却异常的慢,起码有3秒的时间才显示页面,而这个页面是jboss的 ...
- AVL树理解
AVL树理解 简介 我们知道,AVL树也是平衡树中的一种,是自带平衡条件的二叉树,始终都在维护树的高度,保持着树的高度为logN,同时把插入.查找.删除一个结点的时间复杂度的最好和最坏情况都维持在O( ...
- Git_分支管理策略
通常,合并分支时,如果可能,Git会用Fast forward模式,但这种模式下,删除分支后,会丢掉分支信息. 如果要强制禁用Fast forward模式,Git就会在merge时生成一个新的comm ...
- 新型穿墙监控雷达Range-R:让你的隐私无所遁形(转)
还是隐私问题,原帖地址:http://www.freebuf.com/news/57446.html 在我们的认知中,政府对民众的监控已经成为一种常态.从电话.电子邮件到通信聊天.社交网络,一切细节都 ...
- chrome --headless --disable-gpu --dump-dom http://www.python.org
Driving Headless Chrome with Python:Python chrome --headless --disable-gpu --dump-dom http://www.pyt ...
- [Asp.net MVC]Html.AntiForgeryToken()
CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack”或者Session Riding,通常缩写为CSRF或者XSRF,是一种对网站 ...