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

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的更多相关文章

  1. redmine computed custom field formula tips

    项目中要用到Computed custom field插件,公式不知道怎么写,查了些资料,记录在这里. 1.http://apidock.com/ruby/Time/strftime 查看ruby的字 ...

  2. JIRA Plugin Development——Configurable Custom Field Plugin

    关于JIRA Plugin开发的中文资料相当少,这可能还是由于JIRA Plugin开发在国内比较小众的原因吧,下面介绍下自己的一个JIRA Plugin开发的详细过程. 业务需求 创建JIRA IS ...

  3. Add custom field in Material Master

    1.Add fields in the Append Structure of table MARA. 2.Configure SPRO IMG -> Logistics General -&g ...

  4. SharePoint Development - Custom Field using Visual Studio 2010 based SharePoint 2010

    博客地址 http://blog.csdn.net/foxdave 自定义列表的时候有时候需要自定义一些字段来更好地实现列表的功能,本文讲述自定义字段的一般步骤 打开Visual Studio,我们还 ...

  5. Query DSL for elasticsearch Query

    Query DSL Query DSL (资料来自: http://www.elasticsearch.cn/guide/reference/query-dsl/) http://elasticsea ...

  6. Yii的学习(3)--查询生成器 (Query Builder)

    原文地址:http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder 不过原文是英文的,Yii的官网没有翻译这一章,自己就尝 ...

  7. yii Query Builder (yii 查询构造器) 官方指南翻译

    /**** Query Builder translated by php攻城师 http://blog.csdn.net/phpgcs Preparing Query Builder 准备 Quer ...

  8. 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 ...

  9. 数据库之Query Builder

    Yii的查询构造器提供了一个用面向对象的方法来构造SQL语句.他让开发人员可以用类的方法,属性来作为SQL语句的一部分.然后把不同部分组装到一个正确的SQL语句中,调用DAO的方法来执行.下面的例子演 ...

随机推荐

  1. requests https访问错误SSLError: certificate verify failed 及InsecureRequestWarning处理办法

    转自: https://blog.csdn.net/mighty13/article/details/78076258?locationNum=3&fps=1 在使用requests访问某网站 ...

  2. 表单验证插件validate

    http://www.runoob.com/jquery/jquery-plugin-validate.html <!DOCTYPE html> <html lang="e ...

  3. ZOJ2112 BZOJ1901 Dynamic Rankings 树套树 带修改的区间第k小

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2112 树套树,线段树套splay或者主席树套树状数组,我抄了一下hzwer ...

  4. PHP session用redis存储

    redis的官方github这么说: phpredis can be used to store PHP sessions. To do this, configure session.save_ha ...

  5. [USACO11DEC]Grass Planting

    题目大意: 有一棵结点个数为n的树,有m个操作,可以将一段路径上每条边的权值+1或询问某一个边的权值. 思路: 树链剖分+线段树. 轻重链划分本身比较简单,主要需要思考如何用线段树维护每条链. 当x, ...

  6. Ubuntu16.04配置Android5.0编译环境

    1.安装jdk7 Ubuntu16.04的安装源已经默认没有openjdk7了,所以要自己手动添加仓库,如下: $ sudo add-apt-repository ppa:openjdk-r/ppa ...

  7. 最好的PHP博客系统

    1.Wordpress http://www.wordpress.org/ B2基础上开发而来,这是国内用户比较喜欢而且用户较多的一个php博客程序,缘由是因为Wordpress提供大量插件和模板,让 ...

  8. QT 开发资料

    http://pan.baidu.com/s/1bntYkpx 密码: fgsa

  9. Lua中调用C函数(lua-5.2.3)

    Lua能够调用C函数的能力将极大的提高Lua的可扩展性和可用性. 对于有些和操作系统相关的功能,或者是对效率要求较高的模块,我们全然能够通过C函数来实现,之后再通过Lua调用指定的C函数. 对于那些可 ...

  10. SSH深度历险(四) Maven初步学�

    这几天接触这个词,非常多遍了,仅仅是浅显的体会到它在GXPT中的优点,功能之强大,又通过网络查询了资料进一步的认识学习了,和大家分享. Maven是基于项目对象模型(POM),能够通过一小段描写叙述信 ...