1

我对 WordPress 的永久链接如何工作感到有些困惑,尤其是超出了 Wordpress 自己的使用范围。我的固定链接是这样的:

%post_id%-%post_name%

但是在single.php我想放置另一个指向页面本身的链接,但使用不同的查询字符串。单击它时,永久链接结构可能如下所示:

%mystring%-%post_id%-%post_name%

我想从中获取值$_GET['action'],所以:

$_GET['action'] = %mystring%

我的计划是将其解释为:

if('xx' == $_GET['action']){
   //do xx stuff
} else if ('yy'==$_GET['action']){
   //do yy stuff
} else {
   //show the single post as a single.php always shows
}

这意味着,我想解析$_GET['action']可选的。如果即使它在查询字符串中可用,我也不解析它,我希望页面能够正确呈现。

所以要完成这项工作,我应该在哪里实际工作?另外我如何形成<a>标签的链接?通常我们这样建立链接:

<a href="'.the_permalink().'">TEXT</a>

但你已经知道了,我需要在帖子的原始永久链接之前添加一些文字。

提前致谢。

4

1 回答 1

7

保留您的永久链接结构并查看我对自定义重写规则的回答

您可以像这样调整代码;

function my_rewrite_rules($rules)
{
    global $wp_rewrite;

    // the key is a regular expression
    // the value maps matches into a query string
    $my_rule = array(
        '(.+)/(.+)/?$' => 'index.php?pagename=matches[2]&my_action=$matches[1]'
    );

    return array_merge($my_rule, $rules);
}
add_filter('page_rewrite_rules', 'my_rewrite_rules');


function my_query_vars($vars)
{
    // this value should match the rewrite rule query paramter above

    // I recommend using something more unique than 'action', as you
    // could collide with other plugins or WordPress core

    $my_vars = array('my_action');
    return array_merge($my_vars, $vars);
}
add_filter('query_vars', 'my_query_vars');

现在该页面my_page应该在http://example.com/whatever/my_page和可用http://example.com/my_page

您可以获得whateverusing的价值get_query_var('my_action')

免责声明

在查看子页面或页面附件时,这可能会产生不良影响。你可以通过在你的重写中传递一个标识符来解决这个问题,效果如下:

http://example.com/my_identifier/whatever/page

注意:如果您希望这样做,您将需要编辑重写规则。每次更改代码时,您都需要重新保存永久链接结构以“刷新”规则。

于 2010-07-15T18:57:07.393 回答