Cannot access ACF field in php code - php

I'm trying to set a custom field featured_image with ACF and can't access it within my php code. First are screenshots of confirming adding the field to the latest post, then after is the php code.
I'm very new to WordPress so I'm expecting this to be a trivial misunderstanding.
I've run var_dump( get_post_meta(get_the_ID()) ); which doesn't show the existence of the 'featured_image' field. I've also created a text custom field, which also doesn't show up.
<?php $my_query = new WP_Query( 'cat=2&posts_per_page=3' );
while ( $my_query->have_posts() ) : $my_query->the_post();
// some variable code
?>
<div class="section-info background3">
<div class="section-details">
// some irrelevant html
<?php
$image = get_field('featured_image');
var_dump( $image );
echo $image;
$featured_image = the_field('featured_image');
var_dump( $featured_image );
$size = 'full'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
?>
</div>
</div>
<?php endwhile; ?>
Which outputs
bool(false) for var_dump( $image );
NULL for var_dump( $featured_image );
Any help is greatly appreciated. Thanks in advance.

First strategy I'd go for in this case is to confirm that the data is present at the DB level.
Run a query against your DB:
SELECT * FROM `wp_postmeta` WHERE `post_id` = YOUR_POST_ID AND `meta_key` LIKE '%featured_image%'
If you can confirm that the data's there, then the next thing to do is ensure that you're passing the right post_id to get_field.
Because you're creating a custom WP_Query, and get_field usually infers ID from the global $post var, there's always potential for confusion. get_field optionally takes a second $post_id parameter.
If you can dump the contents of get_the_ID() inside your custom loop, and confirm that it matches the post whose featured_image field has the data, then send it along in the form of
<?php
$my_query = new WP_Query('cat=2&posts_per_page=3');
while ($my_query->have_posts() ) :
$my_query->the_post();
var_dump(get_the_ID()); // <-- this should match the ID of the post w/ the featured_image
$image = get_field('featured_image', get_the_ID());
var_dump($image);
endwhile;
wp_reset_postdata(); // always good practice to reset the globals after a custom q!

Related

Looping through CMB2 attached posts

I've set up two different custom post types – one for categories and one for posts. I've attached the posts to the categories with the CMB2 plugin. I now want to display all the attached/related posts on each category page. I'm able to display the different ID's from the array, but not the post content.
Trying to get attached posts:
$attached_users = get_post_meta( get_the_ID(), 'pr2_cmb2_attached_posts', true );
foreach ( $attached_users as $user ) {
$employee = get_post( $user );
}
Trying to display the content from the attached posts
<?php while ( have_posts() ) : the_post(); ?>
<?php echo get_the_title($employee);?>
<?php echo get_the_post_thumbnail($employee);?>
<?php endwhile; // end of the loop. ?>
The plugin you are using gives you an array of ids.
Using this ids gives you the possibility to get the post object by using get_post($id).
The function gives you a post object: https://developer.wordpress.org/reference/functions/get_post/
But if you just want to use functions like get_the_title() you only need the post id, not the whole post object.
Well, you already got all the data you need and do not need to get the post object.
The plugins gives you an array of post ids.
// get array of post ids
$attached_users = get_post_meta( get_the_ID(), 'pr2_cmb2_attached_posts', true );
// loop through posts using post ids
foreach ( $attached_users as $user ) {
echo get_the_title( $user );
echo get_the_post_thumbnail( $user, 'thumbnail' );
}

Display specific blog posts using ACF repeater in WordPress

