• HI
    I created my own theme. I show posts with thumnails of images that are attached to the posts. I use this function:

    function getTheFirstImage() {
        $files =       get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
    	if($files) :
            $keys = array_reverse(array_keys($files));
    	$j=0; $num = $keys[$j];
            $image=wp_get_attachment_image($num, 'large', false);
            $imagepieces = explode('"', $image);
            $imagepath = $imagepieces[1];
            $thumb=wp_get_attachment_thumb_url($num);
            echo "<img src='$thumb' class='thumbnail' />";
        endif;
    }

    It works corectly. But when I create new post and I use image that is already used in other post, then it doesnt show thumbnail. I checked that in this case function get_children returns null although I have correct post parent ID in this function.
    I have no idea how fix this problem.

Viewing 3 replies - 1 through 3 (of 3 total)
  • One of the oddities of WP’s attachment system is that each attachment can only have one post_parent, and that value is set when the image is first attached to a post and doesn’t change (unless you call update_metadata()).

    As a result, you can’t actually do what you’re trying to do, if the attached images were already uploaded and attached to another post. I haven’t tested this, but it should work if you upload another copy of the same image and attach it to the second post. That’s a horrible waste of resources, though. Another thing to try would be to get the post content ($post_content = $post->post_content) and search that for the string wp-image-xxxx. The “xxxx” is the ID of the image, which you could then pass to wp_get_attachment_image() or wp_get_attachment_url().

    Thread Starter kyryfyrymyndy

    (@kyryfyrymyndy)

    I used your last idea and it works. Thanks!
    But I have a feeling that it’s not correct way to show thumbnails in wordpress news ??

    Can you clarify what you’re trying to achieve, then? Your code works fine in pretty much all situations, except for this corner case, and I haven’t found another way of getting the IDs of attached media in this case where get_children() won’t work. If someone knows another workaround, that’d be great.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Function get_children() returns null’ is closed to new replies.