First off, I admit I’m a WP-noob, so I’m not even sure I’m going about this the right way. I’m trying to create a simple plugin that replaces matched text in the_content. The code works on my PHP test server, but fails in WP, leaving me to believe I’m missing something. I am hoping someone can point me in the right direction.
I would like the code to search the_content for a string in the format [custom attr=”x” attr2=”y”]sometext[/custom]. To do this, I’m just using preg_match/regex to match the pattern, then swapping it out with str_replace. I’m not sure if the square braces are causing the problem (since WP apparently uses these for the quick links). Can anyone lend a hand?
Some example code is below (simplified $txt
, but you can still get an idea of what I’m trying to accomplish). Thank you.
function test_function($content)
{
global $post;
$match = preg_match_all('/[custom w="(d+)" h="(d+)"]((?:[a-z][a-z][0-9]+[a-z0-9]))[/custom]/is', $content, $matches);
if($match) {
$width = $matches[1][0];
$height = $matches[2][0];
$customtxt = $matches[3][0];
$rep = '[custom attr="' . $width . '" attr2="' . $height . '"]' . $customtext . '[/custom]';
$txt = '
<div id="' . $customtxt . '_container" class="overlay">
<img width="'.$width.'" height="'.$height.'" src="'.$customtxt.'_thumb.jpg" />
</div>
';
if(strpos($content, $rep)) {
$content = str_replace($rep, $txt, $content);
}
}
return $content;
}
function insert_head()
{
?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script language="javascript" type="text/javascript" src="<?php bloginfo('wpurl') ?>/wp-content/plugins/test_function/js/test_function.pack.js"></script>
<?php
}
add_action('wp_head', 'insert_head');
if(is_single()) {
add_filter('the_content', 'test_function');
} else {
add_filter('the_excerpt', 'test_function');
}
why don’t you just use the WordPress shortcode api? -> http://codex.wordpress.org/Shortcode_API
As far as I can tell there are a number of things wrong here. First, I would use preg_replace instead of preg_match. So I would write the function like this:
Which is basically 2 lines of code. Some other problems you’re running into:
1) Your regex fails. The first [ isn’t escaped, and as you know that’s a special character in regexes. I suspect there are other problems with your regex too.
2) From the PHP manual for strpos:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or “”. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.