I am trying to create simple repeter filed with ACF on my WordPress site. What I trying to get is to let admin display "Other interesting" blog posts at the bottom of the article.
So far I have created a loop with Wp_Query:
<?php
if( have_rows('featured') ): while( have_rows('featured') ) : the_row();
?>
<div class="container-fluid blog-container medium-container">
<div class="row">
<div class="col-12 blog-one">
<?php
// Get ACF sub field
$get_ids = get_sub_field('article_id');
// Make them display with comma
$show_ids = implode(', ', $get_ids);
// Featured blog list query
$blog = new WP_Query( array(
'posts_per_page' => 5,
'order' => 'DESC',
// Display post with specific ID using ACF repeater field inside array
'post__in' => array($show_ids)
));
...
...
...
<?php endwhile; endif; ?>
So the goal is to display numbers (posts ID's) included by admin on backend - liost them in array inside "post__in". But my code does not work. Any ideas how to fix that?
Advanced Custom Fields has a post object field type. You can configure it to accept multiple posts which it will then return as an array of posts objects (WP_Post) for you. This avoids any need for looping through a repeater field to build the arguments for a query.
Recommended Solution
Firstly, replace the repeater field with a post object field. Set the post type to post, allow null to true, and multiple to true.
You can then adapt your code to display those posts.
Example:
<?php if ( $featured_posts = get_field( 'featured' ) ) : ?>
<div class="container-fluid blog-container medium-container">
<div class="row">
<div class="col-12 blog-one">
<?php foreach ( $featured_posts as $post ) {
setup_postdata( $post );
// Do whatever you need to do to display the post here...
} ?>
. . .
<?php endif;
Documentation: https://www.advancedcustomfields.com/resources/post-object/
Fixing Your Existing Code
If you'd instead prefer to fix the code you already have, you need to rethink the loop.
Each time you iterate over your repeater field, you'll go in and grab the ID that was entered (subfield) for the post. You need to collect all of those up first and then use that to build your query.
Example:
$posts_ids = [];
if ( have_rows( 'featured' ) ) : while( have_rows( 'featured' ) ) : the_row();
$post_ids[] = get_sub_field( 'article_id' );
endwhile; endif;
// Let's drop any blank elements and force them all to integers.
$filtered_ids = array_map( 'intval', array_filter( $post_ids ) );
$blog_query = new WP_Query( [
'post__in' => $filtered_ids,
] );
You could add some more checks, clean this up, etc. Either way you're still far better off letting ACF do this for you and opting for the recommended solution instead.

Wordpress Show Featured Image on Main Page for Blog Snippet/Link

I am looking to show the Wordpress featured images of blog posts alongside the snippets and titles of the blog posts (already there). We don't normally work in PHP so I'm having issues getting the images to show. This is for a client's website that turned out to be WAY more work than we anticipated. The code was originally pulling an image from a section they had titled 'Activities'. We moved away from that content and are using the 'Posts' section again for this.
The code for that area is below. Any help is GREATLY appreciated. Thanks
<?php
$args = array('post_type' => 'post','order'=> 'ASC', 'posts_per_page' =>2,'orderby' => 'date','order'=>'DESC');
// The Query
query_posts( $args );?>
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<?php //$post_thumbnail_id = get_post_thumbnail_id( get_the_ID () ); ?>
<?php /*$image_id = get_post_thumbnail_id(get_the_ID ());
$image_url = wp_get_attachment_image_src($image_id,'post-thumb', true);*/
?>
<li>
<?php //if ( has_post_thumbnail() ){ ?>
<?php if(get_field('show_this_activity_image_in_home_page')){?>
<div class="actImg">
<?php
$attachment_id = get_field('show_this_activity_image_in_home_page');
$size = "post-thumb"; // (thumbnail, medium, large, full or custom size)
$image = wp_get_attachment_image_src( $attachment_id, $size );
OK, the code looks like it is using Advanced Custom Fields which would have been returning the ID of a media item. As you have moved from a Custom Post Type to the native Posts these ACF values will no longer be available.
As you have setup the post data with the_post(); you should be able to get the thumbnail url with get_the_post_thumbnail_url();
See https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/ for an explanation of this function.

Show post excerpts with title and image attachment thumbnail

I am having trouble getting the image attachment to show by the title & excerpt on a Wordpress page in a list. I am using a new WP_Query to generate the list, consisting of 3 posts, from certain categories. Inside the loop, I'm trying to get the first image of each post, retrieving their image IDs with a 'get_children' array (the posts do not have featured images, so I can't use the_post_thumbnail). Using console.log, I can see that I am at least getting the image url for the first item in the list, but not for the others. And even with the one I am getting, I can't get it to display using wp_get_attachment_thumb_file(). Here's the code I have so far:
<div class="inner-left">
<ul class="blog-posts-ul">
<?php
global $wp_query;
$wp_query = new WP_Query(array('order' => 'DESC', 'posts_per_page' => 3, 'cat' => '21,23,689,741,1589'));
if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<?php $attachment = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image' ) );
if ( $attachment ) {
$attachment = current( $attachment );
$image_url = wp_get_attachment_thumb_url( $attachment->ID );
$attachment_id = attachment_url_to_postid( $image_url );
echo '<script>console.log("thumb: "' . $image_url . ')</script>';
}; ?>
<?php the_title(); ?><?php the_excerpt(); ?>
<?php wp_get_attachment_thumb_file( $attachment->ID ); ?>
</li>
<?php endwhile; endif; ?>
</ul>
<?php // Reset Query
wp_reset_query(); ?>
</div><!-- inner-left -->
The test site is at http://testsite.humortimes.com/ if you want to have a look. Scroll down, it's formatted as 3 squares, below the 'Latest Humor Times Faux News Headlines' section. Right now, it's not formatted very well, I plan on having two columns, there's just one showing.
Any help would be appreciated. Thank you.
Stop using console log and start using var_dump ($image_url) ; that will print whatever you have directly on that element.
I dont quite get why you cant use post thumbnail?
After a lot of frustration, I found this nifty function that does just what I want. It queries the database to find the first image of the post, which I guess is the key I was missing. It also tests for a featured image first, so that's taken care of as well. I put the function in my child function file, and just call it when needed on a page.
If you use it, be aware you need to add $size = 'thumbnail'; because, although her description says it'll return a thumbnail, it was returning full size images. This variable is used throughout the function, though, so you just need to give it a value.
Thanks, Amberweinberg!

Hide post from displaying in wordpress

I've inherited a wordpress site and I am having a hard time understanding how posts are being displayed. I want to hide a couple from view (but still be able to give out a URL to view them). I'm not familiar with the way a particular template was coded. The template outputs an image and blurb for each event in a certain category. The meat of code that is spitting this out look like this:
<?php
$args['post_type']='seasonalevents';
$args['posts_per_page']=-1;
$args['orderby'] = 'menu_order';
$activities = new WP_Query( $args );
while ( $activities->have_posts() ) : $activities->the_post();
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'thumb_345_154', true);
?>
Is there any way I can exclude post ID's within the code above? Any hints or tips? Feel totally baffled by this. The variables are defined above this code snippet. I can post if needed.
thanks!
The wordpress-y way to do this would be to add an element to the $args array under the three you already have:
$args['post__not_in'] = array(123,456,789);
Where 123, 456, and 789 are the ids of the posts you want to exlude from showing on this page.
So your whole code would look like:
<?php
$args['post_type']='seasonalevents';
$args['posts_per_page']=-1;
$args['orderby'] = 'menu_order';
$args['post__not_in'] = array(123,456,789);
$activities = new WP_Query( $args );
while ( $activities->have_posts() ) : $activities->the_post();
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'thumb_345_154', true);
?>
Yes there is!
You can get the current post's ID using http://codex.wordpress.org/Function_Reference/get_the_ID
I recommend you looking into 'the loop' and what that is.
This code snippet should do the job :-)
...
$not_these = array(1, 2, 7 /* array with post id's you got somewhere */);
while ( $activities->have_posts() ) : $activities->the_post();
if(in_array(get_the_ID(), $not_these)) continue;
...
The easiest solution is to unpublish that post from your administration panel.
Or
<?php
// The Loop
while($query->have_posts()):
$query->the_post();
if(get_the_ID()!=YOUR_POST_ID):
?>
<!-- Show Post -->
<?php
endif;
endwhile;
?>

Categories