WordPress.org

Ready to get started?Download WordPress

Forums

How to change excerpts from 50 characters to 100 charaters (2 posts)

  1. mlanoue34
    Member
    Posted 3 years ago #

    I am using the "TDD Recent Posts" plugin and I want to change the excerpts from 50 characters to 100. I went into the tddrecentposts.php file and changed 50 to 100, but this didn't work. So I am sure I need to change some other things in the files. Can you PHP experts help me out?

    Here are the files.

    tddrecentposts.php:

    <?php
    /*
    Plugin Name: TDD Recent Posts
    Version: 1.2
    Plugin URI: http://tddewey.com/tdd-recent-posts-wordpress-plugin
    Description: A recent-posts widget that displays a small amount of the post text
    Author: Taylor Dewey
    Author URI: http://www.tddewey.com
    */
    
    /*
    Plugin template written by Trevor Creech (http://trevorcreech.com)
    Other than the plugin template, copyright (c) 2008 Taylor D. Dewey (td@tddewey.com)
    
    This software is distributed under the following license:
    GNU General Public License (GPL) version 3
    http://www.gnu.org/licenses/gpl.html
    
        This program is free software; you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation; either version 2 of the License, or
        (at your option) any later version.
    
        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.
    
        You should have received a copy of the GNU General Public License
        along with this program; if not, write to the Free Software
        Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    
    */
    
    //Uncomment this next line to set $pluginpath to the directory where the plugin resides.  This is very handy if you need to refer to other files included in the directory (images, for example).  The final slash is added, so use it like this: $image = $pluginpath . 'filename.png';  I found this handy line in the Sidebar Widget's code.
    
    $pluginpath = str_replace(str_replace('\\', '/', ABSPATH), get_settings('siteurl').'/', str_replace('\\', '/', dirname(__FILE__))).'/';
    
    //First off, we are going to set up the options used in this plugin if the plugin is being activated and they don't already exist
    register_activation_hook( __FILE__, 'td_install');
    
    function td_install() {
    
                $options = get_option('tddrecentposts');
    
                //If the options array is not true (because there is nothing there, because get_options is empty or doens't exist let's add our defaults.
    
                if(!$options) {
    
                //Set up the default options
                $title_default 	=	'Recent Posts';
                $returnnum_default	=	5;		//Number of rows to return. Default default is 5
                $lengthof_default	=	50;		//# of characters in the post content excerprt. Default default is 50
    			$hard_truncate_default = 0; // Truncate number of characters "exactly". Default is off, we truncate to a '.'
    			$truncate_excerpts_default = 0; //Truncate excerpts, too. Default is off.
    			$ver = '1.2';
    
                $options2 = array('title'=>$title_default, 'returnnum'=>$returnnum_default, 'lengthof'=>$lengthof_default, 'hard_truncate'=>$hard_truncate_default, 'truncate_excerpts'=>$truncate_excerpts_default, 'ver'=>$ver);
    
                add_option('tddrecentposts',$options2);
    
                } else if(!$options['ver'] || $options['ver'] != 1.2) {
    			//Update the database with our new variables for this installation
    
    			//New Vars
    			$hard_truncate_default = true; // Truncate number of characters "exactly". Default is off, we truncate to a '.'
    			$truncate_excerpts_default = 0; //Truncate excerpts, too. Default is off.
               	$ver = '1.2';
    
    			$options2['hard_truncate'] = $hard_truncate_default;
    			$options2['truncate_excerpts'] = $truncate_excerpts_default;
    			$options2['ver'] = $ver;
    
    			update_option('tddrecentposts',array_merge($options,$options2));
    
    			}
    
    }
    
    //uncomment the next line if you want the plugin to uninstall itself from the database. This will be an option in future releases
    //register_deactivation_hook( __FILE__, 'td_uninstall');
    function td_uninstall() {
    
              delete_option('tddrecentposts');
    
                }
    
    //Anything you echo in this function will be placed in the pages header.  To use this function, you must uncomment this line at the bottom of this file: add_action('wp_head', 'tddrecentposts_header');
    
    //This is not used for this plugin at this time.
    function tddrecentposts_header()
    {
    
    	//External javascript file in the plugin directory
    	echo '<script type="text/javascript" src="'. $pluginpath . 'filename.js"></script>';
    
    	//Embedded javascpript
    	echo '<script type="text/javascript">
    		//some javascript code
    		'. /* some php code */ '' . '
    	</script>';
    
    	//External css file in the plugin directory
    	echo '<link rel="stylesheet" href="'.$pluginpath .'filename.css" type="text/css" media="screen" />';
    
    	//Embedded css
    	echo '<style type="text/css">
    		/* some CSS */
    	</style>';
    }
    
    //This is a wrapper for the main function, which grabs the parameters from a direct function call, or from the options database.  The first parameter is important, because it allows you to have the direct data returned.  I use this to insert a plugin contents into a post with the content_tddrecentposts function. If you don't pass any other arguments, the options will be pulled from those set in the options panel.
    function tddrecentposts($echo = 'true') {
    	$options = get_option('tddrecentposts');
    
    	$title = (($title != '') ? $title : $options['title']);
    	$returnnum = (($returnnum != '') ? $returnnum : $options['returnnum']);
    	$lengthof = (($lengthof != '') ? $lengthof : $options['lengthof']);
    
    	if($echo)
    	{
    		echo tddrecentposts_return ($title, $returnnum, $lengthof);
    	}
    	else
    	{
    		return tddrecentposts_return ($title, $returnnum, $lengthof);
    	}
    }
    
    //This is the heart of the plugin, where you get to write your own php code.  I'm afraid I can't help you with that, as it will be completely unique to your plugin.  Just make sure to return your output, instead of echoing it.  The parameters will be passed directly from the tddrecentposts function, so you don't need to use get_options().
    function tddrecentposts_return ($title, $returnnum, $lengthof)
    {
    	global $pluginpath;
    
    //The file output.php deals with calculating and returning $output. It's probably not the best way to segment everything, but it works for now.
    
    require_once('output.php');
    
    	return($output);
    }
    
    //This function creates a backend option panel for the plugin.  It stores the options using the wordpress get_option function.
    function tddrecentposts_control()
    {
    		$options = get_option('tddrecentposts');
    
    		/*This shouldnt be neccessary since there was a on activation hook at the very top
    		if ( !is_array($options) )
    		{
    			//This array sets the default options for the plugin when it is first activated.
    			$options = array('title'=>'Recent News', 'returnnum'=>'5', 'lengthof'=>'50');
    		}*/
    
    		if ( $_POST['tddrecentposts-submit'] )
    		{
    			$options['title'] = strip_tags(stripslashes($_POST['tddrecentposts-title']));
    
    			//Evaluate the two other parameters to ensure they are numeric and fall within the specified range
    
    			if (is_numeric($_POST['tddrecentposts-returnnum']) && $_POST['tddrecentposts-returnnum'] <= 15){
    			$options['returnnum'] = $_POST['tddrecentposts-returnnum'];
    			}
    
    			if (is_numeric($_POST['tddrecentposts-lengthof']) && $_POST['tddrecentposts-lengthof'] <= 200){
    			$options['lengthof'] = $_POST['tddrecentposts-lengthof'];
    			}
    
    			if (!$_POST['tddrecentposts-hard_truncate']){
    			$options['hard_truncate'] = 0;
    			} else {
    			$options['hard_truncate'] = 1;
    			}
    
    			if ($_POST['tddrecentposts-truncate_excerpts'] != 1){
    			$options['truncate_excerpts'] = 0;
    			} else {
    			$options['truncate_excerpts'] = 1;
    			}
    
    			update_option('tddrecentposts', $options);
    		}
    
    		$title = htmlspecialchars($options['title'], ENT_QUOTES);
    
    		echo '<p style="text-align:right;"><label for="tddrecentposts-title">Title:</label><br /> <input id="tddrecentposts-title" name="tddrecentposts-title" type="text" value="'.$title.'" /></p>';
    
    		//You need one of these for each option/parameter.  You can use input boxes, radio buttons, checkboxes, etc.
    		echo '<p style="text-align:right;"><label for="tddrecentposts-returnnum">Number of entries to display (max 15)</label><br /> <input  id="tddrecentposts-returnnum" name="tddrecentposts-returnnum" type="text" size="2" maxlength="2" value="'.$options['returnnum'].'" /></p>';
    		echo '<p style="text-align:right;"><label for="tddrecentposts-lengthof">Length of the preview text (in characters, maximum of 200)</label><br /> <input id="tddrecentposts-lengthof" name="tddrecentposts-lengthof" type="text" size="3" maxlength="3" value="'.$options['lengthof'].'" /></p>';
    		if($options['hard_truncate'] == 1){
    			$hard_truncate_checked = 'checked="checked"';
    			}
    		echo '<p style="text-align:right;"><label for="tddrecentposts-hard_truncate">Hard Truncate<br />(break at <em>exactly</em> the number of chars above)</label><br /> <input id="tddrecentposts-hard_truncate" name="tddrecentposts-hard_truncate" type="checkbox" '. $hard_truncate_checked.' value="1" /></p>';
    				if($options['truncate_excerpts'] == 1){
    					$truncate_excerpts_checked = 'checked="checked"';
    			}
    		echo '<p style="text-align:right;"><label for="tddrecentposts-truncate_excerpts">Truncate the excerpts, too</label><br /> <input id="tddrecentposts-truncate_excerpts" name="tddrecentposts-truncate_excerpts" type="checkbox" '. $truncate_excerpts_checked.' value="1" /></p>';
    
    		echo 'Thanks for using TDD Recent Posts. The database version is: '. $options['ver'];
    		echo '<input type="hidden" id="tddrecentposts-submit" name="tddrecentposts-submit" value="1" />';
    	}
    
    //This function is a wrapper for all the widget specific functions
    //You can find out more about widgets here: http://automattic.com/code/widgets/
    function widget_tddrecentposts_init()
    {
    	if (!function_exists('register_sidebar_widget'))
    		return;
    
    	//This displays the plugin's output as a widget.  You shouldn't need to modify it.
    	function widget_tddrecentposts($args)
    	{
    		extract($args);
    
    		$options = get_option('tddrecentposts');
    		$title = $options['title'];
    
    		echo $before_widget;
    		echo $before_title . $title . $after_title;
    		tddrecentposts();
    		echo $after_widget;
    	}
    
    	register_sidebar_widget('TDD Recent Posts', 'widget_tddrecentposts');
    	//You'll need to modify these two numbers to get the widget control the right size for your options.  250 is a good width, but you'll need to change the 200 depending on how many options you add
    	register_widget_control('TDD Recent Posts', 'tddrecentposts_control', 250, 200);
    }
    
    //Uncomment this if you want the options panel to appear under the Admin Options interface
    //add_action('admin_menu', 'tddrecentposts_addMenu');
    
    //Uncomment this is you need to include some code in the header
    //add_action('wp_head', 'tddrecentposts_header');
    
    //Uncomment this if you want the token to be called using a token in a post (<!--tddrecentposts-->)
    //add_filter('the_content', 'content_tddrecentposts');
    
    //You can comment this out if you're not creating this as a widget
    add_action('plugins_loaded', 'widget_tddrecentposts_init');
    
    ?>

    output.php:

    <?php
    
    		//This is yet another database call just to make SURE that we have the variables we need. I think this is redundant, but until I know exactly what is being sent where, its the safest way.
    
    		$options = get_option('tddrecentposts');
    
    		$returnnum = $options['returnnum'];
    
    		$lengthof = $options['lengthof'];
    
    		$title = $options['title'];
    
    		$truncate_excerpts = $options['truncate_excerpts'];
    
    		$hard_truncate = $options['hard_truncate'];
    
    		global $wpdb;
    
    		$sqllimit = 1000 + $lengthof;
    
    		// SQLlimit sets the amount of data to get from the post. +250 is a guess for how much random HTML could sit before the content since all HTML content gets stripped out. Its not perfect, but I wanted to really limit DB queries.
    
    		$before = '<li><dl>';
    
    		$after = '</dl></li>';
    
    		//Hide posts that require a password to view
    
    		$hide_pass_post = true;
    
    		//Set to "1" to skip always skip the most recent post, etc. Not in the admin section yet.
    
    		$skip_posts = 0;
    
    		//show_excerpts is not an admin option because the point of this plugin is to show excerpts (otherwise use the built-in WP widget. However, it can be toggled here to turn off ALL post content previews. This does not rely on the 'excerpt' built into WP page/post authoring.
    
    		$show_excerpts = true;
    
    		$include_pages = false;
    
    		//Figure out what the current time is so that we are only getting results that are published in the past
    
    		$time_difference = get_settings('gmt_offset');
    
    		$now = gmdate("Y-m-d H:i:s",time());
    
    		//Below is a great CF for the SQL query. Fairly easy to interpret, though.
    
    		$request = $wpdb->prepare("SELECT ID, post_title, post_date, post_excerpt,LEFT(post_content,$sqllimit) AS short_post_content FROM $wpdb->posts WHERE post_status = 'publish' ");
    
    		if($hide_pass_post) $request .= "AND post_password ='' ";
    
    		if($include_pages) $request .= "AND (post_type='post' OR post_type='page') ";
    
    		else $request .= "AND post_type='post' ";
    
    		$request .= "AND post_date_gmt < '$now' ORDER BY post_date DESC LIMIT $skip_posts, $returnnum";
    
    		//Send the request to the DB and capture the result in $posts
    
    		$posts = $wpdb->get_results($request);
    
    		//This starts our list. Its important to maintain the ".=" instead of "=" because the main php file for this function may have already written content to $output
    
    		$output .= '<ul class="tddrecentposts">';
    
    		//Seperate_counter allows us, if needed for future flexibility, count how many rows have been proccessed.
    
    		$separate_counter = 0;
    
    		if($posts) {
    
    			foreach ($posts as $post) {
    
    				$separate_counter = $separate_counter + 1;
    
    				//Define some variables for use below
    
    				$post_title = stripslashes($post->post_title);
    
    				$permalink = get_permalink($post->ID);
    
    				$postdate = date("F j, Y",strtotime($post->post_date));
    
    				//Output the title and link for each entry in the list
    
    				$output .= $before . '<dt><a href="' . $permalink . '" rel="bookmark" title="' . htmlspecialchars($post_title, ENT_COMPAT) . '">' . $post_title . '</a></dt><dd class="sidebardate">'. $postdate ."</dd>";
    
    				//post_excerpt refers to the excerpt function built into WP post/page writing. If an excerpt already exists we don't need to create one, we'll just use that
    
    				if($show_excerpts == 'true' && $post->post_excerpt != '') {
    
    				/*deal with Post Excerpts */
    
    					if ($truncate_excerpts == 0) {
    
    						$post_excerpt = stripslashes($post->post_excerpt);
    
    						$output.= PHP_EOL.'<dd>' . $post_excerpt . ' ... </dd>';
    
    					} else if($hard_truncate == 1) {
    
    						$string = $post->post_excerpt;
    
    						$string = substr($string,0,$lengthof);
    
    						$output .= PHP_EOL.'<dd>'.$string.'</dd>';
    
    					} else if($truncate_excerpts == 1) {
    
    						$string = $post->post_excerpt;
    
    						$break = ".";
    
    						$pad = ". ...";
    
    						if(strlen($string) <= $lengthof) {
    
    						//Do nothing, $string is OK to be placed in $output without truncating it because its already smaller than the length we want to truncate to
    
    						} else  {
    
    							// is $break present between $lengthof and the end of the string?
    
    							if(false !== ($breakpoint = strpos($string, $break, $lengthof))) {
    
    								if($breakpoint < strlen($string) - 1) {
    
    									$string = substr($string, 0, $breakpoint) . $pad;
    
    								}
    
    							}
    
    						}
    
    						$output.= PHP_EOL.'<dd>' . $string . ' </dd>';
    
    						}

    } elseif ($show_excerpts == 'true') {

    /*deal with posts w/o post_excerpts */

    if ($hard_truncate == 1) {

    $string = strip_tags(stripslashes($post->short_post_content));

    $string = substr($string,0,$lengthof);

    $output .= PHP_EOL.'<dd>'.$string.'</dd>';

    } else {

    //We are investigate $string -- this is the full $sqllimit.

    $string = strip_tags(stripslashes($post->short_post_content));

    //$break allows us to break the $string at a defined (rather than arbitrary) point. In this case we are breaking at a period, usually the end of a sentence. $pad is what we will add at the end to indicate that there is more. In this case, it's three periods or elipsis.

    $break = ".";

    $pad = ". ...";

    if(strlen($string) <= $lengthof) {

    //Do nothing, $string is OK to be placed in $output without truncating it because its already smaller than the length we want to truncate to

    } else {

    // is $break present between $lengthof and the end of the string?

    if(false !== ($breakpoint = strpos($string, $break, $lengthof))) {

    if($breakpoint < strlen($string) - 1) {

    $string = substr($string, 0, $breakpoint) . $pad;

    }

    }

    }

    //Now that were done hacking away at the $string, lets send it to the output.

    $output .= "<dd>".$string."</dd>";

    }

    }

    //Were all done now. PHP_EOL = end of line. Makes the HTML source look nice.

    if($separate_counter <= $returnnum) {

    $output .= $after . PHP_EOL . PHP_EOL;

    }

    }

    $output .= '';

    } else {

    $output .= $before . "None found" . $after . '';

    }

    ?>`

    readme.txt:

    <strong>=== Plugin Name ===
    Contributors: taylorde,ericmann
    Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=385223
    Tags: recent,posts,post,pages,page,excerpt,preview
    Requires at least: 2.5
    Tested up to: 2.7
    Stable tag: 1.2

    Simple widget that displays the recent posts with a short content preview. Control the number returned and length of the content preview

    == Description ==

    This is a very simple plugin that essentially mimics the effect of the "recent posts" widget included with WordPress, but with the addition of a content preview. The plugin will, by default, display the name of the post (with a link), the date it was published, and a short bit of text from the post.

    There is a widget admin panel that allows changing of the title, the number of posts to display, and how many characters to use for the content preview.

    Updates:

    * 1.2 - Adds two options: "truncate excerpts" allows you to shorten the content that is hand-written in the excerpt field of a new post. "hard truncate" will shorten the preview content to exactly the number of characters you specify.
    * 1.1 - Fixed xhtml validation errors that this plugin was causing.

    Limitations:

    * The plugin strips out any HTML tags from the post before displaying it, so if you are looking to display images -- try a different plugin. Perhaps in future releases this will get more customized.

    * At this time the plugin does NOT strip out shortcode (e.g. [shortcode]. Shortcode will not be interpreted, but it will be displayed.

    == Installation ==

    Same ol'

    1. Upload the 'tddrecentposts' folder to the /wp-content/plugins/ directory
    1. Activate the plugin through the 'Plugins' menu in WordPress
    1. Add the widget to your sidebar from Design->Widgets

    == Screenshots ==
    1. Sample, styled, output of the plugin. You will need to modify your CSS to get the specific look you need
    2. Widget admin options.

    == Frequently Asked Questions ==

    = It looks like garbage in my theme, What's up? =
    You need to do some CSS Styling. The plugin uses the ul, li, dl, dt, and dd HTML tags.

    The entries are based upon an unordered list with class "tddrecentposts"

    In the next version I will probably include more classes to work off of, but right now you can still do some heavy styling with CSS by calling the classname and then the specific tag you want to work off of. For example:

    .tddrecentposts dt {
    border-bottom: 1px solid #000;
    }

    = Can I set it to display pages as well as posts? =

    Yes, although it is not in the admin menu.
    1. Open output.php.
    1. Find the line that has the variable $include_pages (on or around line 18)
    1. Set the variable to say: $include_pages = true;

    = What about password protected pages? =

    Same as above, but set the variable $hide_pass_post to false.

    = I have a post with a bunch of images before my text and it doesn't display a content preview. What's going on? =

    In order to limit the database query that is made, the plugin only retreives 250 characters more than what it needs. If you have more than 250 characters of HTML markup before the content of your post, it will start cutting into what can be displayed. You can increase the default of 250 characters:
    1. Open output.php.
    1. Find the line that has teh variable $sqllimit (on our around line 3)
    1. Change 250 to whatever you need (or delete in the following line: $sqllimit = 250 + $lengthof;)

    = Why can't I display images (or other HTML stuff) in my recent posts preview? =

    Right now the plugin strips out any HTML occuring in the post and just outputs text. Perhaps this will be in the next release if the demand is strong enough.

    = ________ screwed up OR _________ isn't working... =

    Sorry? Plugin dev isn't my full time job. Shoot me an email or post on my website and I'll try to fix it.

    Thanks for the help in advance!

  2. keesiemeijer
    moderator
    Posted 3 years ago #

    In future use the pastebin to post large pieces of code. In the wp-admin under Appearance > Widgets you can set the excerpt length: "Length of the preview text (in characters, maximum of 200)" if that doesn't work try the option: "Truncate the excerpts, too"

Topic Closed

This topic has been closed to new replies.

About this Topic