admin管理员组

文章数量:1278787

Is there any way to check if post has any attached medias via new WP_Query($args)?

$args = [
   'post_type' => 'post',
   'post_status' => 'publish',
   'posts_per_page' => 10,
   'paged' => 1,
   *****************************************
    → [args for checking attached medias] ←
   *****************************************
];
$posts = new WP_Query($args);

I want to retrieve posts that have media attachments...

Is there any way to check if post has any attached medias via new WP_Query($args)?

$args = [
   'post_type' => 'post',
   'post_status' => 'publish',
   'posts_per_page' => 10,
   'paged' => 1,
   *****************************************
    → [args for checking attached medias] ←
   *****************************************
];
$posts = new WP_Query($args);

I want to retrieve posts that have media attachments...

Share Improve this question asked Sep 25, 2021 at 11:21 Bahman WorldBahman World 135 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

I'm afraid that it's not possible by default. Using WP_Query you can only check if posts have a featured image set.

What you can do instead:

Create a hook that fires during post save (e.g. "post_updated"), check if this post has any attachments - save this information in post_meta. Use meta_query with WP_Query to get the posts.

To check if a post has attachments you will have to scan through post_content and detect any tags or maybe comments left by gutenberg blocks? (e.g. "<!-- /wp:gallery -->" or "<!-- /wp:media-text -->")

Bear in mind that this is not a bulletproof solution.

Save attachment meta data

add_action( 'post_updated', 'has_post_attachments', 12, 3 );

function has_post_attachments( $post_ID, $post_after, $post_before ) {
    // This is not ultimate list of all possible test strings, adjust it for your env
    $test_strings = array(
        '<!-- /wp:image -->',
        '<!-- /wp:gallery -->',
        '<!-- /wp:media-text -->',
    );

    update_post_meta( $post_ID, '_my_custom_key', 0 );
    foreach ( $test_strings as $str ) {
        if ( false !== strpos( $post_after->post_content, $str ) ) {
            update_post_meta( $post_ID, '_my_custom_key', 1 );
            return;
        }
    }

    return;
}

Query posts with attachments

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 10,
    'paged' => 1,
    'meta_query' => array(
        array(
            'key'     => '_my_custom_key',
            'value'   => '1',
            'compare' => '='
        )
    )
);
$posts = new WP_Query($args);

本文标签: phpWPQuery Check if post has one or more attached medias