• Resolved huntz

    (@huntz)


    Hello,

    I have a string and I want to see if I have any matching post titles. I basically want to loop through all my post titles and compare it to this string and if there is a result i want to do something.

    Anyone got any ideas? Any helps hints would be appreciated.

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter huntz

    (@huntz)

    If I had an array of the titles I could use php in_array to see if it is there but it’s building the array of post titles I’m struggling with.

    <?php
    $all_posts = get_posts('numberposts=-1&cat=0');
    $all_titles = array();
    foreach( $all_posts as $all_post ) {
    $all_titles[] = $all_post->post_title;
    }
    ?>

    Of course, if you’re actually just trying to figure out whether or not you have any posts with a specific title, you could do something like this, instead:

    /**
     * Retrieve a WordPress post object by its title
     * @param string $title the title to search for
     * @param string $post_type the type of post to search for
     * @return bool|post the WordPress post object retrieved, false if not found
     */
    function get_post_by_title( $title, $post_type=NULL ) {
    	if( empty( $title ) )
    		return false;
    	global $wpdb;
    	$post = ( is_null( $post_type ) ) ?
    		$wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title=%s", $title ) ) :
    		$wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title=%s AND post_type=%s", $title, $post_type ) ) :
    
    	if( $post )
    		return get_post( $post );
    	else
    		return false;
    }
    Thread Starter huntz

    (@huntz)

    Thanks all,

    alchymyth this worked, cheers.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to loop through post titles.’ is closed to new replies.