Search code examples
wordpresswordpress-4.5.2

Wordpress get_permalink - always return the first post instead of the parent page?


I have set a custom page 'myblog' as 'Posts page' in 'Reading Settings', but why I always get the first post article of 'myblog' instead of 'myblog' itself?

var_dump(get_permalink()); // "http://xxxx.com/myblog/hello-world/"

It should be:

"http://xxxx.com/myblog/"

Any idea why and how I can fix this?


Solution

  • You can do something like this to get the permalink for your blog page (page_for_posts). Below has a couple conditionals checks for fallback, but really the call get_permalink() on the page_for_posts option is what you need.

    function get_my_blogpage_permalink() {
        if( 'page' == get_option( 'show_on_front' ) ) {
    
            return get_permalink( get_option('page_for_posts' ) );
    
        } else {
    
            return home_url();
    
        } 
    }
    
    var_dump(get_my_blogpage_permalink());