Trim first 2 words of the exceprt

I am currently pulling in the post excerpt however there are 2 words at the start of it that I would rather not have in this particular place as there is a title already.

I have used wp_trim previously but this only takes words off the end, is there a way to do this for the first 2 words. These words are always the same if that helps? I’m not sure if I have get get the excerpt as a string then replace with nothing or if wp_trim can do this.

<?php $tagname = get_the_title (); ?>
<?php

$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>1, 
    'orderby' => 'rand',
    'tag' => sluggify( $tagname));
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
    while (have_posts()) : the_post();
        echo '<h2 class="entry-title">';
        echo 'CASE STUDY';
        echo '</h2>';
        echo '<span>';
        the_post_thumbnail();
        echo '</span>';
        echo '<strong>';
        the_title();
        echo '</strong>';
        echo '<p>';
        the_excerpt();
        echo '</p>';
    endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();?>

Amended code from suggested answer from @RRikesh:

<?php $tagname = get_the_title (); ?>
<?php

$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>1, 
    'orderby' => 'rand',
    'tag' => sluggify( $tagname));
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
    while (have_posts()) : the_post();
    $str = get_the_excerpt();

        echo '<h2 class="entry-title">';
        echo 'CASE STUDY';
        echo '</h2>';
        echo '<span>';
        the_post_thumbnail();
        echo '</span>';
        echo '<strong>';
        the_title();
        echo '</strong>';
        echo '<p>';
        echo ltrim($str, "INSTRUCTION SYNOPSIS"); // Output: This is another Hello World.
        echo '</p>';
    endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();?>

3 Answers
3

A more reliable way would be to filter the excerpt and to explode the string into an array, remove the first two key/value pairs from the array and then return your string

add_filter( 'wp_trim_excerpt', function ( $text )
{
    // Make sure we have a text
    if ( !$text )
        return $text;

    $text               = ltrim( $text );
    $text_as_array      = explode( ' ', $text );

    // Make sure we have at least X amount of words as an array
    if ( 10 > count( $text_as_array ) )
        return $text;

    $text_array_to_keep = array_slice( $text_as_array, 2 );
    $text_as_string     = implode( ' ', $text_array_to_keep );
    $text               = $text_as_string;

    return $text;
}):

Leave a Comment