如何从附件 wordpress 中获取 post id

How to get post id from attachment wordpress

我正在使用下面的代码来获取分配给我的自定义post类型的所有附件..但现在我想获取post 循环中的 id..我该怎么做?

$query = new WP_Query(  
          array(  
            'post_type' => 'portfolio', // adjust your custom post type name here  
            'posts_per_page' => -1,  
            'fields' => 'ids'  
          )  
        );  
        $image_query = new WP_Query(  
          array(  
            'post_type' => 'attachment',  
            'post_status' => 'inherit',  
            'post_mime_type' => 'image',  
            'posts_per_page' => -1,  
            'post_parent__in' => $query->posts,  
            'order' => 'DESC'  
          )  
        );  


        if( $image_query->have_posts() ){  
          while( $image_query->have_posts() ) {  
              $image_query->the_post();  
              $imgurl = wp_get_attachment_url( get_the_ID() );  

             if(!empty($output)) $output = 'Sorry, no attachments found.';  
              $output .= '<a href="'.$imgurl.'"><img src="'.$imgurl.'"></a>';  

              echo $output;  
          }  

谢谢!

根据您在循环中查找的 ID,您可以执行以下操作

  • $post-ID -> Returns 正在显示附件 post 中的 post ID

  • $post->post_parent -> Returns 当前附件 post 父级 post ID