Finding post content that begins with a specific character

If I want to find all posts where the very first character(s) of the post text / content (ie not the title) are

"<" 

or

"<a"

How would I do so?

I tried these solutions:

https://stackoverflow.com/questions/2246263/fetch-posts-starting-with-alphabet-x

https://stackoverflow.com/questions/39205088/querying-post-id-from-posts-starting-with-specific-character

but they did not work

1 Answer
1

Something like this will probably work:

$results = array();

$allPosts = get_posts('post_type=post&numberposts=-1');
foreach ($allPosts as $aPost) {
    if ( substr($aPost->post_content, 0, 1) == '<' || substr($aPost->post_content, 0, 2) == '<a' )
        $results[] = $aPost->ID;
}

echo "<pre>".print_r($results,true)."</pre>";

UPDATE: but you should revisit the MySQL approach in the links you provided. This php method is somewhat wasteful as it gets everything, instead of only whats needed.

Leave a Comment