I'm creating a shortcode that outputs the javascript code to create a customized Google Map, like this:
[map w="600" h="400" style="full" z="16" marker="yes" infowindow="<h2>Title</h2>" address="New York"]
Here are some extracts of the code:
function gmap($atts) {
$atts = shortcode_atts(array(
[...]
'infowindow' => '',
[...]
'style' => ''
), $atts);
[...]
//infowindow
if($atts['infowindow'] != '')
{
$thiscontent = htmlspecialchars_decode($atts['infowindow']);
$returncode .= '
var contentString = \'' . $thiscontent . '\';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
';
}
[...]
return $returncode;
}
Everything is fine if in "infowindow" I only use text, but if I use markup, like <h2>Title</h2> what I get in the code is:
var contentString = '<br />
<h2>Title</h2>
<p>';
... with two newlines that mess up the js.
Can anybody help me?
Thanks a lot!
Looks like you're getting screwed over by WordPress's automatic paragraph formatting.
Option 1: Sometimes you can get around this by switching to the html tab of the editor, then removing any whitespace in your markup, but this also has a tendency to fall apart next time you edit the same page/post.
Option 2: Disable wpautop in your theme's functions.php:
remove_filter( 'the_content', 'wpautop' );
However, this might screw up your content elsewhere on your site.
Option 3. Use yet another plugin, to toggle wpautop on or off of specific pages: https://wordpress.org/plugins/toggle-wpautop/
Option 4. Add some more shortcode attributes, then apply the required html via PHP, so you don't have to deal with this!
Related
I am using ACF, and using TinyMCE Advanced plugin.
When editing posts, the editor inserts new links into p tags, which I am trying to prevent as I am using the code tag and if there is a return within the code within the code tag, it wraps it in a new p and code block that then breaks the layout of the post.
I have tried playing with the plugin settings to check to remove the p tags, however no luck.
I have searched and found that I should be setting forced root block to false, however I am still unable to get it to work:
add_filter('tiny_mce_before_init', function ($init) {
//Prevent <p> tags in editor
$init['forced_root_block'] = false;
$init['force_br_newlines'] = false;
$init['force_p_newlines'] = false;
$init['convert_newlines_to_brs'] = false;
return $init;
});
When viewing the post in Text tab, the code shows no P tags, however when editing within the visual tab, its breaking it all out into p tags.
Any ideas on how to resolve?
When you output the content, while in a loop, you can sanitize the output to remove any and all tags using wp_strip_all_tags.
Properly strip all HTML tags including script and style.
<?php wp_strip_all_tags( the_content(), true ); ?>
(true or false for line breaks). Same thing for ACF, just englobe the output in it.
Source # https://developer.wordpress.org/reference/functions/wp_strip_all_tags/
Alternatively, you can remove any auto <p> tag applied as line break by removing the wpautop via remove_filter in your function.php file.
<?php remove_filter( 'the_content', 'wpautop' ); ?>
And with an ACF editor WYSIWYG/TinyMCE
<?php remove_filter ( 'acf_the_content', 'wpautop' ); ?>
It seems that wordpress is creating empty p tags for no reason whatso ever. I usually correct this problem by getting rid of all white space - as white space seems to be interpreted as "P TAG HERE! PLACE A P TAG HERE".
Here is my Wordpress dashboard content that I am concerned with:
[block]<p>This is a test</p>[/block]
As you can see there is no whitespace.
Here is the HTML Representation of that same piece of html.
<div class="block sidebar">
<p>This is a test</p>
<p></p></div>
See that second <p></p> that is there for no reason?
Can someone please tell me why this happens and how (if at all) I can remedy the situation?
I created that shortcode [block] as well and have been using it on other pages without this problem. So it seems page specific (because that makes sense..not).
Any help is very much appreciated. I can provide a link to the page if necessary. Let me know.
How the dashboard looks:
The reason why wordpress does tried to format code is because of a function called wpautop
https://codex.wordpress.org/Function_Reference/wpautop
I found a solution from this thread and tweaked it a bit:
Wordpress - empty p tags
add_filter('the_content', 'remove_empty_p', 11);
function remove_empty_p($content){
$content = force_balance_tags($content);
//return preg_replace('#<p>\s*+(<br\s*/*>)?\s*</p>#i', '', $content);
return preg_replace('#<p></p>#i', '', $content);
}
The third parameter 11 is the priority. For me wpautop filter has a priority of 10 so I set my filter to 11 and that solved my problem.
Thanks all who have tried to help!
Add this to your functions.php and it will fix the problem
add_filter('the_content', 'shortcode_empty_paragraph_fix');
function shortcode_empty_paragraph_fix($content) {
$array = array(
'<p>[' => '[',
']</p>' => ']',
']<br />' => ']',
']<br>' => ']',
);
$content = strtr($content, $array);
return $content;
}
I would like to change the logo redirection when clicked. Right now when you click on the logo, the user is redirected to the homepage but I want it to redirect to another site. How do I do this?
I agree with Stu Mileham. Another way to implement what you are asking for would be to use JavaScript / jQuery.
Save the following code to a .js file (eg. pageRedirect.js, let's say placed in a js folder inside your theme's root folder):
(function($) {
$(document).ready(function() {
$('#pageLogo').on( "click", function(event) {
event.preventDefault();
window.location.assign("http://www.google.com/");
});
});
})(jQuery);
To make the previous code work, you would have to select somehow the page logo via jQuery.
On the previous code this is achived via $('#pageLogo') since I have made the assumption that your logo has an id with the value pageLogo.
Of course, to enable your theme to use this pageRedirect.js file, you have to enqueue it by placing the following code to your theme's functions.php file:
/**
* Enqueue pageRedirect script.
*/
function pageRedirect_scripts() {
wp_enqueue_script( 'page-redirect-js', get_template_directory_uri() . '/js/pageRedirect.js', array('jquery'), '20150528', true );
}
add_action( 'wp_enqueue_scripts', 'pageRedirect_scripts' );
Code Explanation:
//-jQuery selects html element with id='pageLogo'
//-when it is clicked, it calls a function in which it passes the event
$('#pageLogo').on( "click", function(event) {
//prevents page from redirecting to homepage
event.preventDefault();
//redirects to your desired webpage
window.location.assign("http://www.google.com/");
});
If you don't have the option to change the link from admin then you will have to edit your theme's header.php file (most likely, depends on how the theme is built though).
Many themes have a tag similar to the following:
<img src="logo.jpg">
You would need to change this to:
<img src="logo.jpg">
I've added the target tag to open the site in a new window, this is my personal preference when re-directing to a different site but it's optional.
Your theme files might look very different to this, it's impossible to know for sure without seeing some code, but this should give you an idea.
Also be aware that your changes could be overwritten by a theme update. This can be avoided by creating a child theme.
https://codex.wordpress.org/Child_Themes
Depends on your theme
Some theme creators gives you the possibility to change the link from admin
Some theme creators just believe that clicking the logo you need to go on homepage - so you need to edit the theme
Depending upon the theme you are using, you can try one of the following options.
Explore the admin options and see if the theme provides a direct way to change the link on the logo.
If not found in admin options, try looking for the code in header.php. Do an inspect element on your logo and see the html code surrounding the logo file, If the code is directly present in header.php, your task is simple. Just change the code to update the URL, instead of reading it from home_url(). Something like <a href="<?php echo home_url();?>"> will need to be replaced with <a href="https://www.example.com">
The other option to look for is get_custom_logo. Some themes get the logo code from this function. You can apply a filter to change the home_url just before this method is called in your theme and then remove filter afterwards. Or else you can copy the code from wordpress and update it with a differently named function say get_custom_link_logo in functions.php then where'ver your theme is using get_custom_logo you can use get_custom_link_logo instead of that.
function get_custom_link_logo ( $blog_id = 0 ) {
$html = "";
$switched_blog = false;
if ( is_multisite() && ! empty( $blog_id ) && (int) $blog_id !== get_current_blog_id() ) {
switch_to_blog( $blog_id );
$switched_blog = true;
}
$custom_logo_id = get_theme_mod( 'custom_logo' );
// We have a logo. Logo is go.
if ( $custom_logo_id ) {
$custom_logo_attr = array(
'class' => 'custom-logo',
'itemprop' => 'logo',
);
/*
* If the logo alt attribute is empty, get the site title and explicitly
* pass it to the attributes used by wp_get_attachment_image().
*/
$image_alt = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );
if ( empty( $image_alt ) ) {
$custom_logo_attr['alt'] = get_bloginfo( 'name', 'display' );
}
/*
* If the alt attribute is not empty, there's no need to explicitly pass
* it because wp_get_attachment_image() already adds the alt attribute.
*/
$html = sprintf( '%2$s',
esc_url( "https://www.example.com" ),
wp_get_attachment_image( $custom_logo_id, 'full', false, $custom_logo_attr )
);
}
// If no logo is set but we're in the Customizer, leave a placeholder (needed for the live preview).
elseif ( is_customize_preview() ) {
$html = sprintf( '<img class="custom-logo"/>',
esc_url( "https://www.example.com" )
);
}
if ( $switched_blog ) {
restore_current_blog();
}
/**
* Filters the custom logo output.
*
* #since 4.5.0
* #since 4.6.0 Added the `$blog_id` parameter.
*
* #param string $html Custom logo HTML output.
* #param int $blog_id ID of the blog to get the custom logo for.
*/
return apply_filters( 'get_custom_logo', $html, $blog_id ); }
This might not cover all the use cases, but you get the idea. Depending upon the theme you'll have a similar solution for your case. The important thing to figure out which case you fall under will be to identify the code where html for your logo is getting added. header.php is a good starting point.
Use this javascript in the header or footer of your theme:
<script>
document.getElementsByClassName("site-logo")[0].getElementsByTagName('a')[0].href="https://www.test.com";
</script>
i am assuming that site-logo is the class name of your LOGO.
I would like to add rel="nofollow" and target="_blank" for all external links in my Wordpress posts and pages permanently. I am aware, that there are plugins, which do the same, but as soon as they get disabled, all changes will be reversed and the articles are the same as from the beginning.
I do not know how to differ between internal or external links nor how to check if there is already a rel="nofollow" or target="_blank" attribute.
I guess the best way of doing this would be using PHP instead of MySQL. I already searched the web for guides, tutorials or plugins, without success.
May someone help me? I appreciate your support.
I have got a solution for applying nofollow to all existing and new external links.
Copy the code into your functions.php of your activated theme
function add_nofollow_content($content) {
$content = preg_replace_callback('/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i', function($m) {
if (strpos($m[1], "YOUR_DOMAIN_ADDRESS") === false)
return ''.$m[2].'';
else
return ''.$m[2].'';
}, $content);
return $content;
}
add_filter('the_content', 'add_nofollow_content');
You can also call the function home_url() instead of "YOUR_DOMAIN_ADDRESS" in the space provided to avoid hard coding of the domain name.
The code is tested and it works.
Hope this one helps.
You can use following snippet:
http://wpsnipp.com/index.php/functions-php/nofollow-external-links-only-the_content-and-the_excerpt/
This great little snippet that will add rel=”nofollow” to external
links within both the_content and the_excerpt. Add this snippet to the
functions.php of your wordpress theme to enable nofollow external
links.
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;
}
I think adding rel"nofollow" and target="_blank" to outgoing links permanently is more work than it can be shown here. You will have to rebuild the functions of plugins like External Links so that even links in your wp_nav_menus can be rewritten.
I have a suggestion that adds the desired attributes via JavaScript when the page is loaded. You can add this script directly to your theme header or you can keep it in a seperate file enqueing the script in your themes' functions.php:
$(document).ready(function () {
$( "a:not(a[href^='http://www.your-domain-name.com'],a[href^='javascript'],a[href^='#'])" ).attr({
rel: "nofollow",
target: "_blank"
});
});
I took the answer of #rony-samuel and adjusted few things you might find useful.
Use the built-in make_clickable function to wrap links automatically. (E.g. useful when creating posts via API) - then check if the user has added additional classes to a link, (like a button to have a different styling) – we don't want to overwrite that, so just return the given markup with $m[0].
Last thing is the regex. In combination with make_clickable it would output <a <a href... so a link in a link. I corrected the regex to avoid that.
// Auto warp links within content
add_filter( 'the_content', 'make_clickable' );
// Add target blank and nofollow to external links
// Do not overwrite links that probably have been placed manually in the content
// and contain classes like "button" or whatever etc. Since they were placed manually
// with additional styling, the editor can add target="_blank" manually as well if needed.
function external_links ($content) {
$content = preg_replace_callback(
'/<a[^>]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
function($m) {
$hasClass = (bool) preg_match('/class="[^"]*[^"]*"/', $m[0]);
if (strpos($m[1], home_url()) === false && $hasClass === false)
return ''.$m[2].'';
else
return $m[0];
},
$content);
return $content;
}
// set a very low priority to ensure,
// all the content and shortcode things has been completed already
add_filter('the_content', 'external_links', 999);
I am trying to change the color of the first word in the widget title in wordpress. I am using WP v.3.7.1 and a custom child theme that I created off of the twentythirteen theme.
I just need to wrap the first word in a and can style it from there. I tried to add the following code to the function.php but it only works for one of the three widgets that I have. I have tried other widgets and it doesn't work either.
add_filter ('widget_title', 'wpzoom_fix_widgets');
function wpzoom_fix_widgets($old_title) {
$title = explode(" ", $old_title,2);
$titleNew = "<span>$title[0]</span> $title[1]";
return $titleNew;
}
Any suggestions?
Thank you!
Take a look at the first answer on WordPress Answsers, it looks close to what you are looking for:
add_filter('widget_title', my_title);
function my_title($title) {
// Cut the title to 2 parts
$title_parts = explode(' ', $title, 2);
// Throw first word inside a span
$title = '<span class="my_class">'.$title_parts[0].'</span>';
// Add the remaining words if any
if(isset($title_parts[1]))
$title .= ' '.$title_parts[1];
return $title;
}
Good luck :)