Home > Net >  Get first word from Wordpress page title
Get first word from Wordpress page title

Time:01-18

Edit

Is this code ok?
It works on a dummy website, but I'm afraid to not break a live website.
If used for links, is there a problem if links have capitalization?

function shortcode_page_title( ){
return get_the_title();
}
add_shortcode( 'page_title', 'shortcode_page_title',  );

function shortcode_title_first_word( ){
$title = get_the_title();
$title_words = explode(' ', $title);
return $title_words[0];
}

add_shortcode( 'title_first_word', 'shortcode_title_first_word', );

Thanks, @ADyson, for the resources.

Initial post

I can't code :( I'm using Sepster's solution to get the page title.

function shortcode_page_title( ){
    return get_the_title();
}
add_shortcode( 'page_title', 'shortcode_page_title',  );

How can I insert another step and select only the first word of the title?

I've seen the explode function and array selection, but I don't know how to implement them.

Thank you!

CodePudding user response:

If you still want to use the shortcode as the way to insert the title wherever you need it, then all you need is to combine the 2 functions above and insert it on the bottom of your functions.php file (preferably on a child theme).

 function first_word_from_title( ){
      $title = get_the_title(); // Retrieves the title
      $title_words = explode(' ', $title); // Transforms the title into an array composed of each separate word
      return $title_words[0]; // Returns the first element of the array
    }
  add_shortcode( 'page_title', 'first_word_from_title');

I don't think you need to worry about the above code causing a crash as it is only run when you insert the shortcode and not on every page load.

You can always test it first on a draft post and see if you get an error.

  •  Tags:  
  • Related