Query posts by custom fields - wordpress

I am building a website using Advanced Custom Fields that has yachts for sale. The yachts use a custom Post type called ‘yachts’
One of the fields in the individual yacht listing is a true/false value to determine wether it should be a featured listing. (it was originally a checkbox but I changed it after experimenting with the answer in this post)
Advanced custom fields: can't query posts by custom field
I am trying to display previews of the featured listings on the home page but I can’t get it to work.
I originally tried this code from the ACF documentation
edit: I started with just trying to fetch the title but I also need the additional fields
<section class="featured-yachts">
<h2>FEATURED YACHTS</h2>
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'yachts',
'meta_key' => 'featured',
'meta_value' => 'yes'
);
// 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(). ?>
</section>
And now have this after switching to a true false field
<section class="featured-yachts">
<h2>FEATURED YACHTS</h2>
<?php
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'featured',
'value' => '1',
'compare' => 'LIKE',
)
),
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();
echo get_the_title();
endwhile;
wp_reset_postdata();
}
?>
</section>
I have also tried editing this: How filter custom posts by Advanced Custom Fields checkbox
but again, I cant get it to work.
The most any of these return is the h3 title
I can't work out what the issue is.
Thanks in advance for any help
edit : I have at least one post using the custom post type 'yachts' that is set to true for featured.
I still have lots of fields to add, but I would have expected that this output the h3 title and then the title of the post marked featured.
In the end, I would like it to function much like latest post previews, but display custom fields and only if the 'featured' true/false is set to yes
I have made an ACF field called 'featured yachts' and registered the block with Gutenberg, but there are no actual ACF fields within it, it's only used to call the file 'content-featured-yachts-block.php' which has this code I am trying to fix.
I am trying to populate the post previews within this featured yachts block with data pulled from the individual yacht listings. In these listings is the 'featured' true/false option. Screen shot atttached.
This is my code for registering the CPT
// Our custom post type function
function create_posttype() {
register_post_type( 'yachts',
// CPT Options
array(
'labels' => array(
'name' => __( 'Yacht Listings' ),
'singular_name' => __( 'Yacht' ),
'supports' => array( 'title', 'editor', 'comments', 'excerpt', 'custom-fields', 'thumbnail' ),
'add_new' => __( 'New Yacht Listing'),
'add_new_item' => __( 'Add New Yacht Listing'),
'edit_item' => __( 'Edit Yacht Listing'),
'new_item' => __( 'New Yacht Listing'),
'view_item' => __( 'View Listings'),
'search_items' => __( 'Search Listings'),
'not_found' => __( 'No Yacht Listings Found'),
'not_found_in_trash' => __( 'No yacht Listings found in Trash')
),
'public' => true,
// 'has_archive' => true,
'rewrite' => array('slug' => 'yachts'),
'show_in_rest' => true,
'menu_icon' => 'dashicons-sos',
'hierarchical' => true,
'taxonomies' => array('category')
)
);
}
Another edit - I made the assumption that if I could get the title field to show, the other fields would be easy but i can't get them either so I ALSO need to work out how to add the additional fields from the listing
The code I have tried is below
<h2>FEATURED YACHTS</h2>
<?php
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'featured',
'value' => 'yes',
'compare' => 'LIKE',
)
),
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();?>
<h2><?php the_title(); ?></h2>
<?php
get_post_meta( get_the_ID(), 'price', true );
?>
<?php endwhile;
wp_reset_postdata();
}
?>
AND ALSO
<section class="featured-yachts">
<h2>FEATURED YACHTS</h2>
<?php
$args = array(
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'featured',
'value' => 'yes',
'compare' => 'LIKE',
)
),
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) : $my_posts->the_post();?>
<h2><?php the_title(); ?></h2>
<p><?php the_field( 'price' ); ?></p>
<?php endwhile;
wp_reset_postdata();
}
?>
</section>

