WordPress: Titel kürzen

Eine Frage, die immer wieder in WordPress-Foren auftaucht, ist, wie man den Titel auf eine bestimmte Anzahl Zeichen kürzen und ein “…” anfügen kann.

Das Problem ist mit einigen Zeilen PHP schnell gelöst:

add_filter( 'the_title', 'short_title' );
function short_title( $title ) {
  $chars = 20;
  if ( strlen( $title ) > $chars ) {
    $title = substr( $title, 0, $chars );
    $title .= " …";
  }
  return $title;
}

Die Variable $chars muss auf die Anzahl Zeichen gesetzt werden, die man maximal anzeigen möchte und in Zeile 6 muss der Platzhalter für den ausgelassenen Text eingefügt werden (… ist typografisch richtige Version für drei Punkte, Ellipse genannt).

Nachteilig an dieser Lösung ist, dass der Titel mitten in einem Wort abgeschnitten werden könnte. Wenn man möchte, kann man die Funktion entsprechend erweitern:

add_filter( 'the_title', 'short_title' );
function short_title( $title ) {
  $chars = 20;
  if ( strlen( $title ) > $chars ) {
    $title = substr( $title, 0, $chars );
    $title = substr($title, 0, strrpos( $title, ' ' ) );		
    $title .= " …";
  }
  return $title;
}

Kopiert man diese Funktion in die funtions.php des Themes werden alle Aufrufe von the_title den eingefügten Angaben entsprechend gekürzt.

One thought on “WordPress: Titel kürzen”

  1. Ich habe noch eine bessere Lösung gefunden / erstellt wenn mann einen Bestimmten Titel nur ändern möchte.folgendes in die funcions.php einfügen:////////////////////////////////////////////////function ShortTitle($text){// Change to the number of characters you want to display$echo = false;$length = 37;$dots = ‚…‘;if (strlen($text) == 0) return;if (strlen($text)>$length) {$text = substr(trim($text), 0, $length-3);if (strrpos(trim($text), “ „)>0) {$text = substr($text, 0, strrpos(trim($text), “ „));}$text=$text . $dots;}if ($echo)echo $text;elsereturn $text;}////////////////////////////////////////////////… und für die Ausgabe einfach folgendes an der gewünschten Stelle (title) in die page.php oder single.php oder andere.php seinfügen:///////////////////////////////////

    /////////////////////////////////////////////////////////////somit kann man einen bestimmten titel kürzen, die Andern title bleiben in original Länge erhalten.

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)