Retrieve post taxonomy inside get_posts() - php

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.

Related

Get ACF field data within foreach loop - wordpress

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; ?>

Am looking for a way to show random products in products category page using woocomerce

How do I change product in same category randomly? I've been looking but can't seem to find any plugin/script to do this, anyone got an idea on this... thanks
You can use the following code to display the products rows of "CATXXX" :
<?php echo do_shortcode( '[product_category category="CATXXX" per_page="8" columns="4" orderby="rand"]' ) ?>
Also you can treat products like any other post type and query using get_posts(). Limit the number of posts retrieved to 1 and change the orderby parameter to random:
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'category' => 'CATXXX'
'post_type' => 'product');
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<li>
<?php the_title(); ?>
</li>
<?php endforeach;
wp_reset_postdata();
You can also use new WP_Query() which would be similar.
You can try this code shortcode
[product_category category="category_slug" per_page="10" orderby="rand"]
Or
<?php echo do_shortcode( '[product_category category="category_slug" per_page="10" orderby="rand"]' ) ?>

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.

ACF custom post feed by custom taxonomy

I'm using wordpress with custom post type UI plugin and ACF plugin.
Trying to build a “single” template with multiple feeds of custom post types by custom custom taxonomy. Using this code, with a few variations to figure out what am i doing wrong.
Got 2 pieces of code like this in a row
<?php if( get_field('collectiona') ):
$argsc = array(
'post_type' => 'products',
'product-collections' => get_field('collectiona'),
);
$prods2 = new WP_Query( $argsc );
if( $prods2->have_posts() ) {
while( $prods2->have_posts() ) {
$prods2->the_post();
?>
Whatever post code
<?php
}
}
else {
echo '';
}
?>
<?php endif; ?>
collectiona is a taxonomy field. With the piece of code, shown above, it just shows all the “products” posts out there. I’ve also tried using a text field with taxonomy slug. It shows first feed perfectly fine, if i’m not using first if statement (<?php if( get_field(‘collectiona’) ): ?>), and if that statement is present- same thing happens. All the “products” are shown. However, even with first feed shown fine, 2nd feed still shows all the “products” out there. Despite what taxonomy slug says.
I’m trying to build it the way, admin could chose a dropdown taxonomy. Text field with taxonomy slug is just an example.
p.s.
I use term object
Full template code is here jsfiddle.net/pudfbxhv . I know jsfiddle is useless for wp templates, but that's a pretty big piece of code
EDIT
Here is updated code
<?php
$taxterms = get_field("collectiona"); ?>
<?php
$args = array(
'post_type' => 'products',
'tax_query' => array(
array(
'taxonomy' => 'product-collections',
'field' => 'id',
'terms' => $taxterm->term_id
)
)
);
$myquery = new WP_Query( $args );
if($myquery->have_posts()) : ?>
<ul>
<?php while ( $myquery->have_posts() ) : $myquery->the_post(); ?>
<li> <img src="<?php the_field('prod_featured_image'); ?>" onmouseover="this.src='<?php the_field('prod_hover_featured_image'); ?>'" onmouseout="this.src='<?php the_field('prod_featured_image'); ?>'" />
<h2><?php the_field('prod_subtitle'); ?></h2>
<p>$<?php the_field('prod_price'); ?></p>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); ?>
Well, that may be a perversion, but it worked for me.
$termss = get_field('collectiona');
$slll = $termss->slug;
$args = array(
'post_type' => 'products',
'product-collections' => $slll,
);
$lineblocks = new WP_Query( $args );
if( $lineblocks->have_posts() ) {
while( $lineblocks->have_posts() ) {
$lineblocks->the_post();
Also, gotta remember to put the following code after every array
<?php wp_reset_query(); ?>

Custom Post Type displays post belong on the category

I have a custom post type advice and taxonomy adcat. I want to display all post belong to that category.
Lets say I have 4 categories namely : 'games', 'tours', 'dishes', 'hotels' and also this four category is a menu. If I click one of the category for example: hotels all post belong to the hotels should display.
By the way this code I used to show wordpress default categories:
<?php $catname = wp_title('', false); ?>
<?php $posts = get_posts("category_name=$catname&numberposts=8&offset=0");
foreach ($posts as $post) : start_wp(); ?>
//html output
<h1><?php the_title(); ?></h1>
<?php endforeach; ?>
this is not working in custom post 'taxonomies' any suggestion would be helpful thank's
try this maybe it work... I write a note so you can see whats going on.. hope it help
<?php
// Get the term/category of the post
$terms = get_the_terms( $post->ID , 'advice-cat' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'advice cat' );
}
//WordPress loop for custom post type
$terms = get_the_terms( $post->ID , 'advice-cat' );
$my_query = new WP_Query('post_type=advice&advice-cat=' . $term->name . '&posts_per_page=-1');
while ($my_query->have_posts()) : $my_query->the_post(); ?>
// output content
<?php the_title(); ?>
<?php endwhile; wp_reset_query(); ?>
try something like this, this is the example to fetch post by category id
$args = array( 'cat' => $cat_id, 'post_type' => 'advice', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
endwhile;
wp_reset_postdata();
you can also use with category name as well.
$args = array('category_name' => 'catname', 'post_type' => 'advice', 'posts_per_page' => -1 );
you can use post_per_page as per your requirement, I have just added -1 for all the posts
I don't really understand your terminology. When you are talking about adcat, is it a custom taxonomy or a term of the build-in taxonomy category. If adcat is a custom taxonomy, you should use the tax_query in WP_Query,not the category parameters.
Remember, category and a custom taxonomy are both taxonomies, their direct children is called terms, and their direct childen is called child terms
You should also not be using wp_title() to get the queries object. You should be using get_query_var() to get the queried object. For categories it will be cat, taxonomy will be taxonomy and for terms term. Have a look at get_categories, get_taxonomies and get_terms for returned values
Example
$category = get_query_var( `cat` );
$cat_slug = $category->slug;
You can now return $cat_slug to your custom query as category_name
EDIT
I've quickly rethinked the whole thing and checked your comment as well. Why not just copy your index.php and rename it taxonomy.php. There is no need at all for a custom query here. The default loop in taxonomy.php should do it
EDIT 2
For further reading, go and check the following articles
Theme Development
Template Hierarchy
Not sure if I read your answer correctly but what I am assuming is you want to search posts by the taxonomy terms correct? So in your adcat taxonomy you have 'games', 'tours', 'dishes', 'hotels' as your terms or categories. Your best option would be to use a tax_query in your query arguments. Here is how to do that with the WP_Query() object.
<?php
$args = array(
'post_type' => 'advice',
'posts_per_page' => 8,
'tax_query' => array(
'taxonomy' => 'adcat',
'terms' => array('games', 'tours', 'dishes', 'hotels'),
'field' => 'slug'
)
);
$query = new WP_Query($args);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
Important Note:
When using a WP_Query you will be overwriting the default post data. So in order to get that data back you just use the wp_reset_postdata() as you can see in the example above after the loop has finished.

Categories