最明显的方法是迭代生成的ID数组,为每个ID获取\\u post,并针对post_status == \'publish\'
. 但我想知道这是否会导致记忆问题get_post
是否会在默认情况下尝试缓存每个结果?如果没有自定义SQL联接,是否可以传递任何意外的参数get_objects_in_term()
或者,是否有其他我没有利用的税收职能,我应该这样做?
使用Get_Objects_in_Term()只包含已发布的帖子的优雅方式?
2 个回复
最合适的回答,由SO网友:hacksy 整理而成
您可以添加\'post_status\' => \'publish\'
在仅检索状态为publish的对象的查询中,这将适用于get_posts
, query_posts
或$wp_query
还包括您可以使用的自定义分类法tax_query
在参数列表中
SO网友:chrisguitarguy
没有可以传递的参数。唯一使用的参数是order
. 以下是函数的来源:
<?php
function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
global $wpdb;
if ( ! is_array( $term_ids ) )
$term_ids = array( $term_ids );
if ( ! is_array( $taxonomies ) )
$taxonomies = array( $taxonomies );
foreach ( (array) $taxonomies as $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) )
return new WP_Error( \'invalid_taxonomy\', __( \'Invalid taxonomy\' ) );
}
$defaults = array( \'order\' => \'ASC\' );
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
$order = ( \'desc\' == strtolower( $order ) ) ? \'DESC\' : \'ASC\';
$term_ids = array_map(\'intval\', $term_ids );
$taxonomies = "\'" . implode( "\', \'", $taxonomies ) . "\'";
$term_ids = "\'" . implode( "\', \'", $term_ids ) . "\'";
$object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order");
if ( ! $object_ids )
return array();
return $object_ids;
}
但是,您可以复制该函数并添加一个附加子句以使用post状态。<?php
function wpse29749_get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
global $wpdb;
if ( ! is_array( $term_ids ) )
$term_ids = array( $term_ids );
if ( ! is_array( $taxonomies ) )
$taxonomies = array( $taxonomies );
foreach ( (array) $taxonomies as $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) )
return new WP_Error( \'invalid_taxonomy\', __( \'Invalid taxonomy\' ) );
}
$defaults = array( \'post_status\' => \'publish\', \'order\' => \'ASC\' );
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
$order = ( \'desc\' == strtolower( $order ) ) ? \'DESC\' : \'ASC\';
$term_ids = array_map(\'intval\', $term_ids );
$taxonomies = "\'" . implode( "\', \'", $taxonomies ) . "\'";
$term_ids = "\'" . implode( "\', \'", $term_ids ) . "\'";
$object_ids = $wpdb->get_col( $wpdb->prepare(
"SELECT ID from $wpdb->posts WHERE ID IN (
SELECT tr.object_id FROM $wpdb->term_relationships
AS tr INNER JOIN $wpdb->term_taxonomy AS tt
ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE tt.taxonomy IN ($taxonomies)
AND tt.term_id IN ($term_ids)
) AND post_status = %s
ORDER BY ID $order", $post_status ) );
if ( ! $object_ids )
return array();
return $object_ids;
}
没什么不同。中的附加元素$defaults
以及对SQL的一些修改。结束