2016-04-12 46 views
0

我想創建一個WordPress插件,它從一個自定義的表中提取數據(如產品)WordPress的插件拋出404

我想有一個與該插件,所以我已經處理了「產品」開頭的網址:

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'); 
    } 
} 

在$ pluginPath'/模板/ products.php我:

<?php 
get_header(); ?> 
My content 
<?php get_sidebar(); ?> 
<?php get_footer(); ?> 

然而,當頁面呈現WP似乎插入404碼(以及products.php )和th Ë管理菜單欄不會呈現

我需要知道:

  1. 如何WordPress的檢測404 - 我需要設置的東西來告訴它不要亂扔呢?
  2. 爲什麼管理欄不顯示 - 我從搜索看到這通常是由於插件 - 但不知道如何開始調試...

任何指針將運行超出谷歌的鏈接是巨大的嘗試。

回答

1

你不會以最理想的方式去解決這個問題。 WordPress的功能來說明URL重寫。你現在做的是讓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'; 
     }); 
    } 
} 
+0

謝謝! - 這對我來說是非常痛苦的找到文件,這只是說明了:) –