dongmiao520892 2018-08-17 08:44
浏览 140
已采纳

Wordpress从function.php加载自定义字段

I'm new in wordpress. I'm trying load custom field of post from function.php. Below is code for function post grid layout function where I use custom field:

 $args = array(
    'post_type'         => 'post',      
    'category_name'     => 'category',  
    'posts_per_page'    => -1,        
    'orderby'           => 'ID',
    'order'             => 'ASC'
  );

  // The Query
  $the_query = new WP_Query( $args );

  // The Loop
  if ( $the_query->have_posts() ) {

    $c = 1;     
    $bpr = 5;   

    while ( $the_query->have_posts() ) : $the_query->the_post();
    ?>
        <div class="member">
          <div class="div-block-image">
            <?php the_post_thumbnail(); ?>
          </div>
          <div class="div-block-29 w-clearfix">
            <div class="text-block-21"><?php the_title(); ?></div>
            <div class="text-block-22">subTitle</div>
            <div class="text-block-23">Text...</div>
            <a href="<?php the_permalink() ?>" class="more w-inline-block">
              <div class="text-block-24">More</div>
            </a>
            <p><?php echo get_post_meta($post->ID, 'linkedin', true); ?></p> // custom-field
            <p><?php echo get_post_meta($post->ID, 'bio', true); ?></p>
            <a href="#" target="_blank" class="link-block w-inline-block">
              <div class="biotxt">bio</div>
            </a>
            <a href="#" target="_blank" class="link-block w-inline-block">
              <div class="text-block-20"></div>
            </a>
          </div>
        </div>
    <?

      if( $c == $bpr ) {
        echo '<div class="clear"></div>';
        $c = 0;     
      }
      $c++;             

    endwhile;
  } else {


    _e( '<h2>Oops!</h2>', 'rys' );
    _e( '<p>Sorry, seems there are no post at the moment.</p>', 'rys' );

  }


  wp_reset_postdata();

I want to load this function from template page. All is loading normally except custom field:

<p><?php echo get_post_meta($post->ID, 'linkedin', true); ?></p>

If run function code from template page its running normal. Any ideas?

  • 写回答

2条回答 默认 最新

  • douzhang6646 2018-08-17 08:56
    关注

    $post->ID is not correct, as it's picking up the ID from the global $post object, which just happens to be the same when you're on the template page, but not necessarily when you're using it in a function in functions.php. Use get_the_ID() instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