Skip to content

Instantly share code, notes, and snippets.

@Mulli
Last active December 6, 2021 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mulli/f4b17b9ca5e369b52f703310796e8790 to your computer and use it in GitHub Desktop.
Save Mulli/f4b17b9ca5e369b52f703310796e8790 to your computer and use it in GitHub Desktop.
Wordpress, limit number of words in post titles on archive pages only
<?php
// Display '...' on post titles in arcive pages
// Limit is 10 (default) if not defined in option: 'post_title_max_words'
// Range of values: 1..20.
// The non trivial issue is to affect only relevant post titles
// and ignore menu post titles and archive page post title
function s2g_short_post_title( $title, $id = null ) {
static $arc_data = null;
if (is_null( $id )) return $title; // ignore
if (is_archive() || is_home()){ // initialize "context", we are in archive page
$post = get_post( $id );
// no menu title, etc...
if ( $post instanceof WP_Post && ( $post->post_type == 'post' || $post->post_type == 'page' ) ) {
$arc_data = array('ID' => $id);
}
return $title; // no change in archive title
}
if (is_single() && is_null($arc_data)) // handle posts in sidebar widgets
return $title;
static $word_limit= null;
if (is_null($word_limit)){
$v = intval(get_option('post_title_max_words'));
if (isset($v) && $v > 0 && $v < 20)
$word_limit = $v;
else $word_limit = 10;
}
$short_title = wp_trim_words( $title, $word_limit );
return $short_title;
}
add_filter( 'the_title', 's2g_short_post_title', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment