You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用get_posts无法返回附件的问题求助(附自定义函数代码)

Troubleshooting & Fixing Your Attachment Retrieval Issue

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.

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 numberposts typo to ensure the query fetches 1 attachment
  • Added an optional $post_id parameter for better flexibility and reliability
  • Added post_mime_type to only target image attachments (matches the featured image use case)
  • Replaced $attachments[0]->guid with wp_get_attachment_url() for a stable, valid URL
  • Added validation for $post_id to avoid errors in edge cases
  • Optional: Added orderby/order to respect the attachment order set in the post editor

内容的提问来源于stack exchange,提问作者Marcos Di Paolo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:23:16