如何在WordPress中添加自定义URL重写功能?

玖比肆 WordPress 35

请提供在WordPress中创建和管理自定义URL重写功能的方法。

回复

共1条回复 我来回复
  • 玖比肆的头像
    玖比肆 评论

    在WordPress中添加自定义URL重写功能可以通过以下步骤实现:

    1. 创建一个自定义插件并激活它。你可以在WordPress的插件目录中找到插件模板,或者自己写一个。创建插件时,可以使用register_activation_hook()函数来完成插件激活时的初始化工作。

    2. 在插件中添加以下代码,以便在WordPress中注册自定义URL重写规则:

    function add_custom_rewrite() {
    add_rewrite_rule(
    '^custom-url/([^/]*)/?',
    'index.php?custom_param=$matches[1]',
    'top'
    );
    }
    add_action('init', 'add_custom_rewrite');

    在这个例子中,我们将所有以“custom-url”作为前缀的URL重写为使用“custom_param”参数的标准WordPress查询。模式“^custom-url/([^/]*)/?”指定了匹配的URL格式,其中括号里的部分是一个捕获组,可以通过$matches数组在WordPress查询中访问。例如,URL“http://example.com/custom-url/foo/”将被解释为查询参数“custom_param=foo”。

    3. 现在你需要刷新WordPress的重写规则,以便它们包含新添加的规则。在插件激活时或修改了URL重写规则后,可以使用flush_rewrite_rules()函数刷新规则:

    function flush_custom_rewrite() {
    flush_rewrite_rules();
    }
    register_activation_hook(__FILE__, 'flush_custom_rewrite');

    4. 最后,你可以在WordPress查询中处理自定义参数“custom_param”,并在模板中使用它来显示相应的内容:

    function custom_param_template($template) {
    global $wp_query;
    $custom_param = $wp_query->get('custom_param');
    if ($custom_param) {
    // 根据自定义参数显示相应的内容
    $custom_template = locate_template(array('custom-template.php'));
    if ($custom_template) {
    return $custom_template;
    }
    }
    return $template;
    }
    add_filter('template_include', 'custom_param_template');

    在这个例子中,我们使用template_include过滤器来检查查询中是否存在“custom_param”,如果存在就返回自定义的模板。你可以根据需要修改此函数,以便于你使用的任何自定义内容。

    2023年 5月 14日 上午11:44 0条评论
微信客服
分享本页
返回顶部
玖比肆(9Bi4)专注于帮助企业实现数字化转型,提供全方位的网站建设、网络运营、网络推广、网络营销和SEO优化等一系列数字化营销服务。