Php 从wordpress插件输出内容并重写规则
我创建了一个wordpress插件,它在内容上有一个过滤器,寻找一个特定的标签,然后输出插件内容来代替该标签 我现在想使用重写规则来调用插件并在模板中输出数据,但我没有找到太多帮助 有人可以提供一个例子,或一些指导,说明如何使用内置的wp方法添加重写规则,并在输出某些内容的插件中调用my方法Php 从wordpress插件输出内容并重写规则,php,wordpress,plugins,url-rewriting,Php,Wordpress,Plugins,Url Rewriting,我创建了一个wordpress插件,它在内容上有一个过滤器,寻找一个特定的标签,然后输出插件内容来代替该标签 我现在想使用重写规则来调用插件并在模板中输出数据,但我没有找到太多帮助 有人可以提供一个例子,或一些指导,说明如何使用内置的wp方法添加重写规则,并在输出某些内容的插件中调用my方法 理想情况下,我希望shop/匹配,然后在我的插件上将所有内容传递给我的分派方法,这样我就可以拥有shop/category/shirts或shop/product/the cool shirts。我的dis
理想情况下,我希望
shop/
匹配,然后在我的插件上将所有内容传递给我的分派方法,这样我就可以拥有shop/category/shirts
或shop/product/the cool shirts
。我的dispatch方法将处理拆分url的其余部分并相应地调用方法。这会变得相当有趣。我曾经为一个插件做过这件事,我没有它在我面前,所以这是内存不足,但总体思路应该是正确的
<?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();
}
?>
使用正则表达式本身就是一项艰巨的任务,我相信我使用了这个网站:寻求帮助
我还使用FakePage插件来实际显示我的自定义“动态”页面,正如我所说的,但我认为WP中的所有内容在技术上都是动态的
如果您需要更多帮助,请告诉我。不久前我做了一件非常类似的事情,我是通过作弊来做到的 如果您发现内置的重写规则太复杂或无法完成工作,您可能会发现捕获请求和过滤结果更容易。简化版:
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));
}
解释:
parse_request
执行的操作。它根据URL安装其他操作和筛选器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\u redirect
添加一个过滤器,以将普通页面模板替换为特定于产品的模板。如果你想要永久链接,你可能需要调整URL正则表达式