Functions.php to set all external links with rel:="nofollow" - wordpress

when i use the code:
add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');
function my_nofollow($content) {
return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}
function my_nofollow_callback($matches) {
$link = $matches[0];
$site_link = get_bloginfo('url');
if (strpos($link, 'rel') === false) {
$link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
} elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
$link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
}
return $link;
}
only in the_content and the_excerpt the links get a nofollow attribute. How i can edit the code, that the whole wordpress site use this functions (footer, sidebar...)
Thank you

a good script which allows to add nofollow automatically and to keep the other attributes
function nofollow(string $html, string $baseUrl = null) {
return preg_replace_callback(
'#<a([^>]*)>(.+)</a>#isU', function ($mach) use ($baseUrl) {
list ($a, $attr, $text) = $mach;
if (preg_match('#href=["\']([^"\']*)["\']#', $attr, $url)) {
$url = $url[1];
if (is_null($baseUrl) || !str_starts_with($url, $baseUrl)) {
if (preg_match('#rel=["\']([^"\']*)["\']#', $attr, $rel)) {
$relAttr = $rel[0];
$rel = $rel[1];
}
$rel = 'rel="' . ($rel ? (strpos($rel, 'nofollow') ? $rel : $rel . ' nofollow') : 'nofollow') . '"';
$attr = isset($relAttr) ? str_replace($relAttr, $rel, $attr) : $attr . ' ' . $rel;
$a = '<a ' . $attr . '>' . $text . '</a>';
}
}
return $a;
},
$html
);
}

The idea is to add your action in the full html buffer, once everything is loaded and filtered, not only in the 'content' area.
BE VERRY CAREFULL WITH THIS !!!! This action is verry RAW and low-level... You can really mess up everything with theses buffer actions. But it's also very nice to know ;-)
It works like this :
add_action( 'wp_loaded', 'buffer_start' ); function buffer_start() { ob_start( "textdomain_nofollow" ); }
add_action( 'shutdown', 'buffer_end' ); function buffer_end() { ob_end_flush(); }
Then do the replace action and setup the callback :
Juste imagine the $buffer variable as your full site in HTML, as it will load.
function textdomain_nofollow( $buffer ) {
return preg_replace_callback( '/<a[^>]+/', 'textdomain_nofollow_callback', $buffer );
}
Here is how I do the href checking (read my comments) :
function textdomain_nofollow_callback( $matches ) {
$link = $matches[0];
// if you need some specific external domains to exclude, just use :
//$exclude = '('. home_url() .'|(http|https)://([^.]+\.)?(domain-to-exclude.org|other-domain-to-exclude.com)|/)';
// By default, just exclude your own domain, and your relative urls that starts by a '/' (if you use relatives urls)
$exclude = '('. home_url() .'|/)';
if ( preg_match( '#href=\S('. $exclude .')#i', $link ) )
return $link;
if ( strpos( $link, 'rel=' ) === false ) {
$link = preg_replace( '/(?<=<a\s)/', 'rel="nofollow" ', $link );
} elseif ( preg_match( '#rel=\S(?!nofollow)#i', $link ) ) {
$link = preg_replace( '#(?<=rel=.)#', 'nofollow ', $link );
}
return $link;
}
It works well in my experience...
Q

Related

How to add a custom attribute?

