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 badges1 Answer
Reset to default 0I'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
版权声明:本文标题:php - WP_Query Check if post has one or more attached medias 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741301152a2371096.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论