You can use 'meta_query' and for ACF true and false you don't have to compare with LIKE. Try the below code.
<section class="featured-yachts">
<h2>FEATURED YACHTS</h2>
<?php
$args = array(
'post_type' => 'yachts',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'featuredyacht',
'value' => '1',
)
),
);
$my_posts = new WP_Query($args);
if ( $my_posts->have_posts() ) {
while ( $my_posts->have_posts() ) : $my_posts->the_post();
echo "Title - ".get_the_title()."</br>";
echo "Price - ".get_field( "price", get_the_ID() )."</br>";
echo "Length - ".get_field( "length", get_the_ID() )."</br>";
echo "Year built - ".get_field( "year_built", get_the_ID() )."</br>";
echo "Capacity - ".get_field( "capacity", get_the_ID() )."</br>";
endwhile;
wp_reset_postdata();
}
?>
</section>

To use multiple custom field parameters in your query, replace $args as in Bhautik's answer with something like this:
$args = array(
'post_type' => 'yachts',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'featuredyacht',
'value' => '1',
),
array(
'key' => 'price',
'value' => 50000,
'type' => 'numeric',
'compare' => '>=',
)
),
);
The above example fetches only yachts with featuredyacht set to 1 or true AND with a price of 50,000 or more. Adjust as needed to suit your parameters.
For example, to query featured yachts within a specific price range:
$args = array(
'post_type' => 'yachts',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'featuredyacht',
'value' => '1',
),
array(
'key' => 'price',
'value' => array( 50000, 100000 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
)
),
);
The developer documentation on WP_Query should be very useful to you for any further customizations.

Related

How to get ACF field value form custom taxonomy inside foreach?

I created a custom field with 'domain_url' id to add field in my taxonomy using the following code:
acf_add_local_field_group(array(
'key' => 'group_6294fa89c564b',
'title' => 'Domain url Field',
'fields' => array(
array(
'key' => 'field_629504c3cdd67',
'label' => 'domain url',
'name' => 'domain_url',
'type' => 'text',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'default_value' => '',
'placeholder' => '',
'prepend' => '',
'append' => '',
'maxlength' => '',
),
),
'location' => array(
array(
array(
'param' => 'taxonomy',
'operator' => '==',
'value' => 'news_source',
),
),
),
));
And I want to get the value inside the categories foreach, I tried this code but it didn't give a result
<?php
$args = array(
'taxonomy' => 'news_source',
);
$cats = get_categories($args);
foreach($cats as $cat) {
?>
Name: <?php echo $cat->name; ?> >
Domain: <?php echo get_field('domain_url' ); ?> <br/>
<?php
}
?>
Is the problem in the code? Or does the extension not support it?
You are missing an argument in your get_field(). You need to add an arg for the term or term object.
<?php
$args = array(
'taxonomy' => 'news_source',
);
$cats = get_categories($args);
foreach($cats as $cat) {
?>
Name: <?php echo $cat->name; ?> >
Domain: <?php echo get_field('domain_url', $cat ); ?> <br/> // Put the term in here.
<?php
}
?>
In this case you may need an extra query, or to use the term string plus the term ID in a string.
This ACF documentation article shows some different methods of retrieving tax term fields as well.

Wordpress display posts from multiple value in meta

I have got main product with meta key: addons and meta values in this key: 129456,968945,495435 Each of these three numbers is the key with these meta values. For example:
Post 1: meta_key: subproduct meta_value: 129456
Post 2: meta_key: subproduct meta_value: 968945
Post 3: meta_key: subproduct meta_value: 495435
And now I want to display these three posts in the main product. My code:
<?php if (!empty($addons = get_post_meta(get_the_ID(), 'addons', true))):?>
<?php
$params = array(
'post_type' => 'product',
'meta_key' => 'subproduct',
'meta_value' => $addons
);
$wc_query = new WP_Query($params);
?>
<?php while ($wc_query->have_posts()) : $wc_query->the_post(); ?>
<?php include(rh_locate_template('inc/parts/woomain.php')); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif;?>
With one meta value it worked but with several it doesn't work anymore. How do you view these three posts?
Try to alter your query like this and lets see if that works
$params = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'subproduct',
'value' => array($addons),
'compare' => 'IN'
)
)
);
It works with this code:
$params = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'subproduct',
'value' => $addons,
'compare' => 'IN'
)
)
);

How to show custom post type posts according to category in wordpress

