WordPress custom routes for single posts

Question

I created a custom route in my wordpress website. So basically I have 2 wordpress sites a big blog and a smaller one which will grab the blogs from the big one via API.

I got all the posts from the big blog and now I want to create a routing /blog/post-name and I used the following class for it.

class Custom_Post {

    public function init() {
        add_action( 'init', array( $this, 'add_rewrite_rules' ) );
        add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
        add_filter( 'template_include', array( $this, 'add_template' ) );
    }

    public function add_template( $template ) {
        $post_slug = get_query_var( 'post_slug' );
        if ( $post_slug ) {

            return  get_template_directory().'/blogs.php';
        }
        return $template;
    }

    public function flush_rules() {
        $this->rewrite_rules();
        flush_rewrite_rules();
    }

    public function add_rewrite_rules() {
        add_rewrite_rule( 'blog/(.+?)/?$', 'index.php?post_slug=$matches[1]', 'top' );
    }

    public function add_query_vars( $vars ) {
        $vars[] = 'post_slug';
        return $vars;
    }

}
$custom_post = new Custom_Post();
$custom_post->init();

And I have created a blogs.php file in my theme, the file now it’s very simple as I want to grab the permalink and based on it I’ll make requests to the API to grab the post content. However, when I print_r (get_permalink()) I get the permalink as Hello World on any permalinks I go, if I go to /blog/test-post/ or /blog/new-post it will still show me Hello World.

What do I do wrong?

0
, Radu033 3 years 2020-08-22T16:10:21-05:00 0 Answers 43 views 0

Leave an answer

Browse
Browse