0

I have a strange issue. I am including dashicons on the front-end through

add_action( 'wp_enqueue_scripts', 'load_dashicons_front_end' );
   function load_dashicons_front_end() {
   wp_enqueue_style( 'dashicons' );
}

Then I enter dashicon HTML in the Navigation Label of my menu items, for example:

<span class="dashicons dashicons-admin-home"></span> Home

I also include some code on the blog archive that truncates the post titles to the first 7 words:

add_filter( 'the_title', 'wpse_75691_trim_words' );

function wpse_75691_trim_words( $title )
{
   // limit to 7 words
   return wp_trim_words( $title, 7, '...' );
}

but dashicons disappear when the trim function runs. It works for the whole site apart from the blog page where I have the truncate code. I believe I have a similar problem with the OP on this post.

But I am not sure how to proceed. I am already running the function on the blog archive so the problem only exists there.

2

Your problem is that your filter is trimming all titles to 7 "words". This includes blog posts, pages, menu item labels, revision names, and even product names, if you have products.

You need to adjust your filter to be less aggressive and only target the titles that you need to truncate. For example, the following code will only truncate titles:

  • For Posts
  • In the main loop.
  • On the front end.

function wpse_360758_trim_words( $title, $post_id ) {
    if ( is_admin() ) {
        return $title;
    }

    if ( in_the_loop() && 'post' === get_post_type( $post_id ) ) {
        $title = wp_trim_words( $title, 7, '...' );
    }

    return $title;
}
add_filter( 'the_title', 'wpse_360758_trim_words', 10, 2 );
1
  • I think your code is leaner than the one I used, I have accepted your answer as the solution, thank you! Mar 17 '20 at 1:10
-1

I will post the solution that I have found from this thread, seems to be working and not stripping the dashicon tags:

add_filter( 'the_title', 'wpse_75691_trim_words' );

function wpse_75691_trim_words( $title )
{
    // limit to 7 words
    return  force_balance_tags( html_entity_decode( wp_trim_words(htmlentities($title), 7, '...' ) ) );
}
1
  • I would expect a constructive comment on downvoting, eg: a reason for this? Mar 17 '20 at 1:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.