douwen6274 2015-09-11 16:02
浏览 21
已采纳

wordpress中的自定义查询var

I'm trying to give a pretty url to my custom CPT (Orders). This is the way im trying:

add_filter('post_type_link', 'custom_post_type_link', 1, 3);
function custom_post_type_link( $link, $post = 0 ){
    if ( $post->post_type == 'orders' ){
            $order_code = 1121000+$post->ID;
      return home_url( 'orders/' .  $order_code);
    } else {
        return $link;
    }
}

Assume that post ID is 32, This code creates the following url: http://www.example.com/orders/1121032

Now i wanna write a code to display the post with post ID=32 in above url. I heard somewhere that i should use custom query vars. But i don't know how to use it. This is the rest of code i've written

add_filter('query_vars', 'custom_add_query_vars');
function custom_add_query_vars($qVars){
$qVars[] = "code";
return $qVars;
}

 add_action( 'init', 'custom_rewrites_init' );
    function custom_rewrites_init(){
        add_rewrite_rule(
            'orders/([0-9]+)?$',
            'index.php?post_type=orders&code=$matches[1]',
            'top' );
    }
  • 写回答

1条回答 默认 最新

  • douling8087 2015-09-11 17:08
    关注

    After adding custom rewrite rules, wordpress needs to be told to activate the new rule.

    Use this method after the add_rewrite_rule function call.

    $wp_rewrite->flush_rules();
    

    Warning: flush_rules is expensive, you definitely don't want to call it on every request. Typically you would put the custom_rewrites_init and flush_rules in a plugin register_activation_hook function.

    If you're lazy, you can just add it to your code once, make a request to the website (which will rewrite the .htaccess rewrite rules), then comment the flush_rules method out.

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

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法