mrquad mrquad - 4 months ago 6
PHP Question

Display custom field for logged in user

I am trying to get an acf created custom field via querying all posts.

I tried the following:

<?php
if ( is_user_logged_in() ):

global $current_user;
$current_user = wp_get_current_user();
$author_query = array('post_status' => array( 'draft' ),
'author' => $current_user->ID,
'meta_query' => array(
array(
'key' => 'wpgamail_options',
'key' => 'ganalytics_settings',
),
),);
$author_posts = new WP_Query($author_query);
while($author_posts->have_posts()) : $author_posts->the_post();
?>
<tr>
<td>
<?php the_title(); ?>
</td>
<td>
<?php $post_date = get_the_date(); echo $post_date; ?>
</td>
<td>
<?php $field = get_field('wpgamail_options', $author_posts->the_post()->ID, true); echo $field['nextfetchtime']; ?> //here I get the error
</td>
</tr>
<?php
endwhile;

else :
echo "You are not logged in. Please log in!";
endif;
?>


I get the following error message:


Notice: Trying to get property of non-object in Unknown on line 0 Call
Stack: 3.9772 231600 1. {main}() /home/ubuntu/workspace/index.php:0
3.9774 232048 2. require('/home/ubuntu/workspace/wp-blog-header.php') /home/ubuntu/workspace/index.php:17 4.6285 8745184 3.
require_once('/home/ubuntu/workspace/wp-includes/template-loader.php')
/home/ubuntu/workspace/wp-blog-header.php:19 4.6328 8788784 4.
include('/home/ubuntu/workspace/wp-content/themes/twentysixteen/page-create-report.php')
/home/ubuntu/workspace/wp-includes/template-loader.php:75 1469999466


Any suggestions what I am doing wrong by using the
[get_field()][1]
function?

I appreciate your replies!

Answer

You're using $author_posts->the_post()->ID while you should use get_the_ID() (not the_ID() which displays ID).
Fixed code.

<?php 
$field = get_field('wpgamail_options', get_the_ID(), true);
echo $field['nextfetchtime']; ?> 

Also, you don't need to do $current_user = wp_get_current_user();. $current_user global already contains current user object.

Comments