Wordpress: How to obtain different excerpt lengths depending on a parameter - wordpress

The length of the excerpt in wordpress is 55 words by default.
I can modify this value with the following code:
function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');
So, the following call will return just 20 words:
the_excerpt();
But I can't figure out how could I add a parameter to obtain different lengths, so that I could call, for example:
the_excerpt(20);
the_excerpt(34);
Any ideas? Thanks!

uhm, answering me again, the solution was actually quite trivial. it's not possible, as far as i know, to pass a parameter to the function my_excerpt_length() (unless you want to modify the core code of wordpress), but it is possible to use a global variable. so, you can add something like this to your functions.php file:
function my_excerpt_length() {
global $myExcerptLength;
if ($myExcerptLength) {
return $myExcerptLength;
} else {
return 80; //default value
}
}
add_filter('excerpt_length', 'my_excerpt_length');
And then, before calling the excerpt within the loop, you specify a value for $myExcerptLength (don't forget to set it back to 0 if you want to have the default value for the rest of your posts):
<?php
$myExcerptLength=35;
echo get_the_excerpt();
$myExcerptLength=0;
?>

There is no way to do this as far as I have found using the_excerpt().
There is a similar StackOverflow question here.
The only thing I have found to do is write a new function to take the_excerpt()'s place. Put some variation of the code below into functions.php and call limit_content($yourLength) instead of the_excerpt().
function limit_content($content_length = 250, $allowtags = true, $allowedtags = '') {
global $post;
$content = $post->post_content;
$content = apply_filters('the_content', $content);
if (!$allowtags){
$allowedtags .= '<style>';
$content = strip_tags($content, $allowedtags);
}
$wordarray = explode(' ', $content, $content_length + 1);
if(count($wordarray) > $content_length) {
array_pop($wordarray);
array_push($wordarray, '...');
$content = implode(' ', $wordarray);
$content .= "</p>";
}
echo $content;
}
(Function credit: fusedthought.com)
There are also "advanced excerpt" plugins that provide functionality like this you can check into.

Thanks for your answer, thaddeusmt.
I am finally implementing the following solution, which offers a different length depending on the category and a counter ($myCounter is a counter within the loop)
/* Custom length for the_excerpt */
function my_excerpt_length($length) {
global $myCounter;
if (is_home()) {
return 80;
} else if(is_archive()) {
if ($myCounter==1) {
return 60;
} else {
return 25;
}
} else {
return 80;
}
}
add_filter('excerpt_length', 'my_excerpt_length');

Related

How to get post id using add_my_endpoint?

I'm creating AMP pages on my own, without a plugin, and I have one problem that I can't solve.
function h34_endpoints_add_endpoint_pinup()
{
add_rewrite_endpoint('amp', EP_ALL);
}
add_action('init', 'h34_endpoints_add_endpoint_pinup');
add_filter('template_include', 'amp_page_template_pinup', 2);
function amp_page_template_pinup($template)
{
if (get_query_var('amp', false) !== false) {
$template = plugin_dir_path(__FILE__) . 'amp-template.php';
}
return $template;
}
Now in the amp-template.php file ш need to get the post data (if it is a post) but where and how to get the post ID?
global $post; shows nothing
get_the_ID() - doesn't output anything either.
I will be grateful for any help

Show shortcode for a given word only once

I'm trying to implement a custom functionality to a wordpress shortcode plugin that shows a tooltip for specified words by automatically calling for information from Wikipedia.
Currently my code snippet works fine, but it shows the tooltips for each occurrence of the word in an article. For example if I specified the word : "dessert" in an array it will show the tooltip for all 5 words "dessert" found in the post. I'm looking for a way to limit the tooltip shortcode to be applied only once per word ( in this case "dessert" which has been specified in the array).
Me code snippet is this:
function add_wikitips($content) {
if( is_single() && is_main_query() ) {
$arr = array('dessert');
for ($i = 0; $i < count($arr); $i++) {
$content = str_replace($arr[$i], '[wiki]'.$arr[$i].'[/wiki]', $content);
}
}
return $content;
}
add_filter('the_content', 'add_wikitips');
I tried adding ob_end_clean(); then
static $content = null;
if ($content === null) {
return $content;
}
, but these methods didn't work. Probably because I didn't implement them properly.
Thanks a lot in advance for any advice and suggestions.
Probably, you can try this: Using str_replace so that it only acts on the first match?
You want the first work to have Wiki link. So replace the first occurrence only when you are doing str_replace()
May be like:
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
echo str_replace_first('abc', '123', 'abcdef abcdef abcdef');
// outputs '123def abcdef abcdef'
Mentioned in Karim's amswer

Wordpress: add custom params to all URLS

I have an addition to url e.g. /products/myproduct/?v=iphone-x/transparent/*/Green
So what I need is for wordpress to add the ?v=iphone-x/transparent/*/Green to all links on the page (only '<a href="">'s, no 'img src=""' or others)
I have managed to do that, but it's a little "dirty". Is there any neat function to add the parameter to all links?
The code I have is as follows:
function callback($buffer) {
// modify buffer here, and then return the updated code
$temp = explode('href="', $buffer);
$buffer = $temp[0];
array_shift($temp);
foreach($temp as $t){
$tt = explode('"', $t, 2);
$buffer .= 'href="'.$tt[0].'?v='.$_GET['v'].'"'.$tt[1];
}
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');
One way you can achieve this is to hook into "the_content" filter. By using regexp with preg_replace_callback function you can get decent results.
function add_para( $content ) {
$content = preg_replace_callback(
"/href=(?>'|\")([^\"']+)(?>'|\")/",
function($m) {
print_r($m);
return "href='".$m[1]."/additional-param'";
},
$content);
return $content;
}
add_filter( 'the_content', 'add_para', 0 );
However, you might run into some issues particularly if your content is not formatted probably (extra spaces, missing tags .. etc).
So the alternative is either to us a JS approach (jQuery for example), or using PHP DOM parser like: PHP Simple HTML DOM Parser

Wordpress get values outside function

I need get the value of function that use in wordpress , this function add the value in other page of wordpress using the API add_action , i put the script :
<?php
function wplogincontrol()
{
$a=2;
}
if ($a=="2")
{
header"Location:http://www.google.com");
}
add_action('login_head', 'wplogincontrol');
?>
If use this never can do works and i think use global var and use this :
<?php
function wplogincontrol()
{
global $a;
$a=2;
}
global $a;
if ($a=="2")
{
header"Location:http://www.google.com");
}
add_action('login_head', 'wplogincontrol');
?>
Also i try with $GLOBALS['a'];
But never can get works and can´t get the value outside the function , i try this because if use header location inside function and no work me and give error of header , by this i need get the value outside of function and i see works fine for redirect of header
It´s possible get this value ? , Thak´s , Regards
Are you trying to do something like this ?
<?php
function myfunc()
{
$a=2;
return $a;
}
function wplogincontrol(){
$val = myfunc();
if ($val=="2")
{
header"Location: http://www.google.com");
exit;
}
}
add_action('login_head', 'wplogincontrol');
?>

