7

I am trying to get a post ID by it's post content. I have a custom post type of 'membership' which has post_content that looks like this...

{"member_id":33}

I am trying to get the ID of this post by searching for {"member_id":33}

Am I best off doing this using an SQL statement or is there a better way to do it using WordPress functions?

9

WordPress has a handy function called post_exists() which allows you to find an existing post by its title, content, and/or date. It returns the post ID on success or 0 otherwise.

In your case, you can use $post_id = post_exists( '', '{"member_id":33}' ) to find the post you're looking for.

Note: That function doesn't check the post type so you'd need to do that separately or roll your own function if it's necessary. I doubt it though that you have other posts with the same content :-)

  • Thank you so much! I have been scouring the docs looking for a suitiable function and hadn't found anything, this looks perfect – fightstarr20 Jan 18 '18 at 11:10
  • 3
    Nice solution. ps: there's a ticket for a post type support for post_exist() here #37406 – birgire Jan 18 '18 at 11:17
  • I am trying to use this within my functions.php file but I am getting the error - Call to undefined function post_exists() – fightstarr20 Jan 18 '18 at 11:26
  • 2
    @fightstarr20 this was answered here recently. – birgire Jan 18 '18 at 11:31
  • 1
    This file only contains some harmless functions and doesn't execute any code besides that. It's totally acceptable to include it like this and there are no security concerns associated with that. – swissspidy Jan 18 '18 at 11:36

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.