How to add a custom attribute in the field Contact Form 7 without javascript ?
For example, there is such a field on the page:
<input type="text" name="name" class="form-control" id="name-1" data-attr="custom" data-msg="Текст 1">
Question: is it possible to set these custom attributes (data-attr, data-msg) of fields in the admin panel?
Find the name of your field.
[text* text-21]
If the name of your field name="text-21", like in my example, add this code to functions.php file.
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="text-21"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
Note, it will add those attributes to all forms elements where the name is text-21, if you want prevent it then give your form element some unique name [text* unique-name]
And change the code to
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="unique-name"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
Here is a generic solution that doesn't involve hardcoding the field name and the attributes
add_filter( 'wpcf7_form_tag', function ( $tag ) {
$datas = [];
foreach ( (array)$tag['options'] as $option ) {
if ( strpos( $option, 'data-' ) === 0 ) {
$option = explode( ':', $option, 2 );
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if ( ! empty( $datas ) ) {
$id = uniqid('tmp-wpcf');
$tag['options'][] = "class:$id";
add_filter( 'wpcf7_form_elements', function ($content) use ($id, $datas) {
return str_replace($id, $name, str_replace($id.'"', '"'. wpcf7_format_atts($datas), $content));
});
}
return $tag;
} );
It works on all data attributes so you can use it like this
[text* my-name data-foo:bar data-biz:baz placeholder "Blabla"]
Output: <input type="text" name="my-name" data-foo="bar" data-biz="baz" placeholder="Blabla">
Since wpcf7 doesn't provide a way to hook into options directly the solutions uses a trick and temporary adds a uniquely generated class to the field that is then replaced in a later filter with the added attributes
If you need it to work with more than just data attributes you can whitelist some more attributes by replacing this line
if ( strpos( $option, 'data-' ) === 0 ) {
to something like the following
if ( preg_match( '/^(data-|pattern|my-custom-attribute)/', $option ) ) {
Note: wpcf7_format_atts will not output empty attributes, so make sure you give a value to your attributes
Multiple attributes can be added also. eg
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="your-email-homepage"' );
$content = substr_replace( $content, ' aria-describedby="emailHelp" ', $str_pos, 0 );
$str_pos2 = strpos( $content, 'name="your-fname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="fnameHelp" ', $str_pos2, 0 );
$str_pos3 = strpos( $content, 'name="your-lname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="lnameHelp" ', $str_pos3, 0 );
return $content;
}
Extending on from Tofandel's solution, for the benefit of those who got 99% of the way there, but suffered validation issues - I've resolved that in my case and would like to offer an extended solution that gets as far as Tofandel's (putting the attribute into the form proper) but also successfully validates on submission.
add_filter('wpcf7_form_tag', function($tag) {
$data = [];
foreach ((array)$tag['options'] as $option) {
if (strpos( $option, 'autocomplete') === 0) {
$option = explode(':', $option, 2);
$data[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if(!empty($data)) {
add_filter('wpcf7_form_elements', function ($content) use ($tag, $data) {
$data_attrs = wpcf7_format_atts($data);
$name = $tag['name'];
$content_plus_data_attrs = str_replace("name=\"$name\"", "name=\"$name\" " . $data_attrs, $content);
return $content_plus_data_attrs;
});
}
return $tag;
} );
Rather than changing the tag ID to a random value only to replace it with the "real" value later, we just reference the real value in the first place, replacing the relevant part of the content in the wpcf7_form_elements filter (in my case, autocomplete, but as Tofandel's example shows, this can be extended to any data attribute you'd like).
I propose a solution from the one given by Tofandel without JS (CF7) error and to authorize the use of an attribute without value:
/**
* Add custom attributes on inputs
* Put "data-my-attribute" to use it, with or without value
*
* #param array $tag
*
* #return array
*/
function cf7AddCustomAttributes($tag) {
$datas = [];
foreach ((array) $tag['options'] as $option) {
if (strpos($option, 'data-') === 0 || strpos($option, 'id:') === 0) {
$option = explode(':', $option, 2);
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if (!empty($datas)) {
$id = $tag['name'];
if (array_key_exists('id', $datas)) {
$id = $datas['id'];
} else {
$tag['options'][] = "id:$id";
}
add_filter('wpcf7_form_elements', function ($content) use ($id, $datas) {
$attributesHtml = '';
$idHtml = "id=\"$id\"";
foreach ($datas as $key => $value) {
$attributesHtml .= " $key";
if (is_string($value) && strlen($value) > 0) {
$attributesHtml .= "=\"$value\"";
}
}
return str_replace($idHtml, "$idHtml $attributesHtml ", $content);
});
}
return $tag;
}
add_filter('wpcf7_form_tag', 'cf7AddCustomAttributes');
I use this simple method for setting attribute
[checkbox optName use_label_element "optName"]
<script>
document.querySelector(".optName").setAttribute("onchange","myscript");
</script>

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

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();
}

Rename file while uploading?

I have the following code in my Wordpress. I need to add every uploaded image a counting number like, image_1, image_2, image_3 and so on..
The purpose of this is that every uploaded image attached to post, gets post ID name, and counting number in end to it.
It would be great if some one help me with this. Thanks!
<?php
add_filter('wp_handle_upload_prefilter', 'wpse_25894_handle_upload_prefilter');
add_filter('wp_handle_upload', 'wpse_25894_handle_upload');
function wpse_25894_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $file;
}
function wpse_25894_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $fileinfo;
}
function wpse_25894_custom_upload_dir($path)
{
/*
* Determines if uploading from inside a post/page/cpt - if not, default Upload folder is used
*/
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path; //error or uploading not from a post/page/cpt
/*
* Save uploads in ID based folders
*
*/
$customdir = '/' . $_REQUEST['post_id'];
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( 'image_make_intermediate_size', 'wpse_123240_rename_intermediates' );
function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Build our new image name
$postid = $_REQUEST['post_id'];
$random = rand(1,5);
$new_name = $dir . $postid . '_' . $random . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
?>
Now this code generates images named postid_randomnumber.jpg
I just need to add 20 images at maximum, so if I can have numbers from 1-20, that is also working fine with my purposes.
-- UPDATE --
I canged the last part of code to this, it is not maybe the cleanest solution, but it works:
function wpse_123240_rename_intermediates( $image )
{
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
//$count = get_option( 'wpa59168_counter', 1 );
// Build our new image name
$postid = $_REQUEST['post_id'];
$increment = 1;
$new_name = $dir . $postid . '_1' . $ext;
while(is_file($new_name)) {
$increment++;
$new_name = $dir . $postid . '_' . $increment . $ext;
}
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}

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;
}

how to customize wordpress internal functions, like adjacent_post_link()

I need to customize the previous_post_link() and next_post_link() on WordPress.
Per example, I want to shrink permalinks like "Top 5 programming languages that you need to learn" to "Top 5 programing...".
The function responsible for creating the link isadjacent_post_link() located at wp-includes/link-template.php
To create a custom adjacent link for posts I can make use of the filter hook next_post_link and previos_post_link;
In the functions.php:
function shrink_previous_post_link($format, $link){
$in_same_cat = false;
$excluded_categories = '';
$previous = true;
$link='%title';
$format='« %link';
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);
if ( !$post )
return;
$title = $post->post_title;
if ( empty($post->post_title) )
$title = $previous ? __('Previous Post') : __('Next Post');
$rel = $previous ? 'prev' : 'next';
//Save the original title
$original_title = $title;
//create short title, if needed
if (strlen($title)>40){
$first_part = substr($title, 0, 23);
$last_part = substr($title, -17);
$title = $first_part."...".$last_part;
}
$string = '<a href="'.get_permalink($post).'" rel="'.$rel.'" title="'.$original_title.'">';
$link = str_replace('%title', $title, $link);
$link = $string . $link . '</a>';
$format = str_replace('%link', $link, $format);
echo $format;
}
function shrink_next_post_link($format, $link){
$in_same_cat = false;
$excluded_categories = '';
$previous = false;
$link='%title';
$format='%link »';
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);
if ( !$post )
return;
$title = $post->post_title;
if ( empty($post->post_title) )
$title = $previous ? __('Previous Post') : __('Next Post');
$rel = $previous ? 'prev' : 'next';
//Save the original title
$original_title = $title;
//create short title, if needed
if (strlen($title)>40){
$first_part = substr($title, 0, 23);
$last_part = substr($title, -17);
$title = $first_part."...".$last_part;
}
$string = '<a href="'.get_permalink($post).'" rel="'.$rel.'" title="'.$original_title.'">';
$link = str_replace('%title', $title, $link);
$link = $string . $link . '</a>';
$format = str_replace('%link', $link, $format);
echo $format;
}
add_filter('next_post_link', 'shrink_next_post_link',10,2);
add_filter('previous_post_link', 'shrink_previous_post_link',10,2);
That all I needed to do. Thanks!
the next_post_link() and previous_post_link() function both come with customization options. http://codex.wordpress.org/Function_Reference/next_post_link. After reading that and learning what the acceptable arguments to the function are, Test to see if it is possible to pass a php function to the option, like substr().
<?php next_post_link('%link',substr('%title',20),FALSE);?>
'%link' and '%title' are shortcodes to the post link and title.
Let us know if it works out.

Resources