Wordpress Excerpt with allowable tags is not working?

I am trying to create the simple excerpt plugin in Wordpress. I Googled a lot the allowable tag is not working, can anyone give me a suggestion how to do this?
class fpexcerpt {
function __construct() {
require_once('inc/template.php');
if(isset($_POST['reset'])) {
add_action('admin_init',array($this,'fpexcerptrestore'));
}
}
function fpexcerptdefault() {
add_option('fpexcerptcount',55);
add_option('fpexcerptmore','[...]');
}
function fpexcerptrestore() {
delete_option('fpexcerpttag');
delete_option('fpexcerptcount');
delete_option('fpexcerptmore');
fpexcerpt::fpexcerptdefault();
}
function fpexcerptadmin() {
add_submenu_page('options-general.php','Fantastic Excerpt', 'Fantastic Excerpt', 'manage_options','fpexcerptadmin', 'fpexcerptadmin_menu');
}
function fpexcerptupdate() {
register_setting('fpexcpt','fpexcerpttag');
register_setting('fpexcpt','fpexcerptcount');
register_setting('fpexcpt','fpexcerptmore');
}
function improved_trim_excerpt($text) {
global $post;
if ( '' == $text ) {
$text = get_the_excerpt();
$text = apply_filters('the_excerpt',$text);
// $text = str_replace('\]\]\>', ']]>', $text);
$text = strip_tags($text, '<a>');
$excerpt_length = 80;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, '[...]');
$text = implode(' ', $words);
}
}
return $text;
}
}
$new = new fpexcerpt();
register_activation_hook(__FILE__,array('fpexcerpt','fpexcerptdefault'));
//remove_all_filters('wp_trim_excerpt');
//add_filter('get_the_excerpt', array('fpexcerpt','fpexcerptprocess'));
remove_filter('get_the_excerpt',array('fpexcerpt','wp_trim_excerpt'));
add_filter('get_the_excerpt', array('fpexcerpt','improved_trim_excerpt'));
add_action('admin_menu',array('fpexcerpt','fpexcerptadmin'));
add_action('admin_init',array('fpexcerpt','fpexcerptupdate'));
?>
EDIT:
The first image is show the excerpt content when i click the particular post its getting link but not in excerpt even if i add the excerpt plugin (mine)
Error: Maximum function nesting level of '100' reached, aborting! in E:\wamp\www\fp\wp-includes\cache.php on line 453
Based on the error you've reported above, I can surmise you're stuck in a recursive function call loop. In other words, a function you've written is ( at some point in the callstack ) calling itself ( or a function that calls it ). Picture an infinite loop, but with functions.
I can't determine where this is occurring since I can't see all of your code.

Resources