問題描述

是否有可能從一個單獨的頁面獲得頁面的永久鏈接?我知道您可以使用 get_page_link()從 ID 獲取頁面的永久鏈接:

<a href="http://<?php%20echo%20get_page_link(40);%20?>">Map</a>

如果有什麼辦法可以像這樣的一個頁面一樣做,我很好奇:

<a href="http://<?php%20echo%20get_page_link('map');%20?>">Map</a>

最佳解決方案

你説的是正確的頁面?不是帖子

這是你想要的:

  1.  get_permalink( get_page_by_path( 'map' ) )
  2.  get_permalink( get_page_by_title( 'Map' ) )
  3.  home_url( '/map/' )

次佳解決方案

我認為這可能會更好:

function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
    global $wpdb;
    $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, $post_type ) );
    if ( $page )
            return get_page($page, $output);
    return null;
}

遵循 WordPress 的”original” get_page_by_title 模式。 (行 3173)

rgds

第三種解決方案

這是 Tom McFarlin on his blog 發表的一種方法:

/**
 * Returns the permalink for a page based on the incoming slug.
 *
 * @param   string  $slug   The slug of the page to which we're going to link.
 * @return  string          The permalink of the page
 * @since   1.0
 */
function wpse_4999_get_permalink_by_slug( $slug, $post_type = '' ) {

    // Initialize the permalink value
    $permalink = null;

    // Build the arguments for WP_Query
    $args = array(
        'name'          => $slug,
        'max_num_posts' => 1
    );

    // If the optional argument is set, add it to the arguments array
    if( '' != $post_type ) {
        $args = array_merge( $args, array( 'post_type' => $post_type ) );
    }

    // Run the query (and reset it)
    $query = new WP_Query( $args );
    if( $query->have_posts() ) {
        $query->the_post();
        $permalink = get_permalink( get_the_ID() );
        wp_reset_postdata();
    }
    return $permalink;
}

它適用於自定義帖子類型和 built-in 帖子類型 (如 postpage) 。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。