[英]Wordpress plugin throwing 404
I am trying to create a wordpress plugin which pulls data from a custom table (eg products) 我正在尝试创建一个wordpress插件,该插件可以从自定义表格(例如产品)中提取数据
I would like to have any URL that begins with "products" handled by the plugin so I have: 我想要任何以插件处理的“产品”开头的URL,所以我有:
add_action('parse_request', 'my_url_handler');
function my_url_handler()
{
// Manually parse the URL request
if(!empty($_SERVER['REQUEST_URI']))
{
$urlvars = explode('/', $_SERVER['REQUEST_URI']);
}
if(isset($urlvars[1]) && $urlvars[1] == 'products')
{
$pluginPath = dirname(__FILE__);
require_once($pluginPath.'/templates/products.php');
}
}
In $pluginPath.'/templates/products.php I have: 在$ pluginPath中。'/ templates / products.php中,我有:
<?php
get_header(); ?>
My content
<?php get_sidebar(); ?>
<?php get_footer(); ?>
However, when the page is rendered WP appears to insert the 404 code (as well as products.php) and the admin menu bar isn't rendered 但是,呈现页面时,WP似乎会插入404代码(以及products.php),并且不会呈现管理菜单栏
What I need to know: 我需要知道的是:
Any pointers would be great as running out of google links to try. 任何指针都将非常有用,因为用尽Google链接即可尝试。
You are not going about this in the most optimal way. 您并不是以最佳方式进行此操作。 Wordpress has functions to account for URL rewrites.
WordPress具有用于URL重写的功能。 What you are doing has now way of letting Wordpress know that the request is processed and not a 404. Here is what you should be doing instead:
现在,您正在做的事情是让Wordpress知道请求已被处理而不是404的方法。这是您应该做的:
add_action( 'init', 'yourplugin_rewrite_init' );
function yourplugin_rewrite_init() {
add_rewrite_rule(
'products/([0-9]+)/?$', // I assume your product ID is numeric only, change the regex to suit.
'index.php?pagename=products&product_id=$matches[1]',
'top'
);
}
add_filter( 'query_vars', 'yourplugin_add_query_vars' );
function yourplugin_add_query_vars( $query_vars ) {
$query_vars[] = 'product_id';
return $query_vars;
}
add_action( 'template_redirect', 'yourplugin_rewrite_templates' );
function yourplugin_rewrite_templates() {
if ( get_query_var( 'product_id' ) ) {
add_filter( 'template_include', function() {
return plugin_dir_path( __FILE__ ) . '/products.php';
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.