通过自定义字段获取图像

时间:2014-11-06 14:37:16

标签: sql wordpress

我尝试显示具有the types plugin设置为true的特定自定义字段的所有图片。它也可以通过post_contentpost_excerpt来过滤它们,但到目前为止我的尝试都没有。

<?
  $args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'post_content' => 'foo',
    'numberposts' => -1
  );
?>

<? print_r(get_posts($args)); ?>

这个获取所有图片尽管只有一个具有post_content foo。我尝试使用WP_Query也失败了。

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

WP_Query方法:

$args = array(
    'post_type'  => 'attachment',
    'post_status' => 'inherit',
    'meta_query' => array(
        array(
            'key'     => 'color',
            'value'   => 'blue',        
            'compare' => 'LIKE',
        ),
    ),
);
$query = new WP_Query( $args );

我认为您使用WP_Query失败的原因是由于以下情况。

Codex声明:默认的WP_Query设置'post_status'=&gt;'publish',但附件默认为'post_status'=&gt;'inherit',因此您需要将post_status明确设置为'inherit'或“任何”也是。

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

get_posts方法:

$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'meta_key' => 'custom-field',
    'meta_value' => 'custom value',
    'numberposts' => -1
);

print_r(get_posts($args));  

使用此方法的唯一缺点是meta_value需要与自定义字段中输入的内容完全匹配。如果您仍想使用get_posts,请使用上面WP_Query示例中显示的meta_query

相关问题