在WordPress项目开发过程,很可能需要获取WordPress 各类页面的链接,包括首页、文章页、Page页面、存档页面等等,今天倡萌就简单分享下获取 WordPress 各类页面的链接的方法。

获取文章或页面链接

直接输出文章或页面的链接:

  1. <?php the_permalink(); ?>

返回文章或页面的链接,以供调用:

  1. get_permalink();

可以使用 echo 输出,结果和直接使用 the_permalink() 一样:

  1. <?php echo get_permalink(); ?>

获取存档页面链接

  1. function get_current_archive_link( $paged = true ) {
  2.         $link = false;
  3.         if ( is_front_page() ) {
  4.                 $link = home_url( '/' );
  5.         } else if ( is_home() && "page" == get_option('show_on_front') ) {
  6.                 $link = get_permalink( get_option( 'page_for_posts' ) );
  7.         } else if ( is_tax() || is_tag() || is_category() ) {
  8.                 $term = get_queried_object();
  9.                 $link = get_term_link( $term$term->taxonomy );
  10.         } else if ( is_post_type_archive() ) {
  11.                 $link = get_post_type_archive_link( get_post_type() );
  12.         } else if ( is_author() ) {
  13.                 $link = get_author_posts_url( get_query_var('author'), get_query_var('author_name') );
  14.         } else if ( is_archive() ) {
  15.                 if ( is_date() ) {
  16.                         if ( is_day() ) {
  17.                                 $link = get_day_link( get_query_var('year'), get_query_var('monthnum'), get_query_var('day') );
  18.                         } else if ( is_month() ) {
  19.                                 $link = get_month_link( get_query_var('year'), get_query_var('monthnum') );
  20.                         } else if ( is_year() ) {
  21.                                 $link = get_year_link( get_query_var('year') );
  22.                         }
  23.                 }
  24.         }
  25.         if ( $paged && $link && get_query_var('paged') > 1 ) {
  26.                 global $wp_rewrite;
  27.                 if ( !$wp_rewrite->using_permalinks() ) {
  28.                         $link = add_query_arg( 'paged', get_query_var('paged'), $link );
  29.                 } else {
  30.                         $link = user_trailingslashit( trailingslashit( $link ) . trailingslashit( $wp_rewrite->pagination_base ) . get_query_var('paged'), 'archive' );
  31.                 }
  32.         }
  33.         return $link;
  34. }

该函数可以输出首页、分类法(自定义分类法、标签、分类)、自定义文章类型的存档页面、作者存档页面、日期存档页面 的链接,包含分页。

获取当前页面链接

如果你不想判断页面类型,只想输出当前页面的链接,可以使用下面的代码:

  1. <?php
  2.     global $wp;
  3.     $current_url = home_url(add_query_arg(array(),$wp->request));
  4.     echo $current_url;
  5. ?>

好了,暂且说到这里。如果大家有什么补充,欢迎留言分享,谢谢。

参考资料:

http://wordpress.stackexchange.com/questions/29512/permalink-for-category-pages-and-posts

http://stephenharris.info/how-to-get-the-current-url-in-wordpress/

 

 

 

Last modification:February 16, 2019
If you think my article is useful to you, please feel free to appreciate