Through research, I've discovered this question has been asked on multiple occasions, however, my instance is a bit different. I'm attempting to add a character limit to a pre-existing customer environment with the following elseif:
elseif(get_post_type() == 'post') {
echo '<p class="excerpt">';
the_excerpt();
echo '</p>';
}
I attempted to use a couple of methods through functions, however, I've been unable to find a resolution. I'm not natively a PHP developer, so I'm learning as I go here and hoping a fellow develop can help resolve this question and provide a brief description of how to handle this in the future.
Thanks!
P.S. - I read the documentation here: http://codex.wordpress.org/Conditional_Tags and wasn't able to make it work without breaking the rest of the else statement.
By default, excerpt length is set to 55 words. To change excerpt length to 20 words using excerpt_length filter, add the following code to functions.php file in your theme:
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
http://codex.wordpress.org/Function_Reference/the_excerpt
Use get_the_excerpt to return the text without printing it, and chop it to the length you want with substr:
elseif(get_post_type() == 'post') {
echo '<p class="excerpt">';
$excerpt = get_the_excerpt();
$limit = 100;
if (strlen($excerpt) > $limit) {
echo substr($excerpt, 0, $limit), '[...]';
} else {
echo $excerpt;
}
echo '</p>';
}
Lots of ways to do this.
Easy Way:
Install the Advanced Excerpt plugin and replace the_excerpt(); with the_advanced_excerpt() and configure as needed in Settings -> Excerpt in admin panel (or use string query vars in the function call). This also lets you do a lot of stuff like have custom "read more" link (or exclude it), add '...' or some other text at the end, strip or allow specific html tags, etc.
Tedious Way:
You can use substr PHP function (docs) in conjunction with get_the_content(); or get_the_excerpt() to trim it to however many characters you want (or do whatever else you want to it) like freejosh's answer.
Advanced / Clean Way:
Filter the excerpt length to however many characters you want using the method described in Srikanth's answer (this is my preferred way, unless you need some of the Advanced Excerpt options like use_words etc).
Related
I'm trying to create a basic short code in Wordpress that will allow me to run PHP on pages. This is what I have so far, but it isn't working. Advice?
The idea is it will be [php] Insert PHP here [/php']
<?php
function php_shortcode( $attr, $content = null ) {
return '<?php' . $content . '?>';
}
add_shortcode('php', 'php_shortcode');
?>
Thank you.
Sorry to say you are exploring a concept that simply cannot yield success. The PHP that renders the shortcode, cannot "also" render code within itself.
Short codes as standard will filter PHP tags. You can however write php directly into the content editor. Without giving you all the advisories why it's not recommended, you can do something like the following which will allow you to write php into the content editor:
// write '<?php ... ?>' into the editor
add_filter('the_content', 'allow_php', 9);
function allow_php($content) {
if (strpos($content, '<' . '?') !== false) {
ob_start();
eval('?' . '>' . $content);
$content = ob_get_clean();
}
return $content;
}
After thinking about this for a little while I realized there is an obvious solution. So, someone probably has written a plugin to do it and someone has - https://wordpress.org/plugins/inline-php/.
It consists of about 40 lines of PHP. The critical implementation trick is it is not done as a shortcode but as a 'the_content' filter.
add_filter('the_content', 'inline_php', 0);
This is done before other 'the_content' filter processing and avoids all the problems that I encountered trying to use it as a shortcode. Of course, there is still a significant security risk.
I'm trying to find a way to create view all button in the Woocommerce pagination.
All other sources seem to be outdated and not working.
Currently found one source that is quite recent, but still not working.
So right now I have this:
if( isset( $_GET['showall'] ) ){
add_filter( 'loop_shop_per_page', create_function( '$cols', 'return -1;' ) );
}
else {
add_filter( 'loop_shop_per_page', create_function( '$cols', 'return 25;' ) );
}
And added this for the HTML link in the pagination.php:
echo '<li><a href="';
echo curPageURL();
echo '?showall=1">All</a></li>';
The html link is showing, but it doesn't seem to run the function view all.
Is there something I may be doing incorrectly? or is this method outdated?
Help is greatly appreciated.
The create_function function may still be supported in some situations, but it is highly discouraged. It is actually one of a few functions that when enabled opens your website up to a number of hacking vulnerabilities, which is why in later versions of PHP it has been deprecated. I'd bet your host has it disabled and thus the code you have is not working possibly because of that.
Doing a quick google I found documentation on how to carry out what you said here. Now with a bit of modification based on what you have so far, I'd try this:
add_filter('loop_shop_per_page', 'my_per_page_filter', 100);
function my_per_page_filter($cols) {
return isset($_GET['showall']) ? -1 : $cols;
}
In the code above I am using a bit of code magic to say if $_GET['showall'] is set, then return -1 else the regular number of columns in $cols. I have also set the priority of the filter to 100 so hopefully it runs after other filters, if you find this code does not work then try a much higher value like 99999.
Hope this helps!
Koda
I'm using the Cart66 Wordpress plugin, and I'm trying to include a variable in a shortcode, you can see the code below:
$price = do_shortcode('[add_to_cart item="test-item" showprice="only" text=""]').' test';
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="'.$price.'" ]');
I've done some googling, and apparently this is the right way to include variables in Wordpress shortcodes, but this doesn't seem to work for me, Cart66 just falls back and uses the default "Add to Cart" text instead of the text defined in the shortcode above.
Can anyone see where I'm going wrong here?
As you have googled to add text in the shortcode is correct but not fully correct.
You have used "do_shortcode()" function which is used to replace the shortcode functionality and display its functionality in frontend. But, if you want to add a parameter in a shortcode and make it working you need to change the shortcode functionality a bit.
You have to find shortcode in your files containing the shortcode's functionality:
Find code something like below:
add_shortcode('add_to_cart','function_name');
function function_name($atts)
{
$atts //-- will be used to add parameters as you needed
}
You can use PHP's Output Buffering control
PS: do_shortcode() does not natively echo the output; whatever is bound on that action may echo by itself as well, which is when you either (A) edit the plugin, or (B) use OB.
I think there were some weird characters in the returend value that were causing issues, I used the Expression code below, and it seemed to solve my issue:
$value = substr(do_shortcode('[add_to_cart item="test-item" showprice="only" text=""]'), 0, 4).' Test';
$patterns = array();
$patterns[0] = '/"/';
$replacements = array();
$replacements[2] = ' ';
$value = preg_replace($patterns, $replacements, html_entity_decode($price, ENT_QUOTES));
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="'.$price.'" ]');
Needless to say this was a very ... complicated solution. I ended up using some good old SQL by utilising Wordpresses WPDB class. Turning about 7 lines of code into 2:
$priceValue = $wpdb->get_var("SELECT price FROM wp_cart66_products WHERE id = x");
echo do_shortcode('[add_to_cart item="test-item" showprice="no" quantity="1" text="£'.$priceValue.' Membership" ]');
This is a much better solution, I wouldn't recommend trying to use shortcodes for things they weren't intended to be used for.
The ‘add_shortcode’ function does not allow you to use external variables. It operates with a local scope, so any variables declared INSIDE will be recognized, but any variables OUTSIDE will not be recognized. If you want to use an external variable you will need to use global.
Using global on your external variable will pull it within scope and allow you to use it within the add_shortcode function! :)
$greeting = "hello world!"; //external variable
function run_greeting() {
global $greeting //pulls variable within scope
echo $greeting;
}
add_shortcode( 'greeting_shortcode', 'run_greeting' );
I am brand new at writing Wordpress plugins, so to start I am trying to create a simple one that just modifies a string. I wrote the script a while ago, and know that it functions. But to use it for Wordpress I want to apply it to the post titles. When I replaced the string with the function "get_the_title()" it returns a white screen. I stripped it down to:
function display_title() {
echo get_the_title();
}
add_action('the_title', 'display_title');
This still returns a white screen. So I figure it must be the "get_the_title()" function. Can anybody explain to me why this doesn't work, and maybe a different way to retrieve the title string?
As John says the_title is a filter rather than an action hook, although your function will be called regardless of whether you register it using add_filter or add_action.
Your problem is that with filters your function is expected to return a value (normally a modified version of the argument passed). So, to modify the title using this filter you should do something like this:
function display_title($title) {
$title .= '!'; // Do something with the title string here
return $title;
}
add_filter('the_title', 'display_title');
Well, for one thing, 'the_title' isn't an action, it's a filter. So that function is never firing. So it's not the fault of that function, it is probably something else. I would suggest reading up on the plugin api and learning the difference between actions and filters. Filters are specifically designed to do what you want in a simple way:
http://codex.wordpress.org/Plugin_API/
I am writing a Wordpress plugin and need to go through a number of posts, grab the data from them (for the most part title, permalink, and content), and apply processing to them without displaying them on the page.
What I've looked at:
I've looked at get_posts() for getting the posts, and then
getting title via the_title(),
content via the_content(),
and permalink via the_permalink()
Keep in mind that I need this data after all filters had already been applied, so that I get the exact data that would be displayed to the user. Each of the functions above seems to apply all necessary filters and do some postprocessing already, which is great.
The Problem:
The problem is all these functions, at least in WP 2.7.1 (latest released version right now) by default just echo everything and don't even return anything back. the_title() actually supports a flag that says do not print and return instead, like so
the_title(null, null, false)
The other 2, however, don't have such flags, and such inconsistency is quite shocking to me.
I've looked at what each of the_() functions does and tried to pull this code out so that I can call it without displaying the data (this is a hack in my book, as the behavior of the_() functions can change at any time). This worked for permalink but for some reason get_the_content() returns NULL. There has to be a better way anyway, I believe.
So, what is the best way to pull out these values without printing them?
Some sample code
global $post;
$posts = get_posts(array('numberposts' => $limit));
foreach($posts as $post){
$title = the_title(null, null, false); // the_title() actually supports a "do not print" flag
$permalink = apply_filters('the_permalink', get_permalink()); // thanks, WP, for being so consistent in your functions - the_permalink() just prints /s
$content = apply_filters('the_content', get_the_content()); // this doesn't even work - get_the_content() returns NULL for me
print "<a href='$permalink'>$title</a><br>";
print htmlentities($content, ENT_COMPAT, "UTF-8"). "<br>";
}
P.S. I've also looked at What is the best method for creating your own Wordpress loops? and while it deals with an already obvious way to cycle through posts, the solution there just prints this data.
UPDATE: I've opened a ticket with Wordpress about this. http://core.trac.wordpress.org/ticket/9868
Most functions the_stuff() in WP that echo something have their get_the_stuff() counterpart that returns something.
Eg get_the_title(), get_permalink()...
If you can't find the exact way to do it, you can always use output buffering.
<?php
ob_start();
echo "World";
$world = ob_get_clean();
echo "Hello $world";
?>
OK, I got it all sorted now. Here is the final outcome, for whoever is interested:
Each post's data can be accessed via iterating through the array returned by get_posts(), but this data will just be whatever is in the database, without passing through any intermediate filters
The preferred way is to access data using get_the_ functions and them wrapping them in an call to apply_filters() with the appropriate filter. This way, all intermediate filters will be applied.
apply_filters('the_permalink', get_permalink())
the reason why get_the_content() was returning an empty string is that apparently a special call to setup_postdata($post); needs to be done first. Then get_the_content() returns data properly
Thanks everyone for suggestions.
Is there any reason you can't do your processing at the time each individual post is posted, or when it's being displayed?
WP plugins generally work on a single post at a time, so there are plenty of hooks for doing things that way.