Wordpress + Divi theme: control excerpt length based on category? - wordpress

I have a category called 'News'. The category ID is '20'. I am using the Divi (Divi child) theme + Wordpress and want to shorten the excerpt for the News category.
I typically would use the 'add_filter' function like this:
<pre>
add_filter('excerpt_length', 'news_excerpt_length');
function news_excerpt_length($length) {
if(in_category(20)) {
return 30;
} else {
return 60;
}
}
</pre>
But that ain't workin'. I found the excerpt control in the 'main-modules.php' and figure to add my filter here? Has anyone done this?
I added the 'main-module.php' to the root of my child theme and then added this to my child 'functions.php'
<pre>
if ( ! function_exists( 'et_builder_add_main_elements' ) ) :
function et_builder_add_main_elements() {
require ET_BUILDER_DIR . 'main-structure-elements.php';
require 'main-modules.php';
do_action( 'et_builder_ready' );
}
endif;
</pre>
It didn't break the theme, but it didn't work either. Does anyone have any experience with this particular issue?
-Thanks!

To override the post_excerpt lengh, you can find in custom_functions.php the function truncate_post()
if ( ! function_exists( 'truncate_post' ) ) {
function truncate_post( $amount, $echo = true, $post = '', $strip_shortcodes = false ) {
global $shortname;
if ( '' == $post ) global $post;
$post_excerpt = '';
$post_excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
if ( 'on' == et_get_option( $shortname . '_use_excerpt' ) && '' != $post_excerpt ) {
if ( $echo ) echo $post_excerpt;
else return $post_excerpt;
} else {
// get the post content
$truncate = $post->post_content;
// remove caption shortcode from the post content
$truncate = preg_replace( '#\[caption[^\]]*?\].*?\[\/caption]#si', '', $truncate );
// remove post nav shortcode from the post content
$truncate = preg_replace( '#\[et_pb_post_nav[^\]]*?\].*?\[\/et_pb_post_nav]#si', '', $truncate );
// Remove audio shortcode from post content to prevent unwanted audio file on the excerpt
// due to unparsed audio shortcode
$truncate = preg_replace( '#\[audio[^\]]*?\].*?\[\/audio]#si', '', $truncate );
if ( $strip_shortcodes ) {
$truncate = et_strip_shortcodes( $truncate );
} else {
// apply content filters
$truncate = apply_filters( 'the_content', $truncate );
}
// decide if we need to append dots at the end of the string
if ( strlen( $truncate ) <= $amount ) {
$echo_out = '';
} else {
$echo_out = '...';
// $amount = $amount - 3;
}
// trim text to a certain number of characters, also remove spaces from the end of a string ( space counts as a character )
$truncate = rtrim( et_wp_trim_words( $truncate, $amount, '' ) );
// remove the last word to make sure we display all words correctly
if ( '' != $echo_out ) {
$new_words_array = (array) explode( ' ', $truncate );
array_pop( $new_words_array );
$truncate = implode( ' ', $new_words_array );
// append dots to the end of the string
$truncate .= $echo_out;
}
if ( $echo ) echo $truncate;
else return $truncate;
};
}
}
You don't need to put if ( ! function_exists( 'truncate_post' ) ) { to make it work just create your function with the same name in functions.php
If you are using a child theme (I really hope so with a theme like this), copy/paste index.php and paste these lines, line 54
if(in_category(20)) {
truncate_post( 30 );
} else {
truncate_post( 60 );
}
It can be easier
Hope it helps

