The question:
I have set the blog to be a different page other than the home page.
I want to have a link from single.php to this blog page.
Is there any function that pulls out URL for the blog ?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
As of WordPress 4.5 you can use:
get_post_type_archive_link( 'post' );
This handles the logic of getting the correct URL regardless of whether posts show up on the homepage or in a specified page.
Method 2
To build on Sagive’s answer, you’ll want to wrap the ID in get_permalink() to get the actual link.
<a href="<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>" rel="nofollow noreferrer noopener">Our Blog</a>
Method 3
Best way to check the option before setting the permalink is as follows:
if ( get_option( 'page_for_posts' ) ) {
echo '<a href="'.esc_url(get_permalink( get_option( 'page_for_posts' ) )).'" rel="nofollow noreferrer noopener">'.esc_html__( 'Blog', 'textdomain' ).'</a>';
} else {
echo '<a href="'.esc_url( home_url( '/' ) ).'" rel="nofollow noreferrer noopener">'.esc_html__( 'Blog', 'textdomain' ).'</a>';
}
Method 4
You can use get_option
of page_for_posts
to get the page ID to either assign it to a variable or to echo it if you wish to do so.
<?php $postsPageId = get_option('page_for_posts'); ?>
<a href="index.php?p=<?php echo $postsPageId; ?>" rel="nofollow noreferrer noopener">Our Blog</a>
For additional information of the defualt get_option visit: Option Reference
Method 5
Agree with the Hugh Man that it is better to check the option before echoing the link, but it is possible to set the static page as a front page and leave the posts page empty. In this case, the link will just point to the home URL. A better approach is to provide a fallback to the posts archive page. Something like this:
function slug_all_posts_link() {
if ( 'page' == get_option( 'show_on_front' ) ) {
if ( get_option( 'page_for_posts' ) ) {
echo esc_url( get_permalink( get_option( 'page_for_posts' ) ) );
} else {
echo esc_url( home_url( '/?post_type=post' ) );
}
} else {
echo esc_url( home_url( '/' ) );
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0