• Home
  • WordPress
    • How To
    • Plugins
    • Themes
      • Genesis
      • Themify
      • Mysite myway
    • Security
    • Developer
    • Teaching
    • Conference
    • Chat
  • Blog
  • About
  • Freelance
    • Plugins
    • Teaching
    • Need help?
    • CV og ref.
  • Contact

Easy Web Design Tutorials

WordPress Tutorials and more

  • Home
  • WordPress
    • How To
    • Plugins
    • Themes
      • Genesis
      • Themify
      • Mysite myway
    • Security
    • Developer
    • Teaching
    • Conference
    • Chat
  • Blog
  • About
  • Freelance
    • Plugins
    • Teaching
    • Need help?
    • CV og ref.
  • Contact

3 July - 2016 By Paal Joachim Add a Comment
Last updated on: February 4, 2019

There are multiple code snippets we can add to customize the excerpts meta box

Part 1 – How to use and style the excerpt

All the following code snippets are added into the functions.php file below the other code that is in it.

First lets add the excerpt meta box to the single pages screen:

add_post_type_support( 'page', 'excerpt' );

 

The following code snippets are from this article at:
https://marketblog.envato.com/web-design/wordpress-excerpts/

Allowing shortcodes in the excerpt field:

// Allow Shortcodes in the Excerpt field
 add_filter('the_excerpt', 'do_shortcode');

Limit the length of the words used in the excerpt:

// Limit the amount of words shown in the excerpt. Default is 55. Change XX to the amount of words you want to use.
 function custom_excerpt_length( $length ) {
 return XX; // Replace XX with a number.
 }
 add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

 

https://www.hongkiat.com/blog/wordpress-tweaks-for-post-management/

Another code for limiting words in the excerpt:

add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($len) {
   return 75;
}

Add “Read More” permalink to the end of the_excerpt
Adding this snippet below into the functions.php file of your WordPress theme will add a “read more” permalink at the end of the_excerpt.

function excerpt_readmore($more) {
    return '... <a href="'. get_permalink($post->ID) . '" class="readmore">' . 'Read More' . '</a>';
}
add_filter('excerpt_more', 'excerpt_readmore');

Change excerpt length depending of the category
Change the category ID on line 3. Use ID or ‘category name’.

add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
 if(in_category(14)) // use a number or the name 'category name '
{
 return 13;
 } else {
 return 60;
 }
}

 

Get excerpt tutorial: https://qnimate.com/get-page-excerpt-in-wordpress/

Here is the code to display the excerpt of the current requested page in WordPress.
NB! This code needs more exploring…

 if(is_single() || is_page())
 {
 global $wp_query;
 $id = $wp_query->post->ID;
 $the_post = get_post($id);
 $the_excerpt = $the_post->post_content;
 $shortcode_pattern = get_shortcode_regex();
 $the_excerpt = preg_replace('/' . $shortcode_pattern . '/', '', $the_excerpt);
 $the_excerpt = strip_tags($the_excerpt); 
 echo esc_attr(substr( $the_excerpt, 0, 200));
 }
 else if(is_home() || is_front_page())
 {
 echo "QNimate provides tutorials on WordPress, Hybrid Mobile Development, Web Development and Much More";
 } 
 else if(is_category())
 {
 $name = single_cat_title('', false);
 echo "Learn about " . $name;
 }
 else if(is_tag())
 {
 $name = single_tag_title('', false);
 echo "Learn about " . $name; 
 }
 else if(is_date())
 {
 $date = single_month_title(' ', false);
 echo "Displaying posts of ". $date;
 }

For posts and pages the excerpt is retrieved from the content.

 

Excerpt counter code I found at:
https://premium.wpmudev.org/blog/character-counter-excerpt-box/

