I'm totally new to WordPress so be easy :)
I the following code in a template:
<?php excerpt(20);?>
What this does is limit the text with 20 words. I am now wondering if there is some sort of similar function that limits by characters instead of words?
Thanks!
I use this:
add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($length) {
return '500';
}
function better_excerpt($limit, $id = '') {
global $post;
if($id == '') $id = $post->ID;
else $id = $id;
$postinfo = get_post($id);
if($postinfo->post_excerpt != '')
$post_excerpt = $postinfo->post_excerpt;
else
$post_excerpt = $postinfo->post_content;
$myexcerpt = explode(' ', $post_excerpt, $limit);
if (count($myexcerpt) >= $limit) {
array_pop($myexcerpt);
$myexcerpt = implode(' ',$myexcerpt).'...';
} else {
$myexcerpt = implode(' ',$myexcerpt);
}
$myexcerpt = preg_replace('`\[[^\]]*\]`','',$myexcerpt);
$stripimages = preg_replace('/<img[^>]+\>/i', '', $myexcerpt);
return $stripimages;
}
And then in my theme file, I just call it in with:
better_excerpt('50') //50 being how many words I want
Useful for custom plugins/widgets too.
Wordpress doesn't support the character delimiter for the excerpt method, there's a plugin called Advanced Excerpt that does. After installing you can call the_advanced_excerpt('length=20&use_words=0')
I use this in my functions.php:
function truncate ($str, $length=10, $trailing='...'){
// take off chars for the trailing
$length-=mb_strlen($trailing);
if (mb_strlen($str)> $length){
// string exceeded length, truncate and add trailing dots
$str = mb_substr($str,0,$length);
$str = explode('. ',$str);
for( $i=0; $i<(sizeof($str)-2); $i++ ):
$newstr .= $str[$i].". ";
endfor;
return $newstr;
} else{
// string was already short enough, return the string
$res = $str;
}
return $res;
}
It should truncate to a character count, but then truncate back further to the last period before the truncation. It does get problematic when your excerpt includes links, however, or other markup - in other words, it's best to use the Excerpt field in the post rather than auto-excerpting with this function, because you can't use HTML in the excerpt field.
Please use this code for limiting post content...
<?php substr($post->post_content, 0, xy); ?> ...
Change the limit of XY....
Related
The framework offer LimitWordCount in StringField.php file. It's great but not totally perfect. Some tags et ponctuation needs the be corrected.
I would like :
Keep tags <sup><sub><em>
Correct ponctuation : «.» to «. », «,» to «, », «?» to «? » etc....
I have made my own LimitWordCount :
public function MyLimitWordCount($int) {
$text = strip_tags($this->owner->value, '<sup><sub><em>');
if (str_word_count($text, 0) > $int) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$int]) . '…';
}
$text = str_replace('.', '. ', $text );
$text = str_replace('!', '! ', $text );
$text = str_replace('…', '… ', $text );
$text = str_replace('?', '? ', $text );
return $text;
}
That not works totally. Some ponctuation are not corrected and video shortcodes [embed width="480...] made in an HTMLEditor fields are keep with my function. I dont' know what him doing wrong.
You'll continue to get the shortcodes in your text becuase you need to parse them first.
This is most easily resolved by using (string)$this->owner->dbObject('value') rather than $this->owner->value.
You can then manipulate the value where the shortcodes have been expanded.
I can't comment on why your punctuation is not being "corrected" in this instance as you haven't supplied much information on which punctuation and under what circumstances it isn't working.
I have been trying to set a value containing a percentage sign in PHPExcel.
I couldn't find how to escape it at all and all searches point me to how to format a percentage, but that's not what I need.
My current problem is:
$cell = 'Z12';
$value = '=Y12-(Y12*20%)';
$excel->setActiveSheetIndex(0)->setCellValue($cell, $value);
This problem is specific to the Excel5 Writer, the percentage operator works correctly in other writers.
I'm about to push a fix to github, but in the meanwhile you can edit the Classes/PHPExcel/Writer/Excel5/Parser.php file.
Lines 1431-1437 currently read:
if($this->_lookahead == '%'){
$result = $this->_createTree('ptgPercent', $this->_current_token, '');
} else {
$result = $this->_createTree($this->_current_token, '', '');
}
$this->_advance();
return $result;
Modify these with an extra call to $this->_advance(); for the % operator lookahead branch:
if($this->_lookahead == '%'){
$result = $this->_createTree('ptgPercent', $this->_current_token, '');
$this->_advance(); // Skip the percentage operator once we've pre-built that tree
} else {
$result = $this->_createTree($this->_current_token, '', '');
}
$this->_advance();
return $result;
Current I have WP code like this. I need to make it translateable by poedit. How do I wrap the code to make it work? Im not sure which method is use for this case. Some thing like:
<?php my_e( 'Total sales' ); ?> or __('Total sales', 'my')
This is the code. I need to translate ["Sales amount"], ["Number of sales"]
foreach ($results as $result) {
$date = $result->formatted_post_date;
$statistics[$date]["Sales amount"] += $wp_list_table->column_total_sales($result->ID);
$statistics[$date]["Number of sales"]++;
$statistics[$date]["date"] = $date;
$max_number_of_sales = max(array($max_number_of_sales,$statistics[$date]["Number of sales"] )); }
Thank you for help
You have to use __('string','textdomain') to assign a translated string to some variable. And _e('string','textdomain') to echo a translated string. See I18n_for_WordPress_Developers.
Two observations:
you'll not be able to translate array keys, see php.net/manual/en/language.types.array.php
what you're doing seems wrong. I'd do it like:
$sales_amount = 0;
$sales_number = 0;
foreach ($results as $result) {
$sales_amount += $wp_list_table->column_total_sales($result->ID);
$sales_number++;
$date = $result->formatted_post_date;
$statistics[$date]["sales_amount"] = $sales_amount;
$statistics[$date]["sales_number"] = $sales_number;
}
echo __( 'Sales Amount', 'my' ) . $sales_amount;
Is it possible to grab the contents of the WYSIWYG editor and save the first 100 words into the excerpt automatically? I know about excerpt_save_pre which will save the excerpt when you are in the editor, but haven't seen anything that will grab the contents from the WYSIWYG editor.
I've figured this out. The "secret" is &$_POST when the post is saved/published. That builds an array which the content can be extracted and then saved to the excerpt field using excerpt_save_pre.
I went a little further allowing control over the number of characters or the number of words, using $length, and the output is controlled on which $output section you uncomment.
The code below tested on my vanilla site as working.
function auto_insert_excerpt(){
$post_data = &$_POST;
$post_content = $post_data['content'];
$length = 15;
// This will return the first $length number of CHARACTERS
//$output = (strlen($post_content) > 13) ? substr($post_content,0,$length).'...' : $post_content;
// This will return the first $length number of WORDS
$post_content_array = explode(' ',$post_content);
if(count($post_content_array) > $length && $length > 0)
$output = implode(' ',array_slice($post_content_array, 0, $length)).'...';
return $output;
}
add_filter('excerpt_save_pre', 'auto_insert_excerpt');
I'm trying to search for a way to order categories by meta value. From what I read, it seems like I can use:
get_categories('child_of=92&hide_empty=false&orderby=meta_value&meta_key=date&order=ASC');
However, this does not work at all, the categories are still not in the order I want. I wonder how I can:
correct this to make it work
print out the sql to see what is really going on inside?
Thank you very much in advance.
First of all, I must mention that I'm using the module custom category fields, and second of all I'm a complete WP newbie
Anyhow, after learning that this cannot be done by default, I looked into the get_categories functions and finally came up with a solution
function category_custom_field_get_terms_orderby( $orderby, $args ){
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
return 'cv.field_value';
return $orderby;
}
function category_custom_field_get_terms_fields( $selects, $args ){
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
$selects[] = 'cv.*';
return $selects;
}
function category_custom_field_terms_clauses($pieces, $taxonomies, $args){
global $wpdb;
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
$pieces['join'] .= " LEFT JOIN $wpdb->prefix" . "ccf_Value cv ON cv.term_id = tt.term_id AND cv.field_name = '".$args['category_custom_field']."'";
return $pieces;
}
add_filter('get_terms_orderby', 'category_custom_field_get_terms_orderby',1,2);
add_filter('get_terms_fields', 'category_custom_field_get_terms_fields',1,2);
add_filter('terms_clauses', 'category_custom_field_terms_clauses',1,3);
(The code above can be put into the theme functions.php file)
then the code to get categories is:
get_categories('child_of=92&hide_empty=false&orderby=category_custom_field&category_custom_field=date&order=DESC');
Any correction is greatly appreciated!
You can also give the get_categories new meta and sort using usort.
$subcategories = get_categories();
foreach ($subcategories as $subcategory) {
$subcategory->your_meta_key = your_meta_value;
}
foreach ($subcategories as $subcategory) {
blah blah blah
}
function my_cmp($a, $b) {
if ($a->ordering == $b->ordering) {
return 0;
}
return ($a->ordering < $b->ordering) ? -1 : 1;
}
usort($subcategories, "my_cmp");