2009-04-29 80 views
0

我创建了一个wordpress插件,它在the_content上有一个筛选器,查找特定的标签,然后输出插件内容来代替该标签。wordpress插件的输出内容和重写规则

我现在想使用重写规则来调用插件并输出模板中的数据,但我找不到太多帮助。

有人可以提供一个例子,或者有关如何使用内置wp方法添加重写规则以及在输出某些内容的插件中调用我的方法的指导。

理想情况下,我希望shop/能够匹配,然后将商店后的所有内容传递给我的插件上的调度方法,以便我可以有shop/category/shirtsshop/product/the-cool-shirt。我的调度方法将处理分解剩余的url并相应地调用方法。

回答

0

这可以变得相当有趣。我不得不在一个点上为插件做这件事,我没有把它放在我面前,所以这一切都没有记忆,但总的想法应该是正确的。

<?php 

add_action('init', 'rewrite_rules');   


function rewrite_rules() { 
    global $wp, $wp_rewrite; 
    $wp_rewrite->add_rule('(widget1|widget2|widget3)/([a-zA-Z0-9_-]{3,50})$', 'index.php?pagename=listing&category=$matches[1]&subcategory=$matches[2]', 'top'); 
    $wp->add_query_var('category'); 
    $wp->add_query_var('subcategory'); 
    $wp_rewrite->flush_rules(); 
} 

?> 

使用正则表达式是一项艰巨的任务本身,我相信我使用这个网站:http://tools.netshiftmedia.com/regexlibrary/寻求帮助。

我也使用FakePage插件来实际显示我自定义的“动态”页面,因为我称它们,但我想WP中的所有内容在技术上都是动态的。

http://scott.sherrillmix.com/blog/blogger/creating-a-better-fake-post-with-a-wordpress-plugin/

让我知道如果你需要更多的帮助。

0

不久前我做了一件非常相似的事情,我通过作弊做到了。

如果您发现内置的重写规则过于复杂或无法执行作业,您可能会发现更容易捕获请求并过滤结果。一个简化的版本:

add_action('parse_request', 'my_parse_request'); 

function my_parse_request (&$wp) { 
    $path = $wp->request; 

    $groups = array(); 
    if (preg_match("%shop/product/([a-zA-Z0-9-]+)%", $path, $groups)) { 
    $code = $groups[1]; 
    $product = get_product($code); // your own code here 
    if (isset($product)) { 
     add_filter('the_posts', 'my_product_filter_posts'); 
    } 
    } 
} 

function my_product_filter_posts ($posts) { 
    ob_start(); 
    echo "stuff goes here"; // your body here 
    $content = ob_get_contents(); 
    ob_end_clean(); 

    return array(new DummyResult(0, "Product name", $content)); 
} 

为了解释:

  1. parse_request该操作将在数据库中查找之前调用。根据URL,它会安装其他操作和过滤器。

  2. 帖子上的过滤器用假结果替换数据库查找的结果。

DummyResult是一个简单的类具有相同的字段后,或刚好够他们用它来逃脱:

class DummyResult { 
    public $ID; 
    public $post_title; 
    public $post_content; 

    public $post_author; 
    public $comment_status = "closed"; 
    public $post_status = "publish"; 
    public $ping_status = "closed"; 
    public $post_type = "page"; 
    public $post_date = ""; 

    function __construct ($ID, $title, $content) { 
    $this->ID = $ID; 
    $this->post_title = $title; 
    $this->post_content = $content; 

    $this->post_author = get_default_author(); // implement this function 
    } 
} 

有留在读者很多功课以上,但这是一种丑陋的工作方式。您可能需要为template_redirect添加一个过滤器,以将产品特定的页面模板替换为常规页面模板。如果你想要漂亮的固定链接,你可能需要调整URL正则表达式。