function excerpt_count_js(){

if ('page' != get_post_type()) {

echo '<script>jQuery(document).ready(function(){
jQuery("#postexcerpt .handlediv").after("<div style=\"position:absolute;top:12px;right:34px;color:#666;\"><small>Excerpt length: </small><span id=\"excerpt_counter\"></span><span style=\"font-weight:bold; padding-left:7px;\">/ 500</span><small><span style=\"font-weight:bold; padding-left:7px;\">character(s).</span></small></div>");
 jQuery("span#excerpt_counter").text(jQuery("#excerpt").val().length);
 jQuery("#excerpt").keyup( function() {
 if(jQuery(this).val().length > 500){
 jQuery(this).val(jQuery(this).val().substr(0, 500));
 }
 jQuery("span#excerpt_counter").text(jQuery("#excerpt").val().length);
 });
});</script>';
}
}
add_action( 'admin_head-post.php', 'excerpt_count_js');
add_action( 'admin_head-post-new.php', 'excerpt_count_js');

 

Getting the code to work the the below TinyMCE visual editor inserted code requires a bit more work.

 

 

Add the TinyMCE visual editor to the excerpts meta box.
I will add some variations that give the same result. Select one of them or experiment with the code.

The result:

Excerpts tinymce visual editor

 

Code to adding the TinyMCE visual editor to an excerpt is from:
https://marcgratch.com/add-tinymce-to-excerpt/

Code 1.
To me this seems like the best code of the 3 to use.

function lb_editor_remove_meta_box() {
 global $post_type;
/**
 * Check to see if the global $post_type variable exists
 * and then check to see if the current post_type supports
 * excerpts. If so, remove the default excerpt meta box
 * provided by the WordPress core. If you would like to only
 * change the excerpt meta box for certain post types replace
 * $post_type with the post_type identifier.
 */
 if (isset($post_type) && post_type_supports($post_type, 'excerpt')){
 remove_meta_box('postexcerpt', $post_type, 'normal');
 } 
}
add_action('admin_menu', 'lb_editor_remove_meta_box');
 
function lb_editor_add_custom_meta_box() {
 global $post_type;
 /**
 * Again, check to see if the global $post_type variable
 * exists and then if the current post_type supports excerpts.
 * If so, add the new custom excerpt meta box. If you would
 * like to only change the excerpt meta box for certain post
 * types replace $post_type with the post_type identifier.
 */
 if (isset($post_type) && post_type_supports($post_type, 'excerpt')){
 add_meta_box('postexcerpt', __('Excerpt'), 'lb_editor_custom_post_excerpt_meta_box', $post_type, 'normal', 'high');
 }
}
add_action( 'add_meta_boxes', 'lb_editor_add_custom_meta_box' );
 
function lb_editor_custom_post_excerpt_meta_box( $post ) {

/**
 * Adjust the settings for the new wp_editor. For all
 * available settings view the wp_editor reference
 * https://codex.wordpress.org/Function_Reference/wp_editor
 */
 $settings = array( 'textarea_rows' => '12', 'quicktags' => false, 'tinymce' => true);

/**
 * Create the new meta box editor and decode the current
 * post_excerpt value so the TinyMCE editor can display
 * the content as it is styled.
 */
 wp_editor(html_entity_decode(stripcslashes($post->post_excerpt)), 'excerpt', $settings);
 
 // The meta box description - adjust as necessary
 echo '&lt;p&gt;&lt;em&gt;Excerpts are optional, hand-crafted, summaries of your content.&lt;/em&gt;&lt;/p&gt;';
}

 

 

Code 2 – stopped working and is removed.

 

 

Following code is from: https://wordpress.stackexchange.com/questions/58261/adding-a-rich-text-editor-to-excerpt

Code 3 (Works well in Gutenberg. It adds a meta box on the bottom of the page with TinyMCE toolbar so one can customize the excerpt outside of the tiny sidebar excerpt option.)

add_action( 'add_meta_boxes', array ( 'T5_Richtext_Excerpt', 'switch_boxes' ) );

/**
 * Replaces the default excerpt editor with TinyMCE.
 */
