0
votes

I created a folder in the /wp-content/plugins directory called customshortcode. The add_shortcode command should link the shortcode with the function.

In /wp-content/plugins/customshorcode/ I created 2 files: main.php and test.php

Contents of main php is:

<?php require_once('../../../wp-includes/shortcodes.php'); ?>

<?php function custom_shortcode_func() {
  include_once('test.php');
}

add_shortcode('customshortcode','custom_shortcode_func');

?>

And test.php simply displays a division block:

<style>.testdiv{border:1px solid black; width:300px; heigh:300px;}</style>

<div class="testdiv"></div>

I first run the /wp-content/plugins/customshorcode/main.php file to see no errors and simple white screen. I assumed the short-code should be saved.

But when I enter [customshortcode] in the page, I don't get the division displayed, instead the text [customshortcode] instead.

I think I somehow need to link the page type to the plugin or something like that. Could you help me out?

2
Where and How you add [customshortcode] in the page ? - samuelj90
in your test.php write: return '<style>.testdiv{border:1px solid black; width:300px; heigh:300px;}</style><div class="testdiv"></div>';. And why you have include /wp-includes/shortcodes.php?? - Raunak Gupta
Because without it when I got to the main.php to run it in the URL bar, I get: Fatal error: Call to undefined function add_shortcode() in C:\MAMP\htdocs\new\wp-content\plugins\customshortcode\main.php on line 8 - GRS
Also is in test.php do I need to open and close <?php ?> tags? Currently I only have the return statement above without the tags. - GRS
@SamuelJMathew I simply created a new page, added a title, and put the shortcode in the content, clicked on preview page - GRS

2 Answers

1
votes

In /wp-content/plugins/customshorcode/main.php

<?php
/*
* Plugin Name: Custom Short Code
* Description: Create your WordPress shortcode.
* Version: 1.0
* Author: [email protected] 
*/

// Example 1 : WP Shortcode to display form on any page or post.
function custom_shortcode_func() {
?>
<style>.testdiv{border:1px solid black; width:300px; heigh:300px;}</style>

<div class="testdiv"></div>
<?php
}
add_shortcode('customshortcode','custom_shortcode_func');

?>

Then enable the plugin

Custom Short Code
-1
votes
   <?php
/*
* Plugin Name: Custom ShortCodes
* Description: Create your WordPress plugin shortcodes.
* Version: 1.0
* Author: [email protected]
*/

function wpb_test_shortcode() { 
$message = 'Hello world!'; 
return $message;
} 
add_shortcode('testing', 'wpb_test_shortcode');
?>