Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2561331
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: 系统运维

2012-02-22 11:57:32

大多数时候,我们给wp新增功能都是通过插件的方式。插件一般都比较小巧,如果需要扩展到功能涉及到的页面或功能比较多,我们可能希望在standalone的php脚本中调用wp的api。实际上,并不复杂,只需要在自定义脚本前加载wp engine即可。一旦加载wp-load.php,我们就可以使用wp的各种函数,也可以进行权限的控制。

The term “Standalone” here refers to a page that run using WordPress engine but does not display using your WordPress theme. It means that your page can access all PHP functions in WordPress but you get to decide how the page looks like. The good news is, to do this using WordPress is amazingly easy.

Loading WordPress Engine

First thing to do is to load the WordPress core engine file, wp-load.php. Depends on where you want to put your custom page, you just need to use require_once(‘wp-load.php’), of course point it to correct folder if your custom page is in different folder.

In this example, i put my custom page in my WordPress root folder. Enter this in your custom page:
  1. <?php
  2.       require_once('wp-load.php');
  3.       //if you put in "your-wordpress-root/wp-content/" folder , prepend with "../"
  4.      //to go "1 folder up"
  5.     //require_once('../wp-load.php');
  6.       ?>


Congratulations, you just created a standalone WordPress custom PHP page. Isn’t that easy?
Making the page Admin-Only

Very often you need limit access to your page to your blog admins only. You can check if the user is an admin after the require_once() statement:
  1. <?php
  2. require_once('wp-load.php');
  3.  if ( !is_user_logged_in() && !current_user_can('manage_options')) {
  4. die('Please login as admin to use this page.');
  5. }

     //your page content here



As we said previously, after we loaded wp-load.php, we then have access to all WordPress functions, that is why we can use is_user_logged_in() and current_user_can() to check the user.

“manage_options” is the capability we used to check if the user is admin because all admins can “manage_options”. For more capabilities other than just “manage_options”, please refer to the WordPress Codex on Roles & Capabilities.

Hope this helps :)

From:http://zenverse.net/how-to-create-a-standalone-wordpress-custom-php-page/




阅读(1011) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~