【问题标题】:Wordpress load custom field from funtion.phpWordpress 从 function.php 加载自定义字段
【发布时间】:2018-08-17 08:44:37
【问题描述】:

我是 wordpress 新手。我正在尝试从 function.php 加载自定义的帖子字段。以下是我使用自定义字段的功能后网格布局功能的代码:

 $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();

我想从模板页面加载这个功能。除自定义字段外,所有内容均正常加载:

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

如果从模板页面运行功能代码则运行正常。有什么想法吗?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    $post-&gt;ID 不正确,因为它从全局 $post 对象中获取 ID,当您在模板页面上时恰好是相同的,但在您使用它时不一定functions.php 中的函数。请改用get_the_ID()

    【讨论】:

      【解决方案2】:

      在您的自定义循环中,您需要更新这些以使用:get_the_ID() 而不是 $post->ID

      <p><?php echo get_post_meta(get_the_ID(), 'linkedin', true); ?></p>
      

      这将从当前循环中获取 ID。

      参考:https://developer.wordpress.org/reference/functions/get_the_id/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-21
        • 2017-11-05
        相关资源
        最近更新 更多