【问题标题】:Wordpress call plugin function from the post bodyWordpress 从帖子正文调用插件功能
【发布时间】:2013-01-18 14:15:29
【问题描述】:

我想创建一个 wordpress 插件,它将帖子正文中的特定行替换为插件中标定的函数输出。希望这对你有意义。我是新的 ro wordpress 开发者。

插件代码

<?php

function money_conversion_tool(){

echo "<form action='' method='post'><input type='text' name='id'><input type='submit'>   </form>";

}

?>

发布html

<h1>Some text some text some text some text</h1>

 [MONEY_CONVERSION_TOOL]

<h2>SOme text some text some text </h2>

主题文件: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(); }

}

?>

我不认为,我对 content-page.php 所做的事情是一种完美的方式。在插件代码中应该有更好的方法。告诉我,如果你想要同样的功能,你会怎么做。

我刚刚从 wordpress codex 中找到了关于过滤器的信息。

例如:&lt;?php add_filter('the_title', function($title) { return '&lt;b&gt;'. $title. '&lt;/b&gt;';}) ?&gt;

我可以对插件中的 the_content 做同样的事情吗?

【问题讨论】:

  • 我是不是读错了,还是你在尝试Shortcode

标签: php wordpress


【解决方案1】:
if (strpos(get_the_content(),"[MONEY_CONVERSION_TOOL]")){
   echo str_replace('[MONEY_CONVERSION_TOOL]', money_conversion_tool(), get_the_content());
else
   the_content();

或更短:

echo (strpos(get_the_content(),"[MONEY_CONVERSION_TOOL]")) ? str_replace('[MONEY_CONVERSION_TOOL]', money_conversion_tool(), get_the_content()) : get_the_content();

在你的函数中,不要回显,直接返回。

<?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') 
?>

【讨论】:

  • 我可以在插件文件中这样做吗?
猜你喜欢
  • 2023-03-23
  • 2017-04-28
  • 1970-01-01
  • 2018-01-22
  • 2011-05-11
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
相关资源
最近更新 更多