[转]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

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

来源: <http://www.advancedcustomfields.com/resources/how-to-query-posts-filtered-by-custom-field-values/>

http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

来自为知笔记(Wiz)

时间: 2024-10-09 20:27:32

[转]How to query posts filtered by custom field values的相关文章

wordpress中强大的调用文章函数query posts 用法

query posts是一个非常好用的调用文章函数,可以做到同页面内显示多种特定范围的文章,例如可以调用某分类.标签.日期及作者等不同范围的文章列表.这些文 章列表可以极大的丰富 wordpress 页面的内容,并有利于SEO.二手科学家整理了下query posts调用文章的函数,下面分别说明下. 首先是query posts 的一般写法.通常是如先定义查询再加入文章回圈程式码后再重置查询. <?php  //定义要显示的文章范围查询  query_posts();  //文章回圈  if (

redmine computed custom field formula tips

项目中要用到Computed custom field插件,公式不知道怎么写,查了些资料,记录在这里. 1.http://apidock.com/ruby/Time/strftime 查看ruby的字符串格式,用于改写Date/time format只显示日期,不显示时间. 2.https://github.com/annikoff/redmine_plugin_computed_custom_field/issues/34 看到formula里可以写复杂代码,比如增加变量.指定返回值等. 3.

JIRA Plugin Development——Configurable Custom Field Plugin

关于JIRA Plugin开发的中文资料相当少,这可能还是由于JIRA Plugin开发在国内比较小众的原因吧,下面介绍下自己的一个JIRA Plugin开发的详细过程. 业务需求 创建JIRA ISSUE时能提供一个字段,字段内容是类似于订单号或手机号这种样式的数据,并且显示出来是一个链接,点击后可跳转到订单详情页或手机号所对应的客户的整个订单页,供用户查看和此任务工单关联的订单数据: 例如: 订单号为123456: 订单详情URL为:http://192.168.11.211?order=1

magento如何获取产品属性值 How to Obtain Custom Attribute Values in Magento

<div class="product-sku">SKU:<?php echo $_product->getSku();?>    Brand:<?php $attributes = $_product->getAttributes(); echo  $attributes['brand']->getFrontend()->getValue($_product); ?>    UNIT:<?php echo $_prod

GHOST CMS - Custom Routes

Custom Routes Template routes allow you to map individual URLs to specific template files within a Ghost theme. For example: make /custom/ load custom.hbs Using template routes is very minimal. There's no default data associated with them, so there i

Query runs slow via .NET

Slow in the Application, Fast in SSMS?Understanding Performance Mysteries An SQL text by Erland Sommarskog, SQL Server MVP. Last revision: 2013-08-30.This article is also available in Russian, translated by Dima Piliugin. Introduction When I read var

Query DSL for elasticsearch Query

Query DSL Query DSL (资料来自: http://www.elasticsearch.cn/guide/reference/query-dsl/) http://elasticsearch.qiniudn.com/ --简介-- elasticsearch 提供基于JSON的完整的Query DSL查询表达式(DSL即领域专用语言). 一般来说, 普通的查询如 term 或者 prefix. 另外还有混合查询如 bool 等. 另外查询表达式(Queries)还能够关联特定的过

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 driver. 连接字符串:Server=127.0.0.1;Database=testDB;Uid=root;Pwd=jnex;<system.data> <DbProviderFactories> <add name="MySQL Data Provider" i

数据库之Query Builder

Yii的查询构造器提供了一个用面向对象的方法来构造SQL语句.他让开发人员可以用类的方法,属性来作为SQL语句的一部分.然后把不同部分组装到一个正确的SQL语句中,调用DAO的方法来执行.下面的例子演示如何用QB来构造SQL语句 $user = Yii::app()->db->createCommand() ->select('id, username, profile') ->from('tbl_user u') ->join('tbl_profile p', 'u.id=