簡體   English   中英

帖子正文中的Wordpress調用插件功能

[英]Wordpress call plugin function from the post body

我想創建一個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中找到有關過濾器的信息。

示例: <?php add_filter('the_title', function($title) { return '<b>'. $title. '</b>';}) ?>

我可以使用插件中的the_content做同樣的事情嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM