Get ACF field data within foreach loop - wordpress - php

I have a custom image field for all pages with a specific page template (using ACF plugin).
I'm querying for these pages like so:
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => 'services-page.php'
));
Then I'm displaying pages with a foreach loop:
if( $posts ): ?>
<?php foreach( $posts as $post ): setup_postdata( $post );?>
//content goes here
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Now I want to access the custom field to display inside the loop. But, below doesn't work. I'm guessing because ACF fields don't get appended to the post object.
//Does not work
$image = $post -> services_block_image
ACF has the get_field() function, but what can I do to get the field for each of the posts from my original query? Found ACF docs to be rather confusing on this (goes without saying I'm a bit new to PHP).

Within loop use get_field function to get the image.
check below code for your reference.
$image = get_field('services_block_image'); // get the image
if( !empty($image) ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?>

Related

Getting related articles in WordPress not working

I am trying to display all the posts with the same category in WordPress however its not displaying correctly and instead is just showing everything.
Here is the php code:
<?php
$related = get_posts( array(
'category_in' => wp_get_post_categories($post->ID),
'numberposts' => 3,
'post_not_in' => array($post->ID) ) );
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>
<div class="post">
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
<h3><?php the_title();?></h3>
</a>
</div>
<?php }
wp_reset_postdata();
?>
Its taken from here: https://wordpress.stackexchange.com/questions/41272/how-to-show-related-posts-by-category
And if it helps here is the link to the website in question where the code isnt working:http://u1f8aki.nixweb23.dandomain.dk/cat-4-post-test/
The code in question is further down the page under the red text. You can see the category at the top in the breadcrumbs.
There are quite errors in your code, and I'm sure atleast one of them are the culprit in giving you the wrong result.
I've refactored your code with some comments explaining what and why has been changed:
<?php
// For readability, save our categories in a variable for later use.
// $post->ID has been replaced with get_the_ID(), $post might not be accessible depending if you're exposing $post as a global or not.
$categories = wp_get_post_categories(get_the_ID());
/*
Instead of using get_posts(), use the recommended Wordpress loop in the form of WP_Query().
We start by defining our arguments for the loop
*/
$args = array(
'category_in' => $categories, // here we use variable for readability
'posts_per_page' => 3, //numberposts and posts_per_page has the same function, but posts_per_page is the more common of the two (IMO)
'post__not_in' => array(get_the_ID()) // you were missing a '_', ie post_not_in instead of post__not_in
);
// Start the loop
$query = new WP_Query($args);
if($query->have_posts()): while($query->have_posts()): $query->the_post();
// No need to setup or reset postdata when using this method, it does it for you!
?>
<div class="post">
<a href="<?php the_permalink(); ?>">
<?php
if( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
<?php
// the_title() actually takes opening tag and closing tags as arguments in its function. So add the <h3> code like this.
the_title('<h3>', '</h3>');
?>
</a>
</div>
<?php endwhile; endif; ?>
Long story short, your code prolly isn't working because of the miss-named arguments. If you don't feel like replacing your code with my example, just change your arguments from numberposts to posts_per_page, and post_not_in to post__not_in.
If it still isn't working, check what wp_get_post_categories(get_the_ID()) is returning for each post, and make sure all posts aren't sharing some category you missed.
Edit: numberposts is actually a valid argument, changed my answer to reflect this.

Retrieve post taxonomy inside get_posts()

I am retrieving posts from my Custom Post Type using the built-in Wordpress get_posts() function. I am able to print/retrieve all of the data for the post except the post's taxonomy term (which I registered as a custom taxonomy using register_taxonomy( 'developer_category', 'developer', $args ); Here's my code for displaying the posts...
<?php $devs = get_posts([
'post_type' => 'developer',
'posts_per_page' => '8',
'orderby' => 'rand'
]); ?>
<div id="loaded-devs">
<?php $post_count = 1; ?>
<?php foreach ($devs as $dev): ?>
<div class="loaded-dev" id="dev<?php echo $post_count; ?>">
<?php echo get_the_post_thumbnail( $dev->ID, 'small' ); ?>
<h2><?php echo $dev->post_title; ?></h2>
<p><?php echo get_the_terms($dev->ID); ?> Developer</p>
</div>
<?php $post_count ++; ?>
<?php endforeach; ?>
</div>
<?php wp_reset_postdata(); ?>
Using get_cat_name as I am above returns 'Uncategorized', I believe because it's looking for the default Wordpress category and I am categorizing by custom taxonomy. How can I display my post's taxonomy name inside get_posts() ?
You need to pass the taxonomy to get_the_terms():
$my_tax_terms = get_the_terms( $dev->ID, 'developer_category' );
This returns an array of terms that you can then loop through. Also, you can't just echo it because it's an array. You can print_r( $my_tax_terms ) to see what you get, but you'll need to loop through the results to pull the information you want.

ACF: Display Fields in a template based on Cpt ui

I have created a custom post type based on CPT Ui I am tryin to display the items of that in a template ideally what I want to be able to do is
www.siteurl.com/profile/profilename
Hence why I have created a template page with the following code.
But I dont no how I would get profilename into my query posts and then display the relivent data this is what I have tired so far to get id and permalink to display but to no avail.
I really want to be able to do it like how the documentation states. Ideally i would suspect my best approach would be to check if user has created a profile in the front end if not direct them to do so?.
Display a field
<p><?php the_field('field_name'); ?></p>
http://www.advancedcustomfields.com/resources/code-examples/
<?php
/**
* Template Name: Profile Page
*/
get_header(); ?>
<?php get_template_part( 'page', 'title' ); ?>
<div class="width-container">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php endwhile; // end of the loop. ?>
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'profiles',
'meta_key' => 'profilename',
'meta_value' => 'david'
));
if($posts)
{
echo '<ul>';
foreach($posts as $post)
{
echo '<li>' . get_the_title($post->ID) . '</li>';
}
echo '</ul>';
}
?>
<?php get_sidebar(); ?>
</div><!-- close .width-container -->
<?php get_footer(); ?>
If anyone has done anything simlar maybe I should be using current user but again i dont no how to link that up to acf as I am new to that plugin
Perhaps you could try another approach and build a custom query with WP_Query instead. The example bellow use the WP_Query object rather than the get_posts function, however the arguments and logic remain the same.
This implies we will find all posts that have a post_type of profiles where the ’custom field’ profilename is equal to david. The custom field ‘profilename’ in this case could be a text field, a radio button or a select field (something that saves a single text value).
<?php
/**
* Template Name: Profile Page
*/
get_header();
$user = get_post_meta($post->ID, 'profilename', true); // saving the field value in a $variable can help to build a more dynamic WP_Query...
?>
<?php get_template_part( 'page', 'title' ); ?>
<div class="width-container">
<h1>__('Listing Posts by:', 'text_domain');</h1>
<?php echo '<p class="text-center">' . esc_html( $user ) . '</p>'?>;
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'profiles',
'meta_key' => 'profilename',
'meta_value' => $user // retrieve the actual profilename field value
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
<?php get_sidebar(); ?>
</div><!-- close .width-container -->
<?php get_footer(); ?>
The code above is an example of how to query ("get and display") posts in WP using WP_Query object within a template based on custom field called ‘profilename’ which has a value of ‘david’ or whatever data is saved inside the field as per your example.
Perhaps you want to display the relevant data (values) of the custom fields you've created for the WP default user profile page, and if this is the case, you should follow another approach and instead of query posts you simply output the fields a user might fill on their profile. In order to that you could Get values from a user.
This example will display the field 'profilename' value from a user with an ID of 1.
<?php the_field('field_name', 'user_1'); ?>
Within your loop you could use $user_ID = get_current_user_id(); to retrieve the user_id as follows:
<?php
/**
* Template Name: Profile Page
*/
get_header();
$user = get_post_meta($post->ID, 'profilename', true); // saving the field value in a $variable can help to build a more dynamic WP_Query...
$user_ID = get_current_user_id();
?>
<?php get_template_part( 'page', 'title' ); ?>
<div class="width-container">
<h5>__('Listing Posts by:', 'text_domain');</h5>
<h1><?php the_field('profilename', '$user_ID'); ?>;</h1> // this will retrieve the data/value saved in the 'profilename' field for the current user
...
Check ACF's Query Posts by Custom Fields documentation for other ways to retrieve an array of post objects from the database using native WP functions.

Wordpress get Post infomation from attachment

I was trying to make a template to show all used image in wordpress blog, and link to the post which has the image attached, like a gallery or portfolio page, but I can not get the link nor title to the post single page.
I've made this far:
<?php
$post_parent = get_post($post->ID, ARRAY_A);
$parent = $post_parent['post_parent'];
$paged = ( get_query_var( 'paged' ) ) ? get_query_var('paged') : 1;
$attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC', 'paged' => $paged, 'posts_per_page' =>9,) );
?>
And the foreach:
<?php foreach($attachments as $id => $attachment) :
$img_title = $attachment->post_title;
$img_caption = $attachment->post_excerpt;
$img_description = $attachment->post_content;
?>
So I looked up the codex and found how to get the img url like this:
<?php if ( have_posts() ) : ?>
<li>
<?php $image_attributes = wp_get_attachment_image_src( $id, full ); // returns an array
if( $image_attributes ) {?>
<img src="<?php echo $image_attributes[0]; ?>" alt="<?php echo $img_alt; ?>" title="<?php echo $img_title; ?>" />
<?php
echo $post->post_parent;
?>
<p><a href="<?php
echo get_post($id)->post_parent; ?>">link</a></p>
<?php } ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
These codes above works great, it shows all images attached in an ul li list.
Then I want to add a link to the parent POST in the loop, using something in the foreach like:
<p>Post link</p>
but it returns a link to nothing or returns a "0", if I "echo $id", it return the attachment id but not the Post ID (Post id is what I want).
Please how to get the parent post ID or simply get the post link and title in the loop above? Help!
Thank you!
Find the answer now.
I use the normal query to get all posts, and that query search for the img tag in content( or its featured image) then show that image in loop, optionally to show excerpt below that image, then this template is done.
I was thinking about getting attachments in media library but it is not the right way, some media are not even attached to any posts so it’s a dead end.
But to query post and make that query select posts with “<img” is somewhat way more better than query attachments, and easy to understand too.

wordpress query_posts alternative

I am creating a website that integrates a portfolio which uses custom post types, this was done based off of this tutorial.
So far it is exactly what I am looking for and works great except for one small detail. In order to fetch the posts from the new custom post type the author of the tutorial used the query_posts() codex. So the top of my portfolio page looks like this:
<?php
/* Template Name: Portfolio */
get_header();
query_posts('post_type=portfolio&posts_per_page=10');
?>
What I gather is that this declares "get posts from "post type" portfolio and show 10 per page". My problem is that I can't go get content from my portfolio page. It seems that now my portfolio page only fetches the content from the custom post type, and I can't use:
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
to get content from the actual page.
This is what I am trying to do, I've replaced:
query_posts('post_type=portfolio&posts_per_page=10');
with:
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( is_page( 8 ) && $query->is_main_query() )
$query->set( 'post_type', array( 'portfolio' ) );
return $query;
}
This seems like the right track, but it stills doesn't work. I'm not getting the posts from my custom post type.
Any ideas how I could modify this? I am also still learning so being clear with explanations would be greatly appreciated.
Thank you!
Editing the pre_get_posts will replace the original query and you will not have the content for your page at all. I would only recommend going this approach if you only wanted to display the content of your portfolio post type and not the content of your portfolio page.
For general post queries it is recommended to use WP_Query or get_posts.
http://codex.wordpress.org/Class_Reference/WP_Query
http://codex.wordpress.org/Template_Tags/get_posts
If you use the WP_Query function the wp_reset_postdata() will restore the post data back to the original so you can get the content of your original page.
$args = array(
'posts_per_page' => 10,
'post_type' => 'portfolio',
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
Now you will be able to use the original loop to show the content of your page
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
Usually, I stick my query posts in a variable, like so:
$catid = get_cat_ID('My Category Name');
$args = array(
'posts_per_page' => 5,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'category' => $catid
);
$posts_array = get_posts($args);
Then you can loop it like so:
<?php foreach ($posts_array as $post) : setup_postdata($post);?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
<?php endforeach; ?>
Finally, to access your page content you can use the variable $post, it's automatically set by wordpress. No need to add any more code than this to access your page content.
<?php foreach( $posts as $post ) : setup_postdata($post); ?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
<?php endforeach; ?>
The foreach loop for your page content is a little overkill, and there is a better way to do it (most likely at least), but I haven't been bothered to look into it further yet! It works though!

Categories