Arazam
Arazam

Reputation: 71

Show Custom Field From Custom Post Type In Template

Been learning how to add custom post types and custom fields manually without plugins by pulling pieces of code from here and there and adding them into functions.php. Here is how I added the custom field to custom post type

function add_ads_meta_boxes() {
    add_meta_box("ads_contact_meta", "URL", "add_custom_ads_meta_box", "ads", "normal", "low");
}
function add_custom_ads_meta_box()
{
    global $post;
    $custom = get_post_custom( $post->ID );

    ?>
    <style>.width99 {width:99%;}</style>
    <p>
        <input type="text" name="link-url" value="<?= @$custom["link-url"][0] ?>" class="width99" />
    </p>
    <?php
}
function save_ads_custom_fields(){
  global $post;

  if ( $post )
  {
    update_post_meta($post->ID, "link-url", @$_POST["link-url"]);
  }
}
add_action( 'admin_init', 'add_ads_meta_boxes' );
add_action( 'save_post', 'save_ads_custom_fields' ); 

I can see the field in the post type, and it saves the added info. Now, here is how I'm adding it to the site

<div class="customadwrap">
<?php  $args = array( 'post_type' => 'ads');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
 ?>

<a href="<?php echo get_post_meta($post->ID, 'link-url', true); ?>"> 
 <?php the_title(); ?>
 </a>
 <?php 
endwhile;
 ?>
</div>

Title shows up no problem, but the url entered is not. How do I make the fref to work?

Upvotes: 0

Views: 679

Answers (1)

Peter HvD
Peter HvD

Reputation: 1661

In your second bit of code, replace $post->ID with get_the_ID().

Upvotes: 1

Related Questions