WordPress link to page

Link to page by url slug (alias). Does not work with subpages:


<?php

echo get_permalink( get_page_by_path( 'map' ) );

?>

Link to page by title:


<?php

echo get_permalink( get_page_by_title( 'Map' ) );

?>

Link to page relative from homepage:


<?php

echo home_url( '/map/' );

?>

Link to page by slug (alias). Works with subpages:


<?php

function get_permalink_by_slug( $slug ) {

    

    $permalink = null; // Initialize the permalink value

    

    $args = array( // Build the arguments for WP_Query

        'name' => $slug,

        'posts_per_page' => 1,

        'post_type' => 'page'

    );



    // 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;

}





echo get_permalink_by_slug('contact-us');

?>

Leave a Comment