0

I need a <a href="Something Like <?get_contact_page>">Contact Page</a> Code that always links to the Contact page, no matter what is it's ID

There's a page template for contact page.

Is it possible to do this?

I'll gladly provide any further information you need :)

Thanks!!

2

3 Answers 3

1

If the contact page is identified solely by the associated template, you can query for a page with the template name in meta key _wp_page_template:

$args = array(
    'post_type' => 'page',
    'posts_per_page' => 1,
    'meta_query' => array(
        array(
            'key' => '_wp_page_template',
            'value' => 'contact_template.php'
        )
    )
);
$contact_page = new WP_Query( $args );

if( ! empty( $contact_page->posts ) )
    echo get_permalink( $contact_page->post->ID );
1
  • Damn, you beat me! I pretty much provided the same code, except I created a function and account for instances where a template is assigned to more than one page and support returning an array or echoing single keyed values in the return array. Feb 21, 2013 at 1:48
1

You're in luck. Wordpress stores a pages template value in a hidden custom field not visible in the backend but very much exists called, "_wp_page_template". I created the following function which should return an array or a single key of data for you.

I put the code on Github Gist here because it's a little long. I did some testing and it seems to work! Should do what you want it too.

0
0

There is a function called get_page_by_title() that you might find useful:

http://codex.wordpress.org/Function_Reference/get_page_by_title

If the title is always "Contact Page" then you can use

<?php $page = get_page_by_title("Contact Page");?>

<a href="<?php echo get_permalink( $page->ID ); ?>">Link to my Contact Page</a>
5
  • This won't work in the instance of a client website and they decide that the page which was called, "Contact Us" when the site was built would read better if it said, "Get in Contact" which would break this code. Good idea in theory, but you should never assume things will be constant (especially page titles). Feb 21, 2013 at 1:44
  • I agree, I somehow missed the "template" sentence of his question ;-)
    – birgire
    Feb 21, 2013 at 1:48
  • Happens to the best of us man! :) Feb 21, 2013 at 1:50
  • your get_page_by_template() function looks very useful, nice.
    – birgire
    Feb 21, 2013 at 1:57
  • Thanks man. It's probably a little rough around the edges, but seems to get the job done! I might go and clean it up a little later because it's a pretty useful function. Feb 21, 2013 at 2:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.