Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Adding href to HTML a tag from Custom Post Type

Hi guys,

I've created a custom post type using Custom Post Types UI and Advanced Custom Fields in order to add links to videos to a page.

In order to do it I've created a Custom Field of type text for the URL for the relevant video, with the field named video_link.

I'm having trouble getting this to create an href inside my a tag.

The way I am trying to code it is:-

<?php echo '<a href="' . the_field("video_link") . '">Video Link</a>'; ?>

All this does is write the actual url to my document, followed by "Video Link" which works as a link, but does not have an active href. ie the document shows www.youtube.comVideoLink

When I inspect the document the html which is being generated is:

"www.youtube.com"
<a href>Video Link</a>

I really can't figure this one out.

Any help would be greatly appreciated.

Cheers Don

2 Answers

Bruno Navarrete
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Bruno Navarrete
Full Stack JavaScript Techdegree Graduate 22,246 Points

I'm pretty sure you're not calling it right, go with get_post_meta(), something like:

<?php echo '<a href="' . get_post_meta($post->ID,"video_link",true) . '">Video Link</a>'; ?>

You can also make it a little more readable like this:

<?php $video_link =  get_post_meta($post->ID,"video_link",true); 
    echo '<a href="' . $video_link . '">Video Link</a>';
?>

Hey Bruno,

Thanks for the reply.

That's close, but when I click the link it navigates to a url which is just the current page url with the $video_link url appended.

Any ideas?

Thanks again Don

Bruno Navarrete
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Bruno Navarrete
Full Stack JavaScript Techdegree Graduate 22,246 Points

Don Macarthur are you using it inside of the loop? If so, make sure your post has a value associated with the video_link custom field. If not, replace $post->ID with the post ID of the post you're trying to get the custom field from.

Hi Bruno,

I figured it out. I didn't have the full url including "http://", just from "www." onwards. What a noob...... :-)

Thanks for your help Don