• Resolved ellimstom

    (@ellimstom)


    Hi All,

    Is there a way to add a meta queryvar to be able on post url ? Example:
    https://www.site.com/?metakey=123456 that redirects to related post thanks to a function that retrieve post id by meta value. In this example, metakey is unique.

    Thanks,

    Bernard

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Use the “query_vars” filter to add your query var to the list of recognized vars. You can then use the “pre_get_posts” action to set the “meta_key” and “meta_value_num” query vars to fetch the correct post. “metakey” will be part of the query’s vars, but WP doesn’t know what to do with it on its own. You need to translate it into something WP understands.

    Note that example.com/?meta_key=metakey&meta_value_num=123456 amounts to the same thing but doesn’t require any filter or action hooks.

    Thread Starter ellimstom

    (@ellimstom)

    Hi @bcworkz ,
    Thank you for the info. I now can get the post, but template is an archive. How can I set the query to display single post page ?
    Best regards

    Moderator bcworkz

    (@bcworkz)

    I guess WP doesn’t know the passed value is unique per post and assumes there could be multiple matches. In the same “pre_get_posts” callback, assign true to the WP_Query property “is_single”. And assign false to “is_archive”. N.B: these are object properties, not a query vars.

    I’m pretty sure that’ll affect the template used. On the off chance it doesn’t, we can always override the template used through “template_redirect” or “template_include” hooks. Shouldn’t come to that though.

    Thread Starter ellimstom

    (@ellimstom)

    Thanks a lot, it worked. I also had to set “is_home” to false which makes sense.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Add meta key queryvar to access post’ is closed to new replies.