I have created a shortcode [get_custom_posts] to be inserted in a page (the default page post type from WordPress) to get posts which are from a custom post type.

In each post from that custom post type the user can insert a shortcode [get_attached_images] to get attachments (images) assigned to that specific post. The way this shortcode to get images works is by using the global $post variable. It then basically gets all the images attached to that post, nothing too extraordiary.

The problem is with the shortcode to get these posts ( [get_custom_posts] ). It does not return the expected content which is to display those custom posts along with their image attachments (attachments which are fetched by using the [get_attached_images]). Instead it displays the custom posts with the attachments that belong to the page (!) not to the respective posts.

What happens is that the global $post variable used in the [get_attached_images] shortcode is somehow the $post variable of the page that outputs all those posts.

The way the [get_custom_posts] shortcode works is by getting all the posts that belong to the custom post type that I want to get posts from. It then uses the the_content filter to "execute" the [get_attached_images] shortcodes from those custom posts. This way the posts can be displayed (in theory at least) along with their attachments. But in practice it doesn't work.

Does anybody has any idea what is going on? Why is the $post variable of the page passed to the [get_attached_images] shortcode instead of the $post variable of each custom post? And how can this be prevented?

  • 2
    Maybe, if we see your code... – Bainternet Aug 5 '12 at 10:02
  • Whether the $post variable is updated depends on how you are querying the custom post types. Could you post some code of how the [get_custom_posts] works? – Stephen Harris Aug 12 '12 at 19:12

I had a similar problem, global $post; was returning NULL. But it works fine if I don't use short codes.

So I found a function for getting the post id from the URI, you might be able to extend it to get more information if you need it.

Try this:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.