newbie to wordpress here.
I'm currently trying to add a fb share button to all images on my blog and have added this to functions.php:
function breezer_addDivToImage( $content ) {
// A regular expression of what to look for.
$pattern = '/(<img([^>]*)>)/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<div class="myphoto">$1Share on Facebook</div>';
// run preg_replace() on the $content
$content = preg_replace( $pattern, $replacement, $content );
// return the processed content
return $content;
}
add_filter( 'the_content', 'breezer_addDivToImage' );
Works well, except for the fact that the permalink isn't translating (It's sharing the php). There is something stupidly simple I know I'm doing wrong. Any help is greatly appreciated.
Cheers!
inside single quotes strings are placed as it is, they are not converted... so you can use dot operator to concatenate the generated permalink... otherwise you need to escape the quotes... the following example uses string conctenation
$replacement = '<div class="myphoto">$1Share on Facebook</div>';
That's because you are writing your PHP code into a string:
$replacement = '<div class="myphoto">$1
<a href="http://www.facebook.com/sharer.php?u=' . get_permalink() . '" class="facebook-share-btn fb-" data-fsb-service="facebook" data-href="' . get_permalink() . '"...
try that
Related
<?php
$titledb = array('经济管理','管理','others');
$content='经济管理是我们国的家的中心领导力,这是中文测度。';
$replace='<a target="_blank" href="http://www.a.com/$1">$1</a>';
foreach ($titledb as $title) {
$regex = "~\b(" . preg_quote($title) . ")\b~u";
$content = preg_replace($regex, $replace, $content, 1);
}
echo $content;
?>
I was writing a auto link function for my wordpress site and I'm using substr_replace to find the keywords(which are litterally a lot) and replace it with link--I'm doing this by filtering the post content of course.
But in some circumstances, suppose there are posts with titles like "stackoverflow" and "overflow" it turns out to be a mess, the output will look like :
we love<a target="_blank" href="http://www.a.com/stackoverflow">stackoverflow</a>,this is a test。we love <a target="_blank" href="http://www.a.com/stack<a target=" _blank"="">overflow</a> ">stackoverflow,this is a test。
What I want is:
we love<a target="_blank" href="http://www.a.com/stackoverflow">stackoverflow</a>,this is a test。we love stack<a target="_blank" href="http://www.a.com/overflow">overflow</a>,this is a test。
And this is only a test.The production enviorment could be more complicated,like I said there are tens of thousands of titles as keywords need to be found and replaced with a link. So I see these broken links a lot.It happens when a title contains another title.Like title 'stackoverflow' contains another title 'overflow'.
So my question is how to make substr_replace take title 'stackoverflow' as a whole and replace only once? Of course,'overflow' still needs to be replaced somewhere else just not when it is included in another keyword.
Thank you in advance.
To prevent that a search for a word will start replacing inside the HTML code that you already injected for some other word, you could make use of a temporary placeholder, and do the final replacement on those place holders:
$titledb = array('经济管理','管理','others');
// sort the array from longer strings to smaller strings, to ensure that
// a replacement of a longer string gets precedence:
usort($titledb, function ($a,$b){ return strlen($b)-strlen($a); });
$content='经济管理是我们国的家的中心领导力。';
foreach ($titledb as $index => $title) {
$pos = strpos($content, $title);
if ($pos !== false) {
// temporarily insert a place holder in the format '#number#':
$content = substr_replace($content, "#$index#", $pos, strlen($title));
}
}
// Now replace the place holders with the final hyperlink HTML code
$content = preg_replace_callback("~#(\d+)#~u", function ($match) use ($titledb) {
return "<a target='_blank' href='http://www.a.com/{$titledb[$match[1]]}'>{$titledb[$match[1]]}</a>";
}, $content);
echo $content;
See it run on eval.in
I got a problem with single quotes in a regular expression.
What i want to do is replace smileys in a string to a html image tag.
All smileys are working, except the sad smiley :'-( because it has a single quote in it.
Magic Quotes is turned off (testet with if (g!et_magic_quotes_gpc()) dd('mq off');).
So, let me show you some code.
protected $emoticons = array(
// ...
'cry' => array(
'image' => '<img class="smiley" src="/image/emoticon/cry.gif" />',
'emoticons' => array(":'(", ";'(", ":'-(", ";'-(")
),
);
My method to replace all the emoticons is the following:
public function replaceEmoticons($input) {
$output = $input;
foreach ($this->emoticons as $emo_group_name => $emo_group) {
$regex_emo_part = array();
foreach ($emo_group['emoticons'] as $emoticon) {
$regex_emo_part[] = preg_quote($emoticon, '#');
}
$regex_emo_part = implode('|', $regex_emo_part);
$regex = '#(?!<\w)(' . $regex_emo_part .')(?!\w)#';
$output = preg_replace($regex, $emo_group['image'], $output);
}
return $output;
}
But as i said: ' kills it. No replacement there. :-) :-/ and so on are working. Why?
FYI Content of $regex: #(?!<\w)(\:\'\(|;\'\(|\:\'\-\(|;\'\-\()(?!\w)#
What is wrong here, can you help me?
UPDATE:
Thanks # cheery and cychoi. The replacing method is okay, you've got right.
I found the problem. My string gets escaped before it is forwarded to the replaceEmoticons method. I use TWIG templating engine and i use |nl2br filter before my selfmade replace_emoticon filter.
Let me show you. This is the output in the final template. It is a template to show a comment for an blog entry:
{{ comment.content|nl2br|replace_emoticons|raw }}
Problem: nl2br is auto pre-escaping the input string, so ' gets replaced by the escaped one '
I need this nl2br to show linebreakes as <br /> - and i need the escaping too, to disallow html tags in the user's input.
I need replace_emoticons to replace my emoticons (selfmade TWIG extension).
And i need raw here at the end of the filter chain too, otherwise all HTML smiley img tags gets escaped and i will see raw html in the comment's text.
What can i do here? The only problem here seems to be that nl2br escapes ' too. This is no bad idea but in my case it will destroy all sad smileyss containing ' in it.
Still searching for a solution to solve this and i hope you can help me.
Best,
titan
I added an optional parameter to the emoticon method:
public function replaceEmoticons($input, $use_emo_encoding_for_regex = true) {
and i changed the foreach part a lil' bit:
foreach ($emo_group['emoticons'] as $emoticon) {
if ($use_emo_encoding_for_regex === true) {
$emoticon = htmlspecialchars($emoticon, ENT_QUOTES);
}
$regex_emo_part[] = preg_quote($emoticon, '#');
}
It works! All emoticons are replaced!
I've been reading various articles and have arrived at some code.
For a single URL on my site http://home.com/example/ (and only that URL - no children) I would like to replace all instances of "<a itemprop="url" with just <a basically stripping out itemprop="url" This is what I have come up with but I'm not sure whether I'm on the right lines and if I am how to 'echo' it on on the basis it's code and not something to be echoed to screen. Also not too sure whether I need to escape the double quotes within the single quotes in $str_replace.
if(preg_match("%/example/$%", $_SERVER['REQUEST_URI'])){
$string = "<a itemprop=\"url\"";
$str_replace = str_replace('<a itemprop="url"','<a',$string);
//something here
}
Please could anyone advise also if I am correct in how I am approaching this what the final part of the code needs to be to run it (I'm assuming not echo $str_replace;. I'll be running it as a function from my Wordpress functions.php file - I'm comfortable with that if it works.
This could be a mess and I apologise if it is.
try strpos()
if(strpos($_SERVER['REQUEST_URI'], "example") !== false){
$string = "<a itemprop=\"url\"";
$str_replace = str_replace('<a itemprop="url"','<a',$string);
}
There must be some kind of template where you get the default html and modify it with the php at some point of your code...
$html_template = file('...adress_of_the_url_template...');
.......
if(strpos($_SERVER['REQUEST_URI'], "example") !== false){
$string = "<a itemprop=\"url\"";
$html_template = str_replace($string,'<a',$html_template);
}
.......
.......
echo $html_template
Then you have replaced the html code as you wanted
It looks like I was over-complicating it because the solution appears to be within Wordpress functions. This is what I've ended up with. Any comments, corrections or recommendations appreciated. I'm not a coder as you may realise...
function schema( $content ) {
if (is_page( 'my-page-slug')) {
return str_replace('<a itemprop="url"', '<a', $content);
}
else return $content;
}
add_filter('the_content', 'schema', 99);
I'm trying something out but as I'm not versed in PHP it feels like smashing my head against random walls.
I need to alter the output of image tags. I want to replace the img tag for a div with a background image, to achieve sort of this effect.
I'm working around this function, in functions.php. This only takes the full image code and outputs it into the background-image url. I would need to extract the SRC.
function turnItIntoDiv( $content ) {
// A regular expression of what to look for.
$pattern = '/(<img([^>]*)>)/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<div class="full-image" style="background-image: url("$1")"></div>';
// run preg_replace() on the $content
$content = preg_replace( $pattern, $replacement, $content );
// return the processed content
return $content;
}
add_filter( 'the_content', 'turnItIntoDiv' );
Thank you all in advance
Maybe it would by fine to split.
if (preg_match("/img/i",$content))
{
..
$pattern = '/src="([^"]+)"/i';
..
Then you will get exact file name. Height of div should be set.
Whole code - matching all images:
if (preg_match("/img/i",$content))
{
if (preg_match_all('/src[ ]?=[ ]?"([^"]+)"/i',$content,$matches))
{
foreach ($matches[1] as $i => $match)
{
$replacement = '<div class="full-image" style="background-image: url(\'' . trim($match) . '\')"></div>';
$content = preg_replace("~(<img(.*){$matches[0][$i]}[^>]+>)~i",$replacement,$content);
}
}
}
! div height must be set
When I created a function (in child-theme/functions.php) to modify text in the_content(), the following function worked well.
function my_text_changes ( $text ) {
$text = str_replace( 'My Site Name', '<em>My Site Name</em>', $text );
return $text;
}
add_filter( 'the_content','my_text_changes' );
This function modifies only one portion of text (multiple times). When I changed the function so I could modify more portions of text, I took this same variable and str_replace and put it into a switch/case (also tried if statements) and all the content disappears.
function my_text_changes ( $text ) {
switch( $text ) {
case "My Site Name":
$text = str_replace( 'My Site Name', '<em>My Site Name</em>', $text );
return $text;
break;
}
}
add_filter( 'the_content','my_text_changes' );
I want to build multiple cases but cannot get the first one to work. The same holds true if I change the switch/case to an if statement. I have tried changing $text = and the return $text to $newtext = and return $newtext to no avail. Any ideas?
The $text argument that you are passing there contains the whole content. You switch assignment will never be true (unless the entirety of the content consists of “My Site Name”), and your text will not be substituted.
The reason why everything disappears is because you have to return the $text variable outside of the switch statement (or your if/elses) or else it will display nothing (basically you are substituting the entire content with nothing).
It is, in fact, sufficient that you run your str_replaces without any if/else or switch, if I understand your problem correctly.
Edit:
While the original answer works, there is a better way. You argue in your comment that the second $text will overwrite the first assignment, which is true, but not a problem, since the previous one is already the text with the string correctly replaced. Just give it a try and see by yourself.
In any case, I checked the docs for str_replace and it does accept arrays as arguments, so your problem may be solved like so:
function my_text_changes ( $text ) {
$searches = array( 'My Site Name', 'a second string' );
$replaces = array( '<em>My Site Name</em>', 'a <strong>second</strong> string' );
$new_text = str_replace( $searches, $replaces, $text );
/* ... */
return $new_text;
}
Original answer
Just do:
function my_text_changes ( $text ) {
$text = str_replace( 'My Site Name', '<em>My Site Name</em>', $text );
$text = str_replace( 'second_string', 'replacement', $text);
/* ... */
return $text;
}
You shouldn't use return statement before break.
But the issue seems to be different than the code cited. Can you check the php error logs on the hosting and share the same?