Pass a comment id through url and append the comment post’s slug in the url

Here’s the scenario:
I wrote a custom url rule to pass a comment id to a template and display the comment and comment meta as a single page (eg. http://example.com/reply/56) and it works fine. But now I’m trying to refine this rule to include the comments post slug in the URL. So when I visit 'http://example.com/reply/56' it should map to 'http://example.com/the-post/reply/56'. I’m actually stuck at this point. Here’s what I’ve done till now:
The rule that works:

<?php 
add_rewrite_rule( '^reply/(.*)?$', 'index.php?pagename=reply-page&reply_id=$matches[1]', 'top' );
?>

Added a query_var 'reply_id' for this.

Read More

Now the code I’m trying:

<?php
add_action('init', 'test');
function test()
{
    $reply_struct = '/reply/%reply_id%';
    $wp_rewrite->add_rewrite_tag('%reply_id%', '([^/]+)', 'reply_id=$matches[1]');
    $wp_rewrite->add_permastruct('reply_id', $reply_struct, false);
}

add_filter('post_type_link', 'reply_permalink', 10, 3)
function reply_permalink()
{
    $rewritecode= array(
        '%reply_id%'
    );

    $test = '';
    if ( strpos($permalink, '%reply_id%') !== false ) 
    {
        $i = get_query_var('reply_id'); //Trying to get the comment id, this is where I'll get the post slug and append it to the url
        $test = 'test';
     }

     $rewritereplace = array(
       $test
     );
     $permalink = str_replace($rewritecode, $rewritereplace, $permalink);
     return $permalink;
}

I think when I access the URL 'http://example.com/reply/56', I should get 'http://example.com/test/' or 'http://example.com/reply/test'. But I’m not.

Related posts

Leave a Reply

1 comment

  1. Unless you declare $wp_rewrite as a global in your test function, you’ll be trying to access the local variable $wp_rewrite. This, of course, won’t work.

    Add the line global $wp_rewrite;:

    <?php
    add_action('init', 'test');
    function test()
    {
        global $wp_rewrite;
        $reply_struct = '/reply/%reply_id%';
        $wp_rewrite->add_rewrite_tag('%reply_id%', '([^/]+)', 'reply_id=$matches[1]');
        $wp_rewrite->add_permastruct('reply_id', $reply_struct, false);
    }