I'm having some trouble creating a shortcode that queries some posts. This is the basics of my code:

function shortcode_equipment($atts, $content = null) {

   $equipment = get_page_by_title($content, OBJECT, 'equipment');

   $loop = new WP_Query( array(
   'posts_per_page'    => 1,
   'post_type'         => 'equipment',
   'page_id'         => $equipment->ID
    ) );

   while( $loop->have_posts() ) { $loop->the_post();

   *misc code*

     return $string;


add_shortcode( 'item', 'shortcode_equipment' );

Now, ordinarily, this works fine for 99% of my posts. It queries the post by what's written inside the [item]title goes here[/item] shortcode and then displays a custom tooltip/hover effect accordingly.

However, if my post title has an apostrophe in it (ex: Mal's Post), then it's breaking and just querying whatever the last post in that custom post type is.

So, how do I get this to work with apostrophes in the post titles?

2 Answers 2


Title Hello world!@#$%^*(),.;:\ will work but any title you enter containing ' " < > & characters won't work because in $content variable you have escaped HTML entities so Mal's Post becomes Mal&#8217;s Post.

To bypass it you can use sanitize_title function along with get_page_by_path.

function shortcode_equipment($atts, $content = null) {
   $path = sanitize_title($content);

   $equipment = get_page_by_path( $path, OBJECT, 'equipment');

Rest of code works as before.


There's most likely an escaping issue happening there. Try to escape the title before passing it to your shortcode, by using sanitize_title_for_query(), sanitize_title() or even esc_html():

$content   = sanitize_title_for_query( $content );
$equipment = get_page_by_title( $content, OBJECT, 'equipment' );

More information about escaping data can be found here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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