How to use a plugin function in a post?

February 17th, 2009 Posted in Wordpress MU

Difficulty Level:

Today we will show you how to use your own plugin function in a post.

Sometimes you want to add special content to your post, but there is no wordpress function available. An easy way to solve this problem is to write your own function, which will do what you want and include it into your post with a special tag. In our example we will use a function which shows a list of all available themes.

In four small steps we will reach our goal:

Step 1:
Create a php file. Name it “mg_plugin_post.php”.

Step 2:
Now you have to insert this two small functions:

Funtion 1:

  1. function mg_show_list_available_themes($match) {
  2. //Clear output
  3. $output ='';
  4. // Get all theme information
  5. $themes   = get_themes();
  6. // Get all Theme names
  7. $theme_names  = array_keys($themes);
  8. // Create the output
  9. $output = 'List of all available themes:';
  10. $output .= '<ul>';
  11. //Write every theme name in a list element
  12. foreach($theme_names as $my_themes)
  13. $output .= '<li>' .$my_themes .'</li>';
  14. $output .= '</ul>';
  15. // Return the whole output string
  16. return($output);
  17. }

Function 2:
  1. /***H*O*O*K*************************************/
  2. add_filter('the_content', 'embeddedshow_list_available_themes');
  3. /***********************************************/
  4. // actual plugin function
  5. function embeddedshow_list_available_themes($content) {
  6. $output=preg_replace_callback('[mg_call_show_list_available_themes]',
  7. 'mg_show_list_available_themes', $content);
  8. return ($output);
  9. }

Step 3:
Copy this file in your mu-plugins directory.

Step 4:
Create a new post and the content of your post will be mg_call_show_list_available_themes.

Now you will get a list of all themes in your post.

How did we do that?

  1. In “Function 2” we use a filter to call a function embeddedshow_list_available_themes when content of your blog will be generated.
  2. In this function we use the php function preg_replace_callback to search the content for the special string mg_call_show_list_available_themes. So if we find that string we will call a new function.
  3. In this case the “Function 1” mg_show_list_available_themes which will generate the list of all available themes and return it to “Function 2”.
  4. The funtion embeddedshow_list_available_themes replaces the string mg_call_show_list_available_themes in your post with the new content generated by “Function 1”.

You can also download this wordpress mu plugin.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • MisterWong
  • Y!GG
  • Webnews
  • Digg
  • StumbleUpon
  • Reddit

Comments are closed.

My-Guide Interessante Guides: MontenegroTutorialsKurzarbeitFitnessGitte kocht