I am trying to connect a filepath to my wordpress page.
The filepath I am trying to connect to should be:
'/wp-content/themes/bb-theme-child/php/Hello.php'
Hello.php is:
echo "Hello World"
Here is my code that i have written:
/* SHORTCODE TO HAVE FILES */
add_shortcode('data1', function($atts) {
$atts = 'Some post: ' . include dirname(__Hello.php__) . '/wp-content/themes/bb-theme-child/php/Hello.php';
echo $atts;
});
Whats strange is the output:
echo "Hello!";Some post: 1
Im not sure what Some post: 1 is, nor the reason why Some post comes AFTER Hello.php
The add_shortcode function requires all the output to be returned not echoed
From the docs: https://developer.wordpress.org/reference/functions/add_shortcode/
Note that the function called by the shortcode should never produce an output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. This is similar to the way filter functions should behave, in that they should not produce unexpected side effects from the call since you cannot control when and where they are called from.
That being said, your shortcode should look like:
add_shortcode('data1', function($atts) {
ob_start();
echo 'Some post: ';
include dirname(__Hello.php__) . '/wp-content/themes/bb-theme-child/php/Hello.php';
// do more stuff here maybe ?
return ob_get_clean();
});
!!! Also, make sure your Hello.php file has an open PHP tag before the echo "Hello World" line.
NOTE: Not sure what is your expected output, but this is how I interpreted your code.
You may learn more about WordPress shortcodes from the official docs or from this article I wrote
Related
i code the following
<?php
if ($id = mysql_real_escape_string(#$_GET['pid'])
&& $uid = mysql_real_escape_string(#$_GET['file']))
echo include "foo.php";
else
echo include "bar.php";
?>
When I use the include function in conjunction with a function that's designed to output to the page (e.g., or echo include 'foo.php'), it returns the include but with a "1" after the content that has been included.
echo include "foo.php"
should be
include 'foo.php';
Note that this can also happen when using include with shorthand echo:
<?= include 'foo.php'; ?>
This will also print out the return value of 1 when used inside a script. To get rid of this you need to use the regular PHP opening tag like so:
<?php include 'foo.php'; ?>
PHP will now include the contents of the file without printing the return value.
Okey so the answers here are actually not entirely correct; in some sense even misleading.
include takes the contents of the file and places them in context. One of the more common uses is to pass variable scope around, ie. passing scoped variables in your view by including them in the handler and using include on the view. Common, but there are also other uses; you can also return inside a included file.
Say you have a file like this:
<?php return array
(
'some',
'php'
'based'
'configuration',
'file'
); # config
Doing $config = include 'example-config-above.php'; is perfectly fine and you will get the array above in the $config variable.
If you try to include a file that doesn't have a return statement then you will get 1.
Gotcha Time
You might think that include 'example-config-above.php'; is actually searching for the file in the directory where the file calling the include is located, well it is, but it's also searching for the file in various other paths and those other paths have precedence over the local path!
So if you know you had a file like the above with a return inside it, but are getting 1 and potentially something like weird PEAR errors or such, then you've likely done something like this:
// on a lot of server setups this will load a random pear class
include 'system.php'
Since it's loading a file with out a return you will get 1 instead of (in the case of our example) the configuration array we would be expecting.
Easy fix is of course:
include __DIR__.'/system.php'
That is because the include function returns 1 on success. You get, as you say, 'my name is earl1' because the code inside the included file runs first, printing 'my name is earl' and then you local echo runs printing the return value of include() which is 1.
Let the file.txt contain xxx
echo include("file.txt");
This returns,
xxx1
The '1' is the return value of the include function, denoting the success that the file is accessed. Otherwise it returns nothing, in this case parse error is thrown.
echo print "hello";
This too returns,
hello1
Same as above; '1' denoting the success,it's printed.
echo echo "hello";
print echo "hello";
Both the above cases produces an error.
Since the echo function has no return value, hence undefined.
echo echo "hello"; print echo "hello";
(1st) (2nd)
Now the second 'echo' in the both cases produces an undefined.The first 'echo' or 'print' can't take in the hello output with the undefined (produced by the second echo).
A verification:
if((print "hello")==1)
echo "hey!";
output: hellohey! ('echo' in the 2nd line can be a print, it doesn't matter)
Similarly,
if((include ("file.txt"))==1)
echo "hey!";
output: xxxhey!
Other hand,
if((echo "hello")==1)
echo "hey!";
output: an error
In the first two cases the functions (print and include) returned 1, in the third case 'echo' produces no return value (undefined) hence the third case produces an error.
Well... I am using Codeigniter(php frame work). And I encountered the same problem. What I concluded is that when we try to print/echo the include method then it prints 1 on screen and when we just simply write the include command(example given below) it will only do what it is supposed to do.
<?php include('file/path'); ?> // this works fine for me
<?= include('file/path'); ?> // this works fine but prints "1" on screen
Hope my explaination will be helful to someone
= is assigning operator
== is for checking equal to
check for php operators
I have solved it returning nothing at the end of the included file:
$data = include "data-row.php";
return $data;
Inside data-row.php:
<div>etc</div>
...
<?php return; //End of file
I found the selected answer from this thread very helpful.
Solution 1
ob_start();
include dirname( __FILE__ ) . '/my-file.php';
$my_file = ob_get_clean();
You might also find this thread about the ob_start() function very insightful.
Solution 2
Add a return statement in the file that is being included.
E.g my-file.php
<?php
echo "<p>Foo.</p>";
return;
Drawn from the answer provided by #gtamborero.
To help you understand it the way I do now, just take this oversimplification:
There should always be a return statement otherwise include will return 1 on success.
Happy coding!
M5
Use return null in foo.php and bar.php
echo substr(include("foo.php"),1,-1);
I'm trying to create a basic short code in Wordpress that will allow me to run PHP on pages. This is what I have so far, but it isn't working. Advice?
The idea is it will be [php] Insert PHP here [/php']
<?php
function php_shortcode( $attr, $content = null ) {
return '<?php' . $content . '?>';
}
add_shortcode('php', 'php_shortcode');
?>
Thank you.
Sorry to say you are exploring a concept that simply cannot yield success. The PHP that renders the shortcode, cannot "also" render code within itself.
Short codes as standard will filter PHP tags. You can however write php directly into the content editor. Without giving you all the advisories why it's not recommended, you can do something like the following which will allow you to write php into the content editor:
// write '<?php ... ?>' into the editor
add_filter('the_content', 'allow_php', 9);
function allow_php($content) {
if (strpos($content, '<' . '?') !== false) {
ob_start();
eval('?' . '>' . $content);
$content = ob_get_clean();
}
return $content;
}
After thinking about this for a little while I realized there is an obvious solution. So, someone probably has written a plugin to do it and someone has - https://wordpress.org/plugins/inline-php/.
It consists of about 40 lines of PHP. The critical implementation trick is it is not done as a shortcode but as a 'the_content' filter.
add_filter('the_content', 'inline_php', 0);
This is done before other 'the_content' filter processing and avoids all the problems that I encountered trying to use it as a shortcode. Of course, there is still a significant security risk.
Note: While the issue occurred trying to solve a WordPress problem, the problem being faced right now (see "Current Approach", below) is clearly a PHP issue, which is why it's been posted here.
TL;DR:
I'm dynamically generating PHP code in a file and including that file after it's finished being written to, however PHP cannot call functions from inside the file—even when including it directly without making any changes.
Preface
I've been working on a system for dynamically generating shortcodes in WordPress, and have been running into one serious roadblock along the way: Registering the functions for the shortcodes.
Long story short is that we've got a list of options stored in an array similar to the following:
$array = array(
0 => array(
'code' => 'my-shortcode',
'replacement' => 'replacement_directives_here'
)
);
I've already got a system that processes the codes and sends generates the proper output based on the directives. It's getting the call to add_shortcode($shortcode, $callback) to work.
My first strategy was to use anonymous functions in a manner similar to the following:
foreach ($array as $code => $directions) {
$GLOBALS['my_shortcode_output'] = my_shortcode_process($directions);
add_shortcode($code, function() { return $GLOBALS['my_shortcode_output']; });
}
However this ended up with successive directives overwriting each other due to the fluctuating content of the global, so I decided to try something different...
Current Approach
As a workaround to having the information I need constantly slipping just out of reach, I decided to try something different:
Create a file within my plugin
Write out the PHP code for the functions I wanted to include so that they were guaranteed to generate the right output
Include the file after the fclose() call
Register the shortcodes, referencing the functions in the new file
The code for generating the file looks something like the following:
$file = fopen(PATH_TO_FILE, 'w'); // Open for writing only, truncate file on opening
fwrite($file, "<?php\n\n"); // Using double quotes so newlines and escapes don't get counted as literals
// foreach through list
foreach ($shortcode_list as $shortcode) {
if ($shortcode['code'] != '') {
// Append new function with a dynamic name (e.g. $shortcode[code]._sc') to dynamic_shortcodes.php
// Function should consist of: return my_shortcode_process($shortcode['replacement']);
// Hard-coding so we don't get frozen if information gets changed
$new_function = "\tfunction str_replace('-', '_', $shortcode['code'])."_sc() {\n\t\treturn my_shortcode_process('".$shortcode['replacement']."');\n\t}\n\n";
fwrite($file, $new_function);
// Add function name to $shortcode_functions array, keyed on the shortcode
$shortcode_functions[$shortcode['code']] = str_replace('-', '_', $shortcode['code']).'_sc';
}
}
fclose($file); // Close the file, since we are done writing to it
touch(PATH_TO_FILE); // Ensure the file's modification time is updated
After that it's just a simple loop to register them:
foreach ($shortcode_functions as $shortcode => $callback) {
add_shortcode($shortcode, $callback);
}
When I reload and run everything, however, I get the following:
Notice: do_shortcode_tag was called incorrectly. Attempting to parse a shortcode without a valid callback: [SHORTCODE HERE]. Please see Debugging in WordPress for more information.
I've downloaded the file and verified its contents—everything checks out in PHPstorm. It's properly formatted, there are no syntax errors, and the functions it depends upon are already loaded and working fine.
Even skipping the whole process and just directly including the file and then calling one of the functions inside it isn't working. It's like the file has been blackballed. At the same time, however, neither include() nor require() produce any errors.
Is this a caching issue, perhaps?
Honestly, I'm totally unable to understand what you're trying to do (or even why) but PHP doesn't have any problem with dynamically generated includes. This works fine:
<?php
$file = __DIR__ . '/foo-' . mt_rand(0, PHP_INT_MAX) . '.php';
$code = '<?php
function foo() {
echo "Hello, World!";
};
';
file_put_contents($file, $code);
require $file;
foo();
However, you're apparently trying to execute something like this:
function str_replace('-', '_', $shortcode['code'])."_sc(){
}
That's a blatant syntax error either in included files on in the main script. If you follow the Please see Debugging in WordPress for more information instructions you'll possibly find something similar to this:
Parse error: syntax error, unexpected ''-'' (T_CONSTANT_ENCAPSED_STRING), expecting variable (T_VARIABLE)
A syntax for variable functions that works could be:
$name = str_replace('-', '_', $shortcode['code']) . '_sc';
$name = function (){
};
I am creating new shortcodes for Wordpress on my local version of a Wordpress website.
In functions.php, I am adding for example:
function shortTest() {
return 'Test for shortcodes ';
}
add_shortcode('shortTestHTML', 'shortTest');
Adding the function only is OK, but when I add the add_shortcode() portion, I get a major issue.
It breaks something somehow and I get 500 errors, meaning I can't even load my website locally anymore.
Any thoughts???
Thanks so much!
EDIT:
From PHP Error Log:
[21-Jun-2011 19:02:37] PHP Fatal error: Call to undefined function add_shortcode() in /Users/jonas/Sites/jll/wp-includes/functions.php on line 4505
1) Make sure that you have included shortcodes.php file somewhere (for example, in wp-load.php or whatever other more appropriate place may be).
require_once( ABSPATH . '/wp-includes/shortcodes.php' );
2) Make sure that this file does exist on your installation (which I think you have otherwise we would see a different error).
3) Where do you call this function from (I see it is called from functions.php, but which place)? Possible problem here -- functions.php is loaded prior to shortcodes.php, and if you do use that add_shortcode function before shortcodes.php is loaded you most likely will see this error. Double check your code in that place -- maybe move the call to add_shortcode to another place.
mentioned functions.php is not in wp-include/ directory.
it is in: wp-content/themes/<your-theme-name>/functions.php
adding this in functions.php you say? Well I don't know about that, the way I did it was create a folder inside the wp-content/plugins folder, e.g. shortcodetest.
Inside this folder create a shortcodetest.php file.
in that file you basically write your code:
<?php
/*
Plugin Name: ShortCodeTest
Plugin URI: http://www.example.net
Description: Print a test message
Version: 0.1
Author: anonymous
Author URI: http://www.example.net
*/
add_shortcode('shortcodetest', 'shortcodetest_function');
function shortcodetest_function() {
return "test of shortcode";
}
?>
Then you login as admin, you will see a plugin ShortCodeTest, activate it. Then you can use the shortcode in your posts.
Note that the comments are important... they show up in the plugin description.
I got a way to execute them but it's a little triky :)
You need to change a little bit your template by putting your shortcode (for example: [inline ....]) between <shortcode></shortcode> then
Here is the function to place at the end of your function.php.
function parse_execute_and_echo_shortcode($_path) {
$str = file_get_contents($_path);
while (strrpos($str, "<shortcode>")) {
$beginShortcode = strrpos($str, "<shortcode>");
$endShortcode = strrpos($str, "</shortcode>");
$shortcode = substr($str, $beginShortcode + 11, $endShortcode - ($beginShortcode+11));
$shortcode = do_shortcode($shortcode);
$str = substr_replace($str, $shortcode, $beginShortcode, $endShortcode + 12);
}
echo $str;
}
Then you can call function parse_execute_and_echo_shortcode and giving it the path to your file containing the shortcodes.
Hope that can help someone
Check your error.log file (it should be in your apache log folder).
It probably has to do with add_shortcode not existing as a function.
Put your shortcode in the file /wp-includes/shortcodes.php this way you make sure it will be loaded when all the blows and whistles are up and running.
i code the following
<?php
if ($id = mysql_real_escape_string(#$_GET['pid'])
&& $uid = mysql_real_escape_string(#$_GET['file']))
echo include "foo.php";
else
echo include "bar.php";
?>
When I use the include function in conjunction with a function that's designed to output to the page (e.g., or echo include 'foo.php'), it returns the include but with a "1" after the content that has been included.
echo include "foo.php"
should be
include 'foo.php';
Note that this can also happen when using include with shorthand echo:
<?= include 'foo.php'; ?>
This will also print out the return value of 1 when used inside a script. To get rid of this you need to use the regular PHP opening tag like so:
<?php include 'foo.php'; ?>
PHP will now include the contents of the file without printing the return value.
Okey so the answers here are actually not entirely correct; in some sense even misleading.
include takes the contents of the file and places them in context. One of the more common uses is to pass variable scope around, ie. passing scoped variables in your view by including them in the handler and using include on the view. Common, but there are also other uses; you can also return inside a included file.
Say you have a file like this:
<?php return array
(
'some',
'php'
'based'
'configuration',
'file'
); # config
Doing $config = include 'example-config-above.php'; is perfectly fine and you will get the array above in the $config variable.
If you try to include a file that doesn't have a return statement then you will get 1.
Gotcha Time
You might think that include 'example-config-above.php'; is actually searching for the file in the directory where the file calling the include is located, well it is, but it's also searching for the file in various other paths and those other paths have precedence over the local path!
So if you know you had a file like the above with a return inside it, but are getting 1 and potentially something like weird PEAR errors or such, then you've likely done something like this:
// on a lot of server setups this will load a random pear class
include 'system.php'
Since it's loading a file with out a return you will get 1 instead of (in the case of our example) the configuration array we would be expecting.
Easy fix is of course:
include __DIR__.'/system.php'
That is because the include function returns 1 on success. You get, as you say, 'my name is earl1' because the code inside the included file runs first, printing 'my name is earl' and then you local echo runs printing the return value of include() which is 1.
Let the file.txt contain xxx
echo include("file.txt");
This returns,
xxx1
The '1' is the return value of the include function, denoting the success that the file is accessed. Otherwise it returns nothing, in this case parse error is thrown.
echo print "hello";
This too returns,
hello1
Same as above; '1' denoting the success,it's printed.
echo echo "hello";
print echo "hello";
Both the above cases produces an error.
Since the echo function has no return value, hence undefined.
echo echo "hello"; print echo "hello";
(1st) (2nd)
Now the second 'echo' in the both cases produces an undefined.The first 'echo' or 'print' can't take in the hello output with the undefined (produced by the second echo).
A verification:
if((print "hello")==1)
echo "hey!";
output: hellohey! ('echo' in the 2nd line can be a print, it doesn't matter)
Similarly,
if((include ("file.txt"))==1)
echo "hey!";
output: xxxhey!
Other hand,
if((echo "hello")==1)
echo "hey!";
output: an error
In the first two cases the functions (print and include) returned 1, in the third case 'echo' produces no return value (undefined) hence the third case produces an error.
Well... I am using Codeigniter(php frame work). And I encountered the same problem. What I concluded is that when we try to print/echo the include method then it prints 1 on screen and when we just simply write the include command(example given below) it will only do what it is supposed to do.
<?php include('file/path'); ?> // this works fine for me
<?= include('file/path'); ?> // this works fine but prints "1" on screen
Hope my explaination will be helful to someone
= is assigning operator
== is for checking equal to
check for php operators
I have solved it returning nothing at the end of the included file:
$data = include "data-row.php";
return $data;
Inside data-row.php:
<div>etc</div>
...
<?php return; //End of file
I found the selected answer from this thread very helpful.
Solution 1
ob_start();
include dirname( __FILE__ ) . '/my-file.php';
$my_file = ob_get_clean();
You might also find this thread about the ob_start() function very insightful.
Solution 2
Add a return statement in the file that is being included.
E.g my-file.php
<?php
echo "<p>Foo.</p>";
return;
Drawn from the answer provided by #gtamborero.
To help you understand it the way I do now, just take this oversimplification:
There should always be a return statement otherwise include will return 1 on success.
Happy coding!
M5
Use return null in foo.php and bar.php
echo substr(include("foo.php"),1,-1);