使用get_posts无法返回附件的问题求助(附自定义函数代码)
Let's walk through why your get_posts() call isn't grabbing attachments, then fix the code properly:
1. Critical Typo in Your get_posts() Parameters
First off, you've got a tiny but impactful typo: numberpost should be numberposts (plural). That's a super common mistake that's almost certainly making the query return nothing right off the bat.
2. Add MIME Type Filtering (Optional But Recommended)
Right now your query pulls all attachments, including non-images like PDFs or documents. Since this is for a featured image fallback, adding a post_mime_type filter will make the query more precise and avoid unexpected results.
3. Avoid Over-Reliance on global $post
Using global $post can be fragile if the function runs outside the loop or in a context where $post isn't set. It's better to explicitly pass a post ID to the function, or at least validate that $post exists before using it.
4. Don't Use guid for Attachment URLs
WordPress's guid field isn't meant to be used as a reliable URL (it can change depending on your permalink settings). Instead, use wp_get_attachment_url() which gives you the correct, stable URL for the attachment.
Here's the Corrected Full Code
function just_in_case_featured($size, $post_id = null) { // Use passed post ID, or fall back to global post if available $post_id = $post_id ?: (isset($GLOBALS['post']) ? $GLOBALS['post']->ID : 0); if (!$post_id) { return false; // No valid post ID, exit early to avoid errors } // First try the featured image $featured_image_url = get_the_post_thumbnail_url($post_id, $size); if ($featured_image_url) { return $featured_image_url; } // Fallback: Get first image attachment $attachments = get_posts(array( 'post_status' => 'publish', 'post_type' => 'attachment', 'numberposts' => 1, // Fixed the plural typo here 'post_parent' => $post_id, 'post_mime_type' => 'image', // Only fetch image attachments 'orderby' => 'menu_order', // Optional: Respect the attachment order set in the post editor 'order' => 'ASC' )); if ($attachments) { // Use the proper WordPress function to get a stable attachment URL return wp_get_attachment_url($attachments[0]->ID); } // If no attachments found, return false or a default image URL of your choice return false; }
Key Changes Explained:
- Fixed the
numberpoststypo to ensure the query fetches 1 attachment - Added an optional
$post_idparameter for better flexibility and reliability - Added
post_mime_typeto only target image attachments (matches the featured image use case) - Replaced
$attachments[0]->guidwithwp_get_attachment_url()for a stable, valid URL - Added validation for
$post_idto avoid errors in edge cases - Optional: Added
orderby/orderto respect the attachment order set in the post editor
内容的提问来源于stack exchange,提问作者Marcos Di Paolo