i have create custom post type for show plans and i want to show post according to category. i am using below code in functions.php for creating custom post type for plans.
add_action('init', 'create_post_types');
function create_post_types() {
register_post_type( 'numbers_plan',
array(
'labels' => array(
'name' => __( 'Numbers plan' ),
'singular_name' => __( 'Numbers plan' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'Numbers plan'),
)
);
// Add new taxonomy(like categories)
$labels = array(
'name' => _x( 'PlanCat', 'numbers_plan', 'textdomain' ),
'singular_name' => _x( 'PlanCat', 'numbers_plan', 'textdomain' ),
'search_items' => __( 'Search PlanCat', 'numbers_plan' ),
'all_items' => __( 'All PlanCat', 'numbers_plan' ),
'parent_item' => __( 'Parent PlanCat', 'numbers_plan' ),
'parent_item_colon' => __( 'Parent PlanCat:', 'numbers_plan' ),
'edit_item' => __( 'Edit PlanCat', 'numbers_plan' ),
'update_item' => __( 'Update PlanCat', 'numbers_plan' ),
'add_new_item' => __( 'Add New PlanCat', 'numbers_plan' ),
'new_item_name' => __( 'New PlanCat Name', 'numbers_plan' ),
'menu_name' => __( 'PlanCat', 'numbers_plan' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'numbers_plan' ),
);
register_taxonomy( 'numbers_plans', array( 'numbers_plan' ), $args );
}
for show plans i have create plan.php page with blow code.
<?php
$plan_group = get_terms( 'numbers_plans' );
?>
<?php
foreach ( $plan_group as $plan_group_term ) {
$plan_group_query = new WP_Query( array(
'post_type' => 'numbers_plan',
'tax_query' => array(
array(
'taxonomy' => 'numbers_plans',
'field' => 'slug',
'terms' => array( $plan_group_term->slug ),
'operator' => 'IN'
)
)
));
?>
<h2><?php echo $plan_group_term->name; ?></h2>
<ul>
<?php
if ( $plan_group_query->have_posts() ) : while ( $plan_group_query->have_posts() ) : $plan_group_query->the_post(); ?>
<div>
<div><?php echo the_title(); ?></div>
<div><?php the_field('plan_minutes'); ?></div>
<div><?php the_field('monthly_cost'); ?></div>
<div><?php the_field('cost_of_additional_minutes'); ?></div>
<?php echo do_shortcode("[ARForms_popup id=103 desc='Buy Now' type='link' height='540' width='800']"); ?>
<br/>
</div>
<?php endwhile; endif; ?>
</ul>
<?php
// Reset things, for good measure
$plan_group_query = null;
wp_reset_postdata();
}
?>
it is showing all categories posts but i want to show only one category and it's post. please tell me how can i do this.
One way to select posts from a certain category is by creating a small if statement around the post output. See the example below:
<?php
if (in_category('<category_name')) {
/* the post */
}
else {
/* Do nothing */
}
?>
A full example:
<?php if ( have_posts() ) :
if (in_category('Algemeen')) {
require_once('category-pages/Algemeen-category.php');
} elseif (in_category('Sport')) {
require_once('category-pages/Sport-category.php');
} elseif (in_category('Economie')) {
require_once('category-pages/Economie-category.php');
} elseif (in_category('Politiek')) {
require_once('category-pages/Politiek-category.php');
} elseif (in_category('Gemeente nieuws')) {
require_once('category-pages/Gemeente-category.php');
}
?>
In this example i check each post on it's category and load a different template file for the posts with the corresponding category
exclude all the othe categories id in array.
<?php
$args = array('exclude'=> array("Enter Other categories ID here")); //which categories you dont want
$$plan_group = get_terms('numbers_plans', $args);
?>
I Hope this will help you
<?php
$catquery = new WP_Query( 'cat=3&posts_per_page=10' );
while($catquery->have_posts()) : $catquery->the_post();
?>
<ul>
<li><h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php
the_title(); ?></a></h3>
<ul><li><?php the_content(); ?></li>
</ul>
</li>
</ul>
<?php endwhile; ?>

Show Custom Post based on selected custom taxonomy in Wordpress

In the current website i am building i build the following functionality.
Current situation to give a better understanding of the problem.
There is a page called blog. This page display's all the blogs (posts) in a list. There is a aside with all the categories the posts have. The user can select a category. Once the user clicks on it the user will go to the category.php and see all the posts that have that specific category.
I want to create the same scenario but than with a custom post type. I have a template part; 'offer-list-template.php'
offer-list-template.php (here i get all the offers and display them);
<?php
// set up or arguments for our custom query
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query_args = array(
'post_type' => 'Offers',
'posts_per_page' => 10,
'paged' => $paged
);
// create a new instance of WP_Query
$the_query = new WP_Query( $query_args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); // run the loop ?>
<?php
//$objectData is used in post-listing-item.php
$objectData->title = get_the_title($post);
$objectData->content = get_the_content($post);
$objectData->permalink = get_the_permalink($post);
$objectData->thumbnail = get_the_post_thumbnail($post);
$objectData->posttype = get_post_type($post);
include(locate_template('template-parts/post-listing-item.php'));
?>
<?php endwhile; ?>
In the same file there is the aside which shows the categories. offer_category is the taxonomy slug.
<?php $terms = get_terms( 'offer_category' );
foreach ( $terms as $term ) {
// The $term is an object, so we don't need to specify the $taxonomy.
$term_link = get_term_link( $term );
// If there was an error, continue to the next term.
if ( is_wp_error( $term_link ) ) {
continue;
}
// We successfully got a link. Print it out.
echo '<li>' . $term->name . '<span>('. $term->count . ')</span></li>';
}
?>
</ul
The result is:
If the user clicks on the categorie it goes to: taxonomy-offer-category.php (taxonomy-slug.php)
Here i need to display the posts (post_type->offers) that have the selected category.
Registration of the custom post type:
//Register Custom post type for Offers.
function create_posttype_offer() {
$args = array(
'labels' => array(
'name' => __('Offers', ''),
'singular_name' => __('Offer'),
'all_items' => __('All Offers'),
'add_new_item' => __('Add New Offer'),
'edit_item' => __('Edit Offer'),
'view_item' => __('View Offer')
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'Offers'),
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'capability_type' => 'page',
'supports' => array('title', 'editor', 'thumbnail'),
'exclude_from_search' => true,
'menu_position' => 70,
'has_archive' => true,
'menu_icon' => 'dashicons-star-filled'
);
register_post_type('Offers', $args);
}
add_action( 'init', 'create_posttype_offer');
// Register Custom Categoeries for Custom Post Type Offers
function taxonomies_offer() {
$labels = array(
'name' => _x( 'Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Categories' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category' ),
'menu_name' => __( 'Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
);
register_taxonomy( 'offer_category', 'offers', $args );
}
add_action( 'init', 'taxonomies_offer', 0 );
When i use the default post type and i call category.php which has the following code is will display the posts with the selected category. But with a custom post type i can't find a way to manage it.
<?php if (have_posts() ) : while ( have_posts() ) : the_post(); // run the loop ?>
<?php
//$objectData is used in post-listing-item.php
$objectData->title = get_the_title($post);
$objectData->content = get_the_content($post);
$objectData->permalink = get_the_permalink($post);
$objectData->thumbnail = get_the_post_thumbnail($post);
$objectData->posttype = get_post_type($post);
include(locate_template('template-parts/post-listing-item.php'));
?>
<?php endwhile; ?>
This is the post-listing-item (view)
<article class="post-item">
<figure>
<?php echo $objectData->thumbnail ?>
</figure>
<div class="content">
<a href="<?php echo $objectData->permalink ?>">
<h2><?php echo $objectData->title ?></h2>
</a>
<p><?php echo $objectData->content ?></p>
<div class="read-more-button">
<a href="<?php echo $objectData->permalink ?>">read more
<span>
<svg class="next-arrow"><use xlink:href="#next-arrow" /></svg>
</span>
</a>
</div>
</div>
</article>
By understanding, you have to have a query for having all the custom taxonomy post to load by the following code:
$terms = get_terms(
array(
'taxonomy' => 'offer_category',
'hide_empty' => false,
)
);
foreach ($terms as $term){
$args = array(
'post_type' => 'Offers',
'tax_query' => array(
array(
'taxonomy' => 'offer_category',
'field' => 'slug',
'terms' => $term->slug,
),
),
);
$query = new WP_Query($args);
if($query->have_posts()): while($query->have_posts()): $query->the_post();
the_title();
the_content();
endwhile;
wp_reset_postdata();
endif;
}
Hope this works for you
I found it!
I got the taxonomy and slug from the url and used that in the query.
<?php
$term_slug = get_query_var( 'term' );
$taxonomyName = get_query_var( 'taxonomy' );
$the_query = new WP_Query( array(
'post_type' => 'offers',
'tax_query' => array(
array (
'taxonomy' => $taxonomyName,
'field' => 'slug',
'terms' => $term_slug,
)
),
));
?>
<ul>
<?php while($the_query->have_posts()) : $the_query->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; wp_reset_query(); ?>
</ul>

How to get category listing of most popular products in woocommerce

How can I list out the top 5 most popular category(or category of most popular products) on my wordpress site home page.
I have used woocommerce plugin for products.
Thanks in advance for any suggestion or solution.
Since none of the answers is a solution to the author's question, here is what I came up with. This is a shortcode snippet that lists popular products by categories. By popular I mean most sold products ( as in total sales).
function bestselling_products_by_categories( $atts ){
global $woocommerce_loop;
extract(shortcode_atts(array(
'cats' => '',
'tax' => 'product_cat',
'per_cat' => '5',
'columns' => '5',
'include_children' => false,
'title' => 'Popular Products',
'link_text' => 'See all',
), $atts));
if(empty($cats)){
$terms = get_terms( 'product_cat', array('hide_empty' => true, 'fields' => 'ids'));
$cats = implode(',', $terms);
}
$cats = explode(',', $cats);
if( empty($cats) )
return '';
ob_start();
foreach($cats as $cat){
// get the product category
$term = get_term( $cat, $tax);
// setup query
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $per_cat,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'tax_query' => array(
array(
'taxonomy' => $tax,
'field' => 'id',
'terms' => $cat,
'include_children' => $include_children,
)
),
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array( 'catalog', 'visible' ),
'compare' => 'IN'
)
)
);
// set woocommerce columns
$woocommerce_loop['columns'] = $columns;
// query database
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<?php if ( shortcode_exists('title') ) : ?>
<?php echo do_shortcode('[title text="'. $title .'" link="' . get_term_link( $cat, 'product_cat' ) . '" link_text="' . $link_text . '"]'); ?>
<?php else : ?>
<?php echo '<h2>'. $title .'</h2>'; ?>
<?php endif; ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
wp_reset_postdata();
}
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
} add_shortcode( 'custom_bestselling_product_by_categories', 'bestselling_products_by_categories' );
You can use this by calling it as:
<?php echo do_shortcode('[custom_bestselling_product_by_categories cats="' . $term->term_id . '"]'); ?>
This shortcode has some options:
cats : the category ID or comma-separated IDs to retrieve the products from.
tax : the taxonomy to get the products from, default is product_cat
per_cat : number of products to retrieve
columns : number of columns to display
include_children : if false only direct children of the category will be displayed, if true then children of children will be displayed
title : title to display
link_text : the link text linked to the store
Notice that this snippet assumes you have a shortcode named title and it takes a few other parameters such as link and link_text arguments. You can always change this according to your theme.
Hope it helps.
I recommend you to check this page.
http://docs.woothemes.com/document/woocommerce-shortcodes/
array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'title',
'order' => 'asc',
'category' => ''
)
[product_category category="appliances"]
array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'title',
'order' => 'asc'
)
[top_rated_products per_page="12"]
Or you can use this plugin : https://wordpress.org/plugins/sp-woocommerce-best-selling-products-by-category/
Popular might be in many cases like most viewing, top selling. So i listed products by top selling. This way you can get top selling products and by this you can get category listing.
$query_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => '10',
'columns' => '4',
'fields' => 'ids',
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
'meta_query' => WC()->query->get_meta_query()
);
$best_sell_products_query = query_posts($query_args);
return $best_sell_products_query;

Resources