Forums

How to check if a post exists by title (3 posts)

  1. Oren Yomtov
    Member
    Posted 3 years ago #

    How can I check if a post exists with a certain title?
    e.g.:if (!wp_post_exists('Hello World!')) wp_create_post(.....);

    Is there any function like wp_post_exists? or maybe a way to search the posts by title. or put all post names in an array.

    Thanks in advance, Oren.

  2. stvwlf
    Member
    Posted 3 years ago #

    Here's an article that has code to do that for Pages. Pages are very similar to posts. This should give you a starting place to approach from.
    http://www.tammyhartdesigns.com/tutorials/wordpress-how-to-determine-if-a-certain-page-exists/

  3. gegenalles
    Member
    Posted 3 years ago #

    Hi, I wanted to create a function like that.

    It should be very easy, but in my case, I have to deal with a lot (>2000) posts. For some reason, get_posts() doesn't work, because the data amount created by this is too big.

    I had to find a way to query just the titles, not all the other data which is not needed, eg the content, the custom fields, etc.

    This is what I've figured out and works for me:

    function my_post_exists($suchtitel){
        $suchtitel=strtoupper($suchtitel);
       	$suchtitel = trim($suchtitel, ' ');
    	global $wpdb;
    
        $meinetitel = $wpdb->get_col("SELECT post_title
    	FROM $wpdb->posts
    	WHERE post_status = 'publish'
    	ORDER BY post_title");
      	foreach($meinetitel as $meintitel){
                    $meintitel=strtoupper($meintitel);
      		if($suchtitel==$meintitel){
      			return true;
      		}
      	}
    }

    You could place this function in your "functions.php" and call it in your template where you need it.

    The function is not case sensitive and cuts spaces from the end and the beginning of the search-title.

    If someone could tell me if the query is safe for sql-injections, please tell me, because i'm not very experienced in that.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.