WordPress quickie: Gallery is being displayed only to logged in users

Today, I’m going to tell you about one problem, which brought me sleepless night and could be solved with a few lines of code, as usual.

One client of mine has got a picture gallery on his website, generated by shortcode gallery. Accidentaly we found out that it is not being displayed to normal visitors, but when logged in as admin or editor, it is visible.

Firstly I thought that it “fucked up” one of the plugins, but after disabling all of them it was still the same. Followed a lot of debuging to the guts of WordPress – gallery shortcode itself, WP_Query class, until I found a rather interesting behaviour.

Gallery shortcode takes its paramaters and regarding them it takes all posts with attachment type and inherit status by calling get_posts, which wraps WP_Query. This class provides a layer beween post searching and SQL databse. To my surprise somewhere deep in the guts of itself, it changed its post_status from inherit to publish, which is makes no sense for attachment post_type and therefore the query returns no results. In case there is a user logged in is post_status query different.

Of course, this does some plugin or theme itself, but search for some function hooked to pre_get_posts returned zero results.

So I made a small hack in functions.php, which solved this situation rather smartly with respect to hurry I was in. Behold!

Problem solved. It is up to you if it is clean solution or not.

Leave a Reply

Your email address will not be published. Required fields are marked *