dongmufen8105 2016-07-02 04:20
浏览 6
已采纳

WP url:localhost / page / variable

is there a way for Wordpress to know that when I type: localhost / foo / bar

FOO is an actual page ( rendered with my own script as a template ) and BAR is given VAR that all the stuff displayed on FOO depends on ?

For now, when I type localhost/foo I get the page, everything works okay. localhost/foo/bar produces a 404 error, though.

Obviously, no BAR page exists. How to turn BAR from being rendered as a page to be rendered as a variable?

  • 写回答

1条回答 默认 最新

  • doudou20145 2016-07-02 05:19
    关注

    Here is my solution to your problem:

    in your functions.php file you should add the following code:

    add_action( 'init', 'custom_rewrite_rules' );
    function custom_rewrite_rules() {
        add_rewrite_rule(
            '^(katalog)/([^/]+)/?$',
            'index.php?pagename=$matches[1]&bar_variable_name=$matches[2]',
            'top'
        );
    }
    
    add_action( 'init', 'custom_rewrite_tags');
    function custom_rewrite_tags() {
        add_rewrite_tag( '%bar_variable_name%', '([^/]+)' );
    }
    

    Note: In the above code I have name the bar variable bar_variable_name. If you like, you can replace the variable name with one that better meets your needs.

    Note #2: In case you need to rename the page to something else, then replace the katalog with the slug of the new page.

    After you have done with it, you should go in your WordPress dashboard, in the "Settings / Permalinks" and just save the current settings you use. This way you are going to flush the ReWrite rules of the WordPress.

    Then in your theme folder, either create a template page or in your page.php file and do the following test to check if you are in a page comming with bar and what is the bar value:

    global $wp_query;
    
    if (
        isset( $wp_query->query ) &&
        key_exists( 'bar_variable_name', $wp_query->query ) &&
        ! empty( $wp_query->query['bar_variable_name'] )
    ) {
        $image_path = $wp_query->query['bar_variable_name'];
    
        echo "This is my folder name : " . $image_path;
        die();
    }
    

    Note: In case you replaced the bar_variable_name in the previews code block, then update this code by replacing also the bar_variable_name here too.

    If all are going well, when you will visit the katalog page with an extra segment in the URL you should see the segment string in your page.

    ie: if you visit the page /katalog/beers/ the output it should be : This is my folder name : beers.

    If that does what you need, then you can use the $image_path as variable inside your custom page to display what ever you like.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部