I am learning WP and want to display only the first two words of a post title to the user. For the end user only the first two words of the Post title (H1 class) should be shown but source should have the full title for SEO. For example, if Post title is "Beef Burger - grilled, pan, mustard etc" and I only want to display "Beef Burger" to the end user on all pages - Blog, Archive, custom page with query blocks.
Many threads have offered some solution but they are from years ago. Is there any solution in 2024 as technology might have advanced? I thought this could be done in css but looks like it can't be done. I used ChatGPT to generate some code (code listed below) and it did and instruction was to paste that code in the 'functions.php" file but as I have learned that might get cleared up when the theme gets updated. After much digging around I came across 'Code Snippets'. No idea how to paste the code ChatGPT gave in Code Snippets and maek it work. And read somewhere that the WP Twenty Twenty Four theme doesn't use the functions.php file.
Using the Twenty Twenty Four theme.
Thanks,
Prad
<?php
while ( have_posts() ) :
the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php
// Fetch the post title
$post_title = get_the_title();
// Split the title into an array of words
$words = explode(' ', $post_title);
// Get the first two words
$first_two_words = implode(' ', array_slice($words, 0, 2));
// Display the first two words
echo '<h1 class="entry-title short-title">' . esc_html($first_two_words) . '</h1>';
// Display the full title, hidden
echo '<h1 class="entry-title full-title" style="display: none;">' . esc_html($post_title) . '</h1>';
?>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php yourtheme_entry_footer(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-<?php the_ID(); ?> -->
<?php
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</main><!-- #main -->
```
Edit: Thanks for the comments indicating that this method is not SEO friendly. I did go through the discussion here - https://webmasters.stackexchange.com/questions/1377/how-bad-is-it-to-use-display-none-in-css
My use case is not to spam. I just want to limit the post title when displayed in a grid, so it looks cleaner. The post will still have the title. I found an example of something similar I want to achieve - IMDB page https://www.imdb.com/name/nm0881631/ There are different sections for Personal details where they are displaying the text but also adding additional and relevant text for SEO.
How can I achieve this on 2024 block theme?
functions.php
as that would put a post loop at the top of every request, even admin and AJAX requests