execute function IF criteria is met - wordpress - php

At the moment i have a function and a filter which shortens titles if they are longer than 25characters and appends the triple dot '...'
However, it appends the dots to all the titles. How can i get the following code to run only if the title is longer than 25 characters?
function japanworm_shorten_title( $title ) {
$newTitle = substr( $title, 0, 25 ); // Only take the first 25 characters
return $newTitle . " …"; // Append the elipsis to the text (...)
}
add_filter( 'the_title', 'japanworm_shorten_title', 10, 1 );

You can use PHP's strlen: http://php.net/manual/en/function.strlen.php
Your code would go like:
function japanworm_shorten_title( $title ) {
if (strlen($title) > 25){
$title = substr( $title, 0, 25 ).'…';
}
return $title;
}
add_filter( 'the_title', 'japanworm_shorten_title', 10, 1 );

Related

Why this function is shortening also my Archive Description?

I don't understand why function below influence woocommerce_taxonomy_archive_description()
Where is connection between those two? Shouldn't this work only for woocommerce_short_description?
add_filter( 'woocommerce_short_description', 'limit_woocommerce_short_description' );
function limit_woocommerce_short_description( $post_post_excerpt ) {
if(!is_product()) { // add in conditionals
$text = $post_post_excerpt;
$words = 24; // change word length
$more = ' […]'; // add a more cta
$post_post_excerpt = wp_trim_words( $text, $words, $more );
}
return $post_post_excerpt;
}

Change Woocommerce order number to specific number of digits

I need to change the Woocommerce order number from 4 to 5 digits. I know I can a prefix or suffix with this
add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number', 1, 2);
function change_woocommerce_order_number( $order_id, $order ) {
$prefix = 'WC';
$suffix = '-XY';
return $prefix . $order->id . $suffix;
}
But how can I change the number of digits?
Use str_pad() PHP function as follows:
add_filter( 'woocommerce_order_number', 'customize_order_number', 10, 2 );
function customize_order_number( $order_id, $order ) {
$digits = 5;
$prefix = '';
$suffix = '';
return $prefix . str_pad($order_id, $digits, '0', STR_PAD_LEFT) . $suffix;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Related: Formatting a number with leading zeros in PHP

How would one limit the Manual Excerpt Length in WP?

One can control the WP default (Automatic) excerpt length of a WP post using the using the following snippet within functions.php;
From the WP Codex
// . Post excerpt adjustment (Auto)
// . ==============================
function wpdocs_custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );
My question is how do you limit the manual one?
You know, the exerpt specifically added by the user themselves?
(*) There is an 8 year old question here, that does provide some context but given the current year and progress WP has made I want to post the question again and receive some clarity on the subject.
Added Context: (Edited: 12 March 2019)
It's not that the original answer to the question posted earlier doesn't work, all be it seems, really clunky. I'm looking for a more simple & robust answer using exerpt_length filter. Rather than using something like the following to trim the text; (If Possible)
function excerpt($limit) {
return wp_trim_words(get_the_excerpt(), $limit);
}
We have by default in core, the following filtering:
add_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
but within wp_trim_excerpt() the trimming is only applied on the post's content, when there's no manual excerpt set.
Here's an untested suggestion for a custom filtering:
add_filter( 'get_the_excerpt', function( $excerpt, $post ) {
if ( has_excerpt( $post ) ) {
$excerpt_length = apply_filters( 'excerpt_length', 55 );
$excerpt_more = apply_filters( 'excerpt_more', ' ' . '[…]' );
$excerpt = wp_trim_words( $excerpt, $excerpt_length, $excerpt_more );
}
return $excerpt;
}, 10, 2 );
to apply the similar trimming on manual excerpts.
Hope you can adjust this further to your needs.
Try this, I got this code from here: https://www.wpexplorer.com/wordpress-excerpt-length/
add_filter( 'excerpt_length', function($length) {
return 20;
} );
This pair of functions will give you control over the excerpt length, including the manual excerpt which is returned if available, otherwise the "excerpt-ized" post_content gets returned. These go in your theme functions file:
function get_excerpt_by_id($post_id, $length = NULL) {
$length = isset($length) ? $length : apply_filters('excerpt_length', 32);
$p = get_post($post_id);
return $p->post_excerpt ? build_excerpt_by_length($p->post_excerpt, $length) : build_excerpt_by_length($p->post_content, $length);
}
function build_excerpt_by_length($content, $length = 32) {
$excerpt = strip_tags(strip_shortcodes($content));
$words = explode(' ', $excerpt, $length + 1);
$words = array_slice($words, 0, $length);
$result = trim(implode(' ', $words));
$result = preg_replace('/\W*$/', '', $result);
$more = apply_filters('excerpt_more', '…');
if ($result !== '') $result = $content === $result ? $result : $result . $more;
return $result;
}
Then in your templates you can use by calling:
get_excerpt_by_id($your_post_id, $preferred_excerpt_length);
You can try the following code
$excerpt = get_the_excerpt();
$excerpt = substr( $excerpt, 0, 180 );
$excerpt_description = substr( $excerpt, 0, strrpos( $excerpt, ' ' ) );
echo $excerpt_description;

