使用WP_Query获取附件返回空集


Wordpress: Using WP_Query to get attachment returns empty set

我想获得媒体库中由自定义字段过滤的第一个音频文件,但它总是返回一组空的帖子。我知道我必须通过'post_status' => 'inherit''post_type' => 'attachment',但这不会改变任何事情。

<?php
    // Arguments
    $args = array(
        'post_type' => 'attachment', 
        'post_status' => 'inherit', 
        'post_mime_type' => 'audio', 
        'meta_key' => 'my_meta_key', 
        'meta_value' => 'my_meta_value', 
        'posts_per_page' => 1 );
    // Create the query
    $audio_files = new WP_Query( $args );
    // Output
    var_dump( $audio_files );    // the number of found posts is always 0
?>

所以我试着把它最小化,让所有的元键的东西,并搜索任何附件(如这里提到的)

<?php
    // Arguments
    $args = array(
        'post_type' => 'attachment', 
        'post_status' => 'inherit' );   // or "any", but without effect
    // Create the query
    $any_files = new WP_Query( $args );
    // Output
    var_dump( $any_files );    // same: the number of found posts is always 0
?>

所以我尝试了一种老式的方式,通过自定义sql语句:

<?php
    // Get row by custom SQL-statement
    $wpdb->get_row( 'SELECT * FROM ' . $wpdb->prefix . 'posts p, ' . $wpdb->prefix .  'postmeta m WHERE p.post_mime_type LIKE "audio/%" AND p.ID = m.post_ID AND m.meta_key = "my_meta_key" AND m.meta_value = "my_meta_value" ORDER BY p.post_date DESC' );
?>

和tataaaa !我得到我的第一个音频文件。

我知道有类似的问题:

  • 坏了?WP_Query和"附件"作为post类型
  • WP_Query对附件和自定义meta_query不正常工作

但是他们都没有帮助我,即使他们在处理几乎相同的话题。

我在这里错过了什么?我想用WP_Query

你应该使用offset,order和order当你使用posts_per_page它肯定会工作。这是修改后的代码

如果posts_per_page是-1,那么它会列出所有的post,所以在这种情况下offset会被忽略,但在其他情况下你应该使用。

 $args = array(
        'post_type' => 'attachment', 
        'post_status' => 'inherit', 
         'offset'         => $offset,
        'post_mime_type' => 'audio', 
        'meta_key' => 'my_meta_key', 
         'orderby' =>'ID',
        'order'  => 'ASC',
        'meta_value' => 'my_meta_value', 
        'posts_per_page' => 1 );