[英]How to create a page in WordPress with PHP and without using an admin panel or creating an HTML file?
我想创建一个这样的页面(不使用管理面板或创建 HTML 文件):
example.com/东西
但我不想在 WordPress 管理面板中创建一个“东西”页面。
所以我必须通过PHP创建一个页面。
我在 function.php 中使用了这些代码:
if(false !== strpos($url,'something')) {
echo 'something exists!';
}
现在,当页面加载时,它会显示“有东西存在!” 在页面上停留片刻,然后加载“404”页面。
请告诉我如何避免在我的内容上加载“404”页面。
谢谢
因此,如果您想在 wordpress 中获得可访问的 url,而无需在数据库中创建页面或帖子,那么您可以使用动态路由器插件或 php 类。
DynamicRouter.lib.php
我们开发了一个 PHP 类库,它使在 wordpress 中创建动态页面 url 变得容易。
这是没有依赖项的DynamicRouter.lib.php
类文件...
https://gist.github.com/joshmoto/DynamicRouter.lib.php
DynamicRouter.lib.php
首先将此 lib 文件添加到您的主题中,例如在名为lib
的文件夹中。
然后在你的functions.php
需要这个类lib一次......
// class libraries
require_once(__DIR__ . '/lib/DynamicRouter.lib.php');
然后在您的函数中使用这个所需的库之后(不是之前),您可以开始创建动态 url,而无需在 wordpress cms 中创建物理页面/帖子。
现在创建一个函数(下面的例子)来创建和配置你的动态路由。
// register custom url routes
function register_routes () {
// make sure our DynamicRouter class exists
if(!class_exists('DynamicRouter')) return false;
// create page url /something
DynamicRouter::create(
'^something$',
'router.php',
'Something | ',
[
'post_name' => 'something'
]
);
// create page url /some-other-thing
DynamicRouter::create(
'^some-other-thing$',
'router.php',
'Some Other Thing | ',
[
'post_name' => 'some-other-thing'
]
);
// create page url /parent-thing/child-thing
DynamicRouter::create(
'^parent-thing/child-thing$',
'router.php',
'Child Thing | ',
[
'post_name' => 'child-thing'
]
);
// handle our page routes
DynamicRouter::handle();
}
然后还要确保在您的functions.php
运行上述functions.php
。
// register the routes
register_routes();
然后在主题文件夹的根目录中创建一个名为router.php
的 php 以通过argument
post_name
处理路由,使用下面的代码...
<?php
/**
* router.php handler
*/
// current route array
$route = DynamicRouter::getCurrentRoute();
// handle custom routes
switch ($route['arguments']['post_name']) {
case 'something':
// do your stuff here for url: example.com/something
// get other custom php template or do functions
var_dump('something');
break;
case 'some-other-thing':
// do your stuff here for url: example.com/some-other-thing
// get other custom php template or do functions
var_dump('some-other-thing');
break;
case 'child-thing':
// do your stuff here for url: example.com/parent-thing/child-thing
// get other custom php template or do functions
var_dump('parent-thing/child-thing');
break;
default:
return false;
}
这非常重要,在您更新 wordpress 管理设置中的permalinks
之前,上述代码均无效...
只需转到如上所示的Permalinks
部分,然后点击Save Changes
按钮。 你不需要修改任何当前永久设置,只需简单地打在Save Changes
按钮。
现在您的所有自定义 url 路由(如上面的示例)都将起作用并且不会返回404
页面。
这些 url 现在将执行您在router.php
(在您的主题文件夹中)中配置的router.php
。
如果您对register_routes()
php 配置代码进行了任何更改,则在您再次重新保存永久链接之前,您的新更改将不起作用。
如果您将本地或临时环境部署到实时/生产环境,那么还要确保在设置中重新保存永久链接,以在register_routes()
函数中应用最新配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.