WordPress重写规则的每一篇文章

igetnqfo  于 2022-12-18  发布在  WordPress
关注(0)|答案(1)|浏览(172)

我有一个关于下载应用程序的网站,当访问者点击下载按钮
示例:https://deskrush.com/camp-pinewood-2-apk/
访问者将前往https://deskrush.com/camp-pinewood-2-apk/?target=download&index=0
我希望链接为https://deskrush.com/camp-pinewood-2-apk/download/0
但我想对所有APK帖子模板执行此操作
我试过这个代码,它工作完美,但问题是,我需要刷新重写规则,每次我发布一个新的职位,任何修复这一点?

function simple_blog_add_rewrite_rule()
{
    $args = [
        'numberposts' => -1,
        'post_type' => 'post',
        'meta_key'   => '_wp_page_template',
        'meta_value' => 'single-apk.php'
    ];
    $posts = get_posts($args);
    if ($posts) {

        foreach ($posts as $post) {
            add_rewrite_rule(
                $post->post_name . '/([^/]+)/?$',
                'index.php?name=' . $post->post_name . '&target=$matches[1]',
                'top'
            );
            add_rewrite_rule(
                $post->post_name . '/download/([^/]+)/?$',
                'index.php?name=' . $post->post_name . '&target=download&index=$matches[1]',
                'top'
            );
        }
    }
}
add_action('init', 'simple_blog_add_rewrite_rule');

function simple_blog_add_query_vars_filter($vars)
{
    $vars[] = "target";
    $vars[] = "index";
    return $vars;
}
add_filter('query_vars', 'simple_blog_add_query_vars_filter');
kt06eoxx

kt06eoxx1#

在您的functions.php中
这将处理重定向。

function custom_add_rewrite_rule(){
    
   
    $posts = get_posts( array( 'numberposts' => -1, 'post_type' => 'post') );
  
    if( $posts ){
        
        foreach($posts as $post ){
            
            add_rewrite_rule( 
                $post->post_name . '/download/([^/]+)/?$', 
                'index.php?name=' . $post->post_name . '&target=download&index=$matches[1]', 
                'top' 
            );   
        }
    }
}
add_action('init', 'custom_add_rewrite_rule');

然后添加自定义query_vars

function add_query_vars_filter( $vars ){
    $vars[] = "target";
    $vars[] = "index";
    return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

现在,在模板中,您可以通过访问以下查询来调用它:

get_query_var('target');
get_query_var('index');

相关问题