【问题标题】:Get one post by post type and ID inside of a loop在循环内按帖子类型和 ID 获取一篇帖子
【发布时间】:2016-09-14 13:33:39
【问题描述】:

我正在尝试在循环中执行循环。但它并没有像它应该的那样返回我的价值观。请参阅代码中的注释。它更好地解释了它。任何意见,将不胜感激!

 /* LETS PRETEND I HAVE MY FIRST QUERY HERE */
 /* THEN THE LOOP */     
 while ( $the_query->have_posts() ) : $the_query->the_post();  

     // Establish ID of the clinic from clinicpromo custom field
     $clinicid = get_custom_field('assignclinic');  

    /* MY TROUBLE QUERY:*/

    /* GET CLINIC BY ID - This should only retrieve 1 clinic */
    $argsthree = array(   
      'ID' => $clinicid,
      'post_type' => 'clinics'
     );

  $clinics_array = get_posts( $argsthree ); 

   /* I AM TRYING TO QUERY THE CLINIC THAT THE PROMO BELONGS TO AND SAVE   
      ITS' CUSTOM FIELDS AND REGULAR FIELDS AS VARIABLES TO BE USED LATER */

    foreach ( $clinics_array as $clinic ) :  

      $clinictitle = get_the_title($clinicid);  
      $cliniccity = get_custom_field('cliniccity');
      $clinicstate = get_custom_field('clinicstate');  

  endforeach; 

 // How can I use these variables outside of the loop? Or is it possible?
 // I keep getting "ArrayArrayArray... as results

     echo $clinictitle;
     echo $cliniccity;
     echo $clinicstate; 

  /* These variables will be mixed with content from the first query of clinicspromo

/=============简化更新=========================/

    $clinicid = get_custom_field('assignclinic'); // This is the ID of the clinic I am retrieving from ClinicPromos 

     $clinicpost = get_post($clinicid,array('post_type=clinicpromos'));



      $clinictitle = get_the_title($clinicpost->ID);  
      $cliniccity = get_post_custom_values('cliniccity', $clinicpost->ID);
      $clinicstate = get_post_custom_values('clinicstate', $clinicpost->ID);  

     echo $clinictitle;
     echo $cliniccity;
     echo $clinicstate; 

【问题讨论】:

  • 请尝试用户 $clinics_array = get_posts( $clinicid );
  • 好的,我这样做了,标题现在可以使用,但自定义字段不是。这就是我将自定义字段更改为 get_post_custom_values('cliniccity', $clinicpost->ID);
  • 如何将自定义字段变成变量?
  • 我更新了我现在拥有的内容
  • 自定义字段是唯一无法正确显示的字段

标签: php wordpress foreach while-loop


【解决方案1】:

试试这个方法,因为你已经得到了post id,所以你不需要get post

$clinicid = get_custom_field('assignclinic');

你不需要这个$clinicpost = get_post($clinicid,array('post_type=clinicpromos'));

  $clinictitle = get_the_title( $clinicid);  
  $cliniccity = get_post_meta($clinicid, 'cliniccity', true);
  $clinicstate = get_post_meta($clinicid,'clinicstate', true); 

 echo $clinictitle;
 echo $cliniccity;
 echo $clinicstate;

【讨论】:

  • 我已经编辑了答案,使用 'get_post_meta' 代替 'get_post_custom_values'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 2019-05-28
  • 2017-04-23
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2020-05-06
相关资源
最近更新 更多