How to truncate characters in product description with WooCommerce

I have found out how to add a short description to the thumbnails for products in WooCommerce, but how do I truncate them to a certain length, say 30 characters.
All the answers to do with editing the functions.php file dont mention where in the file to put the code.
My code in my functions.php file is:
add_action('woocommerce_after_shop_loop_item_title','add_title_description',9);
function add_title_description(){
echo get_post_meta($product->id, 'title-description', true)? '<span class="title-description">' . get_post_meta($product->id, 'title-description', true) . '</span><br />' : '';
}
use substr()
add_action('woocommerce_after_shop_loop_item_title','add_title_description',9);
function add_title_description()
{
$titleDescription = get_post_meta($product->id, 'title-description', true);
if( !empty($titleDescription) )
{
if( strlen($titleDescription) > 30 )
$titleDescription = substr($titleDescription, 30);
printf('<span class="title-description">%s</span><br />', $titleDescription);
}
}
My implementation grabbing the first 2 sentences instead of a character count.
/**
* Echo Truncated String
*
* #param string $string
* #return string
*/
function add_title_description( $titleDescription ) {
global $product;
$titleDescription = get_post_meta( $product->id, 'title-description', true );
// combine first 2 sentences
$sentence = preg_split( '/(\.|!|\?)\s/', $titleDescription, 3, PREG_SPLIT_DELIM_CAPTURE );
echo $titleDescription ? '<span class="title-description">' . $sentence[0] . $sentence[3] . '</span><br />' : '';
}
add_action( 'woocommerce_after_shop_loop_item_title', 'add_title_description', 4, 1 );
I added this:
function wcs_excerpt_length( $length ) {
return 15;
}
add_filter( 'product_description_length', 'wcs_excerpt_length' );

Characters being replaced by bbcode plugin

I have a bbcode plugin for wordpress.
But for some reason, if I post something like
[i]v497212he2x2MfMi[/i] the "X" character is outputted as ×, which is some other sort of X. How can I fix this?
Plugin code is below:
class BBCode {
// Plugin initialization
function BBCode() {
// This version only supports WP 2.5+ (learn to upgrade please!)
if ( !function_exists('add_shortcode') ) return;
// Register the shortcodes
add_shortcode( 'b' , array(&$this, 'shortcode_bold') );
add_shortcode( 'i' , array(&$this, 'shortcode_italics') );
}
// No-name attribute fixing
function attributefix( $atts = array() ) {
if ( empty($atts[0]) ) return $atts;
if ( 0 !== preg_match( '#=("|\')(.*?)("|\')#', $atts[0], $match ) )
$atts[0] = $match[2];
return $atts;
}
// Bold shortcode
function shortcode_bold( $atts = array(), $content = NULL ) {
if ( NULL === $content ) return '';
return '<strong>' . do_shortcode( $content ) . '</strong>';
}
// Italics shortcode
function shortcode_italics( $atts = array(), $content = NULL ) {
if ( NULL === $content ) return '';
return '<em>' . do_shortcode( $content ) . '</em>';
}
}
// Start this plugin once all other plugins are fully loaded
add_action( 'plugins_loaded', create_function( '', 'global $BBCode; $BBCode = new BBCode();' ) );
This transformation is taking place because of Wordpress's wptexturize() function that returns given text with transformations of quotes to smart quotes, apostrophes, dashes, ellipses, the trademark symbol, and the multiplication symbol.
This is from WP 3.2.1 wp-includes/formatting.php line 55:
$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/\'(\d)/', '/(\s|\A|[([{<]|")\'/', '/(\d)"/', '/(\d)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/\b(\d+)x(\d+)\b/');
$dynamic_replacements = array('’$1','’$1', '$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');
The last regex in that $dynamic_characters array is the one turning the "X" into ×
As stated on the function page for wptexturize... "[t]ext enclosed in the tags <pre>, <code>, <kbd>, <style>, <script>, <tt>, and [code] will be skipped.", you can fix this by putting that bbcode in one of those tags, or use a plugin that can disable wptexturize, such as InScript or Disabler or Disable wptexturize.

Categories