I ended up doing it ( although I don't know which solution is better ) by putting this in my 'main-module.php' starting on line 12319
// do not display the content if it contains Blog, Post Slider, Fullwidth Post Slider, or Portfolio modules to avoid infinite loops
if ( ! has_shortcode( $post_content, 'et_pb_blog' ) && ! has_shortcode( $post_content, 'et_pb_portfolio' ) && ! has_shortcode( $post_content, 'et_pb_post_slider' ) && ! has_shortcode( $post_content, 'et_pb_fullwidth_post_slider' ) ) {
if ( 'on' === $show_content ) {
global $more;
// page builder doesn't support more tag, so display the_content() in case of post made with page builder
if ( et_pb_is_pagebuilder_used( get_the_ID() ) ) {
$more = 1;
the_content();
} else {
$more = null;
the_content( esc_html__( 'read more...', 'et_builder' ) );
}
} else {
if ( has_excerpt() ) {
the_excerpt();
} else {
if(in_category(20)) {
echo wpautop( truncate_post( 70, false ) );
} else {
echo wpautop( truncate_post( 370, false ) );
}
}
}
} else if ( has_excerpt() ) {
the_excerpt();
}

Related

Remove Yoast Breadcrumb Last Item On Single Pages Only

i got this code from researching and trying to modify it but no luck. I want the last item in yoast breamcrumbs not to appear on single pages only
if ( is_single() ) {
/*Remove Last item in Yoast SEO Breadcrumb */
function adjust_single_breadcrumb( $link_output) {
if(strpos( $link_output, 'breadcrumb_last' ) !== false ) {
$link_output = '';
}
return $link_output;
}
add_filter('wpseo_breadcrumb_single_link', 'adjust_single_breadcrumb' );
};
I tried adding if is single in between the function and also this
if(strpos( $link_output, 'breadcrumb_last' ) !== false && is_single) {
unfortunately, the whole breadcrumb disappears.
with this code, you can remove post title in single page.
add_filter('wpseo_breadcrumb_single_link_info', 'remove_post_title_wpseo_breadcrumb', 10, 3);
function remove_post_title_wpseo_breadcrumb($link_info, $index, $crumbs)
{
if (is_singular() && isset($link_info['id']))
return [];
return $link_info;
}
Updated: In the latest version above code does not work perfectly.
for this reason, I removed the last item with regex:
function getBreadcrumb() {
if ( function_exists( 'yoast_breadcrumb' ) ) {
ob_start();
yoast_breadcrumb( '<p id="breadcrumb" class="meta-info">', '</p>' );
$breadcrumb = trim( ob_get_clean() );
if ( is_singular() )
$breadcrumb = trim( preg_replace( '/ ' . WPSEO_Options::get( 'breadcrumbs-sep' ) . ' <span class="breadcrumb_last" aria-current="page">(.*)<\/span>/i', '',
$breadcrumb ) );
echo $breadcrumb;
}
}
And call the function anywhere you want:
<?php getBreadcrumb() ?>

Using if template equals in a WordPress function

I am working with this function:
if ( $id && $post && $post->post_type == 'business-areas' )
{
$pieces = explode(' ', $the_title);
$last_word = trim(strtolower(array_pop($pieces)));
if($last_word != 'jobs')
{
$the_title = $the_title . ' jobs';
}
}
return $the_title;
This is basically appending the word JOBS to any titles on a custom post type of business-areas if the last word of the title is not JOBS.
Is there a way to add a template query to this?
So basically, if the page template of the custom post is DEFAULT, do this, if the page template is not DEFAULT, don't do it.
Put this code in the functions.php file.
function add_label_to_post_title( $the_title = '' ) {
global $post;
if ($post && $post->post_type == 'business-areas' )
{
$pieces = explode(' ', $the_title);
$last_word = trim(strtolower(array_pop($pieces)));
if($last_word != 'jobs')
{
$the_title = $the_title . ' jobs';
}
}
return $the_title;
}
add_filter( 'the_title', 'add_label_to_post_title' );

Wordpress Excerpt Character Limit On Theme wpexplorer Today Theme

I need help for fixing http://wpexplorer-demos.com/today/page/2/ today theme.
frontpage Boxes takes random sizes. How i fix it from words to characters. Also images. any help plz really appreciated. I am not a coder.
/**
* Custom excerpts based on wp_trim_words
* Created for child-theming purposes
*
* #link http://codex.wordpress.org/Function_Reference/wp_trim_words
* #since 1.0.0
*/
function wpex_excerpt( $length = 45, $readmore = false ) {
// Get global post data
global $post;
// Check for custom excerpt
if ( has_excerpt( $post->ID ) ) {
$output = $post->post_excerpt;
}
// No custom excerpt...so lets generate one
else {
// Redmore text
$readmore_text = get_theme_mod( 'entry_readmore_text', esc_html__( 'read more', 'today' ) );
// Readmore link
$readmore_link = ''. $readmore_text .'<span class="wpex-readmore-rarr">→</span>';
// Check for more tag and return content if it exists
if ( strpos( $post->post_content, '<!--more-->' ) ) {
$output = get_the_content( '' );
}
// No more tag defined so generate excerpt using wp_trim_words
else {
// Generate excerpt
$output = wp_trim_words( strip_shortcodes( get_the_content( $post->ID ) ), $length );
// Add readmore to excerpt if enabled
if ( $readmore == true ) {
$output .= apply_filters( 'wpex_readmore_link', $readmore_link );
}
}
}
// Apply filters and echo
echo apply_filters( 'wpex_excerpt', $output );
}
I've edited it for you:
**
* Custom excerpts based on wp_trim_words
* Created for child-theming purposes
*
* #link http://codex.wordpress.org/Function_Reference/wp_trim_words
* #since 1.0.0
*/
function wpex_excerpt( $length = 45, $readmore = false ) {
// Get global post data
global $post;
$max_characters = 40;
// Check for custom excerpt
if ( has_excerpt( $post->ID ) ) {
$output = mb_strimwidth($post->post_excerpt, 0, $max_characters, '...');
}
// No custom excerpt...so lets generate one
else {
// Redmore text
$readmore_text = get_theme_mod( 'entry_readmore_text', esc_html__( 'read more', 'today' ) );
// Readmore link
$readmore_link = ''. $readmore_text .'<span class="wpex-readmore-rarr">→</span>';
// Check for more tag and return content if it exists
if ( strpos( $post->post_content, '<!--more-->' ) ) {
$output = mb_strimwidth(get_the_content( '' ), 0, $max_characters, '...');
}
// No more tag defined so generate excerpt using wp_trim_words
else {
// Generate excerpt
$output_to_trim = wp_trim_words( strip_shortcodes( get_the_content( $post->ID ) ), $length );
$output = mb_strimwidth($output_to_trim, 0, $max_characters, '...');
// Add readmore to excerpt if enabled
if ( $readmore == true ) {
$output .= apply_filters( 'wpex_readmore_link', $readmore_link );
}
}
}
// Apply filters and echo
echo apply_filters( 'wpex_excerpt', $output );
}
You can change the maximum of characters in this code by changing number in $max_characters variable.
I used mb_strimwidth() function and return it to $output variable: https://secure.php.net/manual/pl/function.mb-strimwidth.php
By example you should understand what's going on:
<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// outputs Hello W...
?>
The function needs string like "Hello World", start of string (like 0), maximum number of characters (like 10) and at the end you can optionally choose nice ending of excerpt (like ...).

Place ads before last paragraph in wordpress

Here is the code for place ads after 1st, 2nd, 3d paragraph. but i want to place ad just before last paragraph of my wordpress post. is there any way to do this ?
<?php
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 1, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
?>
add_filter('the_content', 'ad_signal');
function ad_signal($content)
{
if (!is_single()) return $content;
$tent = get_the_content();
$content = explode("</p>", $content);
$ss = count($content);
$ns = $ss-1; //**before last paragraph in wordpress **
$new_content = '';
for ($i = 0; $i < count($content); $i++) {
if ($i == $ns ) {
$new_content.= ' <div style="text-align:center;">';
$new_content.= '<h1> Your ads Here ! </h1>';
$new_content.= '</div>';
}
$new_content.= $content[$i] . "</p>";
}
return $new_content;
}
I have set Adsense code by this Code in my sites named All BD Results and etunescafe. You just add this code in your sites functions.php N.B. Before adding the code please replace your or add your adsense code. It will be good enough to go through this post. How to Set Adsense Ads Right Before The Last Paragraph
function ads_added_above_last_p($text) {
if( is_single() ) :
$ads_text = '<div class="a" style="text-align: center;">Your Adsense Code</div>';
if($pos1 = strrpos($text, '<p>')){
$text1 = substr($text, 0, $pos1);
$text2 = substr($text, $pos1);
$text = $text1 . $ads_text . $text2;
}
endif;
return $text;
}
add_filter('the_content', 'ads_added_above_last_p');
Hey guys so I ran into the same problem and managed to solve it incorporating your answers into one.
The function that does all the processing is changed so that is counts all the paragraphs created by the explode method. Then another if statement is added to evaluate when you are at the desired location.
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
$last_paragraph_index = count($paragraphs);
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
else if( $last_paragraph_index + $paragraph_id == $index + 1){
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
in order to use the new functionality you must call it with a negative number.
Think of the function this way, if you want to go from the top of the content you use a positive number, if you want to go from the bottom of the content you use a negative number.
Remember that even though the evaluation is for your decided spot such as before the last paragraph the condition that adds to the array uses the index which we all know is zero based.
This just means that to get after paragraph 1 you must use the number 2 when calling the function and to get to before the last paragraph you have to use -2 and so on.
Here is my example to add the a read the next post if it exists to the article
add_filter( 'the_content', 'prefix_insert_next_article_banner' );
function prefix_insert_next_article_banner( $content ) {
if ( is_single() && ! is_admin() && get_next_post_link() ) {
$next_banner = '<div class="next-banner"> <span> Read Next </span>';
$next_banner .= ' ' . get_the_title(get_adjacent_post(false,'',false)) .' ';
$next_banner .= '</div>';
return prefix_insert_after_paragraph( $next_banner, -2, $content );
}
return $content;
}

Wordpress remove shortcode and save for use elsewhere

Trying to remove the gallery shortcode from the post content and save in a variable for use elsewhere in the template. The new Wordpress gallery tool is great for selecting which images they want and assigning captions, hoping to use this to create the gallery, but then pull it out of the content on the front-end.
So this little snipped works just fine for removing the gallery and reapplying formatting... however I want to save that gallery shortcode.
$content = strip_shortcodes( get_the_content() );
$content = apply_filters('the_content', $content);
echo $content;
Hoping to save the shortcode so it can be parsed into an array and used to recreate a custom gallery setup on the front-end. An example of this shortcode I'm trying to save is...
[gallery ids="1079,1073,1074,1075,1078"]
Any suggestions would be greatly appreciated.
Function to grab First Gallery shortcode from post content:
// Return first gallery shortcode
function get_shortcode_gallery ( $post = 0 ) {
if ( $post = get_post($post) ) {
$post_gallery = get_post_gallery($post, false);
if ( ! empty($post_gallery) ) {
$shortcode = "[gallery";
foreach ( $post_gallery as $att => $val ) {
if ( $att !== 'src') {
if ( $att === 'size') $val = "full"; // Set custom attribute value
$shortcode .= " ". $att .'="'. $val .'"'; // Add attribute name and value ( attribute="value")
}
}
$shortcode .= "]";
return $shortcode;
}
}
}
// Example of how to use:
echo do_shortcode( get_shortcode_gallery() );
Function to delete First gallery shortcode from Post content:
// Deletes first gallery shortcode and returns content
function strip_shortcode_gallery( $content ) {
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if ( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$pos = strpos( $content, $shortcode[0] );
if ($pos !== false)
return substr_replace( $content, '', $pos, strlen($shortcode[0]) );
}
}
}
return $content;
}
// Example of how to use:
$content = strip_shortcode_gallery( get_the_content() ); // Delete first gallery shortcode from post content
$content = str_replace( ']]>', ']]>', apply_filters( 'the_content', $content ) ); // Apply filter to achieve the same output that the_content() returns
echo $content;
just use the get_shortcode_regex():
<?php
$pattern = get_shortcode_regex();
preg_match_all('/'.$pattern.'/s', $post->post_content, $shortcodes);
?>
that will return an array of all the shortcodes in your content, which you can then output wherever you feel, like so:
<?php
echo do_shortcode($shortcodes[0][1]);
?>
similarly, you could use the array entries to check for shortcodes in your content and remove them with str_replace():
<?php
$content = $post->post_content;
$content = str_replace($shortcodes[0][1],'',$content);
?>
Something like $gallery = do_shortcode('[gallery]'); might work.

Resources