user3476168
user3476168

Reputation: 280

Return words before specific character from wordpress the_title();

I am trying to get words before specific character in WordPress the_title().

My WordPress post titles always looks something like this "How To - Make Things Happen".

How can I return all the words before the "-" in PHP, for example get "How To" from "How To - Make Things"

I am trying to use all words before "-" and a keyword within the post page.

I have seen a similar solution here: Get first word in string php the_title WordPress but it doesn't fit perfectly as I am trying to get all words before a specific character

Upvotes: 0

Views: 273

Answers (2)

Prashant Devs
Prashant Devs

Reputation: 65

Just remove the index from above answer by Narek. Try this:

$title = current(explode('-', 'How To - Make Things Happen'));

echo $title;

Upvotes: 1

Narek Zakarian
Narek Zakarian

Reputation: 215

You can do it this way:

$title = get_the_title();
$substring = substr($title, 0, strpos($string, '-'));

or

$title = current(explode('-', get_the_title()));

echo $title['0'];

Upvotes: 2

Related Questions