在WordPress 的文章或页面中运行PHP 代码

在WordPress 的文章或页面中运行PHP 代码

如果你在编辑器中输入PHP 代码,默认的话WordPress 不会为你执行这段代码的——只会文本方式输出。Tutsplus 上有一篇文章以插件的方式告知我们实现在WordPress 的文章或页面中运行PHP 代码的方法,下面介绍下。

原理小介绍

懂php 的都知道,PHP中载入其他PHP文件可以用include() 或者 require() 函数,因此为了实现在WordPress 的文章或页面中运行PHP 代码,我们可以将打算运行的代码写入一个额外的PHP 文件中,放在某个目录下,通过某种机制调用。英文原文中采用的是短代码方式,为了方便,作者直接做成了插件。

插件代码如下:

<?php
/*
  Plugin Name: Run PHP code in Post & Page
  Plugin URI: http://code.tutsplus.com
  Description: Run PHP code in WordPress
  Author: Agbonghama Collins
  Version: 1.0
  Author URI: http://tech4sky.com/
 */
 
  function php_include( $attr ) {
    $file = $attr['file'];
    $upload_dir = wp_upload_dir();
    $folder = $upload_dir['basedir'] . '/php-content'. "/$file.php";
    ob_start();
    include ( $folder );
    return ob_get_clean();
}
add_shortcode( 'phpcode', 'php_include' );
?>

上诉代码中的变量 $upload_dir['basedir'] 指代的是WordPress 中多媒体文件的上传路径(默认为/wp-content/uploads/),接下来通过一个实例说明如何使用这个短代码插件。

比如说我打算在文章中运行下面这段php代码,那么我就将这段代码放到一个php 文件中,命名为ordsbackward.php 吧!

<form method="post">
    <textarea name="string"><?php echo ( isset( $_POST['string'] ) ) ? $_POST['string'] : null ;?></textarea>
	<br />
	<input type="submit" name="submit" value="Reverse"/>
</form>
 
<?php
if ( isset( $_POST['submit'] ) && empty( $_POST['string'] ) ) {
	echo "Field should not be left empty";
} elseif ( isset( $_POST['submit'] ) && ( $_POST['string'] ) ) {
	echo '<div>Copy Result</div>';
	echo '<textarea>';
	echo htmlspecialchars( strrev( $_POST['string'] ) );
	echo '</textarea>';
}

然后在多媒体文件的上传路径(默认为/wp-content/uploads/)新建一个php-content 文件夹(集中放这些php 文件,方便管理), 将 wordsbackward.php 丢到里面去。

那么此时,在WordPress 编辑器中写文章时候用下面的短代码插入短代码:

[phpcode file="wordsbackward"]

即可运行相应的wordsbackward.php文件,如图:

have fun!

PS:Tutsplus 上的原文不知为何已经被删除,Jeff 是在RSS 阅读器上保留下的,但还是感谢原作者。经过亲自测试代码可行。

评分:
当前平均分 0.00 (0%) - 0 个投票
10 条 评论
  1. 貌似还没看到有运行javascript的。

    8年前 回复
  2. 只能执行文件啊?

    9年前 回复
  3. 收藏了。。真在发愁这个问题呢。。谢谢。

    9年前 回复
  4. 站长现在是学生还是已经工作了?

    10年前 回复
  5. 学习了 感谢分享 沙发

    10年前 回复
  6. 能运行js代码吗?

    10年前 回复
发表评论