首页 > 解决方案 > 在模板中显示自定义帖子类型的自定义字段

问题描述

一直在学习如何在没有插件的情况下手动添加自定义帖子类型和自定义字段,方法是从这里和那里提取代码片段并将它们添加到 functions.php 中。这是我将自定义字段添加到自定义帖子类型的方式

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' ); 

我可以在帖子类型中看到该字段,它会保存添加的信息。现在,这是我将其添加到网站的方式

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

标题显示没有问题,但输入的网址却没有。如何使 fref 工作?

标签: phpwordpress

解决方案


在您的第二段代码中,替换$post->IDget_the_ID().


推荐阅读