如何获取 WordPress 各类页面的链接
在WordPress项目开发过程,很可能需要获取WordPress 各类页面的链接,包括首页、文章页、Page页面、存档页面等等,今天倡萌就简单分享下获取 WordPress 各类页面的链接的方法。
获取文章或页面链接
直接输出文章或页面的链接:
1 | <?php the_permalink(); ?> |
返回文章或页面的链接,以供调用:
1 | get_permalink(); |
可以使用 echo 输出,结果和直接使用 the_permalink() 一样:
1 | <?php echo get_permalink(); ?> |
获取存档页面链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | function get_current_archive_link( $paged = true ) { $link = false; if ( is_front_page() ) { $link = home_url( '/' ); } else if ( is_home() && "page" == get_option('show_on_front') ) { $link = get_permalink( get_option( 'page_for_posts' ) ); } else if ( is_tax() || is_tag() || is_category() ) { $term = get_queried_object(); $link = get_term_link( $term, $term->taxonomy ); } else if ( is_post_type_archive() ) { $link = get_post_type_archive_link( get_post_type() ); } else if ( is_author() ) { $link = get_author_posts_url( get_query_var('author'), get_query_var('author_name') ); } else if ( is_archive() ) { if ( is_date() ) { if ( is_day() ) { $link = get_day_link( get_query_var('year'), get_query_var('monthnum'), get_query_var('day') ); } else if ( is_month() ) { $link = get_month_link( get_query_var('year'), get_query_var('monthnum') ); } else if ( is_year() ) { $link = get_year_link( get_query_var('year') ); } } } if ( $paged && $link && get_query_var('paged') > 1 ) { global $wp_rewrite; if ( !$wp_rewrite->using_permalinks() ) { $link = add_query_arg( 'paged', get_query_var('paged'), $link ); } else { $link = user_trailingslashit( trailingslashit( $link ) . trailingslashit( $wp_rewrite->pagination_base ) . get_query_var('paged'), 'archive' ); } } return $link; } |
该函数可以输出首页、分类法(自定义分类法、标签、分类)、自定义文章类型的存档页面、作者存档页面、日期存档页面 的链接,包含分页。
获取当前页面链接
如果你不想判断页面类型,只想输出当前页面的链接,可以使用下面的代码:
1 2 3 4 5 6 7 8 | <?php global $wp; $current_url = home_url(add_query_arg(array(),$wp->request)); echo $current_url; ?> |
好了,暂且说到这里。如果大家有什么补充,欢迎留言分享,谢谢。
参考资料:http://wordpress.stackexchange.com/questions/29512/permalink-for-category-pages-and-posts
http://stephenharris.info/how-to-get-the-current-url-in-wordpress/
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
7 条评论
发表评论
要发表评论,您必须先登录。
结合了博主给出的代码,我进行了一个简单的判断,希望能够帮助到大家。
https://www.npc.ink/15806.html
我用这两个函数
the_permalink();
get_permalink();
的时候,为什么会丢失后缀?
我后台是/%postname%.html
得到的链接却是,例如这样的:http://www.wpdaxue.com/get-wordpress-current-link
正确的应该是http://www.wpdaxue.com/get-wordpress-current-link.html
补充,放在边栏的时候出现了这种丢失.html后缀的情况。
很好 Good
能否帮忙写一个获取所有文章、页面及分类链接地址的php语句~~
我想把这些链接写进txt文件。只要http地址,不需要文字。
直接用sql吧
最后那个获取当前页面链接 是wordpress主页啊 不是具体页面当前链接啊 ==