class T5_Richtext_Excerpt
{
 /**
 * Replaces the meta boxes.
 *
 * @return void
 */
 public static function switch_boxes()
 {
 if ( ! post_type_supports( $GLOBALS['post']->post_type, 'excerpt' ) )
 {
 return;
 }

remove_meta_box(
 'postexcerpt' // ID
 , '' // Screen, empty to support all post types
 , 'normal' // Context
 );

add_meta_box(
 'postexcerpt2' // Reusing just 'postexcerpt' doesn't work.
 , __( 'Excerpt' ) // Title
 , array ( __CLASS__, 'show' ) // Display function
 , null // Screen, we use all screens with meta boxes.
 , 'normal' // Context
 , 'core' // Priority
 );
 }

/**
 * Output for the meta box.
 *
 * @param object $post
 * @return void
 */
 public static function show( $post )
 {
 ?>
 <label class="screen-reader-text" for="excerpt"><?php
 _e( 'Excerpt' )
 ?></label>
 <?php
 // We use the default name, 'excerpt', so we don’t have to care about
 // saving, other filters etc.
 wp_editor(
 self::unescape( $post->post_excerpt ),
 'excerpt',
 array (
 'textarea_rows' => 15
 , 'media_buttons' => FALSE
 , 'teeny' => TRUE
 , 'tinymce' => TRUE
 )
 );
 }

/**
 * The excerpt is escaped usually. This breaks the HTML editor.
 *
 * @param string $str
 * @return string
 */
 public static function unescape( $str )
 {
 return str_replace(
 array ( '&lt;', '&gt;', '&quot;', '&amp;', '&nbsp;', '&amp;nbsp;' )
 , array ( '<', '>', '"', '&', ' ', ' ' )
 , $str
 );
 }
}

 

Then we move the excerpts from below the Content area to above it.

I found the following code here: https://wpartisan.me/tutorials/wordpress-how-to-move-the-excerpt-meta-box-above-the-editor

Add the code to your functions file.

/**
 * Removes the regular excerpt box. We're not getting rid
 * of it, we're just moving it above the wysiwyg editor
 *
 * @return null
 */
 function oz_remove_normal_excerpt() {
 remove_meta_box( 'postexcerpt' , 'post' , 'normal' );
 }
 add_action( 'admin_menu' , 'oz_remove_normal_excerpt' );

/**
 * Add the excerpt meta box back in with a custom screen location
 *
 * @param string $post_type
 * @return null
 */
 function oz_add_excerpt_meta_box( $post_type ) {
 if ( in_array( $post_type, array( 'post', 'page' ) ) ) {
 add_meta_box(
 'oz_postexcerpt',
 __( 'Excerpt', 'thetab-theme' ),
 'post_excerpt_meta_box',
 $post_type,
 'after_title',
 'high'
 );
 }
 }
 add_action( 'add_meta_boxes', 'oz_add_excerpt_meta_box' );

/**
 * You can't actually add meta boxes after the title by default in WP so
 * we're being cheeky. We've registered our own meta box position
 * `after_title` onto which we've regiestered our new meta boxes and
 * are now calling them in the `edit_form_after_title` hook which is run
 * after the post tile box is displayed.
 *
 * @return null
 */
 function oz_run_after_title_meta_boxes() {
 global $post, $wp_meta_boxes;
 # Output the `below_title` meta boxes:
 do_meta_boxes( get_current_screen(), 'after_title', $post );
 }
 add_action( 'edit_form_after_title', 'oz_run_after_title_meta_boxes' );

Share this:

  • Email

Categories: Developer, WordPress

Paal Joachim Romdahl

I enjoy teaching and creating tutorials. As well creating web sites.
I help people gain WordPress knowledge through my easy to follow tutorials and specialized training. Contact me for more information on how I can improve your WordPress skills and to help get your web site quickly up and running.

Leave a Comment Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2021 · By Easy Web Design Tutorials · Built on the Genesis Framework · WordPress · Log in · ⇪

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.