Reputation: 287
I want to create a wordpress plugin which will replace the specific line inside the post body with the function output decalared in the plugin. Hope this make sense to you. I'm new ro wordpress development.
Plugin Code
<?php
function money_conversion_tool(){
echo "<form action='' method='post'><input type='text' name='id'><input type='submit'> </form>";
}
?>
Post html
<h1>Some text some text some text some text</h1>
[MONEY_CONVERSION_TOOL]
<h2>SOme text some text some text </h2>
Theme file: content-page.php
<?php
if(strpos[get_the_content(),"[MONEY_CONVERSION_TOOL]"){
$contents_part = explode('[MONEY_CONVERSION_TOOL]',get_the_content());
if(isset($contents_part[0])){ echo $contents_part[0]; }
money_conversion_tool();
if(isset($contents_part[1])){ echo $contents_part[1]; };
} else { the_content(); } } else { the_content(); }
}
?>
I don't think, what i'm doing with the content-page.php is a perfect way. There Should be a better way to this in the plugin code. Tell me what you will do if you want same find of functionality.
I just found from wordpress codex about filters.
Example: <?php add_filter('the_title', function($title) { return '<b>'. $title. '</b>';}) ?>
can i do same thing with the the_content in the plugin ?
Upvotes: 0
Views: 1659
Reputation: 2224
if (strpos(get_the_content(),"[MONEY_CONVERSION_TOOL]")){
echo str_replace('[MONEY_CONVERSION_TOOL]', money_conversion_tool(), get_the_content());
else
the_content();
Or shorter:
echo (strpos(get_the_content(),"[MONEY_CONVERSION_TOOL]")) ? str_replace('[MONEY_CONVERSION_TOOL]', money_conversion_tool(), get_the_content()) : get_the_content();
In your function, don't echo, just return.
<?php
function mct_modifyContent($content) {
if (strpos($content,"[MONEY_CONVERSION_TOOL]"))
$content = str_replace('[MONEY_CONVERSION_TOOL]', money_conversion_tool(), $content);
return $content;
};
add_filter('the_content', 'mct_modifyContent')
?>
Upvotes: 0