I am using a template which has a widget to show woocommetce product on the home page, Currently price of product is just a number E.g. ₹18500/- without any decimal or comma, I want to show price with Thousand separator and Decimal separator E.g. ₹ 18,500/-
Note: Thousand separator and Decimal separator is enabled from woocommerce settings, and here I want to show price on a widget.
I am attaching code of the widget.
any help will be appreciated.
* Filter the arguments for the Recent Posts widget.
*
* #since 1.0.0
*
* #see WP_Query
*
*/
$query_args = array(
'posts_per_page' => $post_number,
'post_status' => 'publish',
'post_type' => 'product',
'no_found_rows' => 1,
'order' => $order,
'meta_query' => array(),
'tax_query' => array(
'relation' => 'AND',
),
);
switch ( $wc_advanced_option ) {
case 'featured' :
if( !empty( $product_visibility_term_ids['featured'] )){
$query_args['tax_query'][] = array(
'taxonomy' => 'product_visibility',
'field' => 'term_taxonomy_id',
'terms' => $product_visibility_term_ids['featured'],
);
}
break;
case 'onsale' :
$product_ids_on_sale = wc_get_product_ids_on_sale();
if( !empty( $product_ids_on_sale ) ){
$query_args['post__in'] = $product_ids_on_sale;
}
break;
case 'cat' :
if( !empty( $travel_way_wc_product_cat )){
$query_args['tax_query'][] = array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $travel_way_wc_product_cat,
);
}
break;
case 'tag' :
if( !empty( $travel_way_wc_product_tag )){
$query_args['tax_query'][] = array(
'taxonomy' => 'product_tag',
'field' => 'term_id',
'terms' => $travel_way_wc_product_tag,
);
}
break;
}
switch ( $orderby ) {
case 'price' :
$query_args['meta_key'] = '_price';
$query_args['orderby'] = 'meta_value_num';
break;
case 'sales' :
$query_args['meta_key'] = 'total_sales';
$query_args['orderby'] = 'meta_value_num';
break;
case 'ID' :
case 'author' :
case 'title' :
case 'date' :
case 'modified' :
case 'rand' :
case 'comment_count' :
case 'menu_order' :
$query_args['orderby'] = $orderby;
break;
default :
$query_args['orderby'] = 'date';
}
$travel_way_featured_query = new WP_Query( $query_args );
if ($travel_way_featured_query->have_posts()) :
echo $args['before_widget'];
$animation = "init-animate zoomIn";
?>
<section id="<?php echo esc_attr( $unique_id ); ?>" class="at-widgets acme-abouts <?php echo $bg_gray_class;?>">
<div class="container">
<?php
if ( ! empty( $title ) ) {
echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
}
$div_attr = 'class="featured-entries-col woocommerce"';
?>
<div class="row at-cat-product-wrap clearfix ">
<div <?php echo $div_attr;?>>
<?php
$travel_way_featured_index = 1;
while ( $travel_way_featured_query->have_posts() ) :$travel_way_featured_query->the_post();
$travel_way_list_classes = 'single-list';
if ( 1 == $column_number ) {
$travel_way_list_classes .= " col-sm-12";
} elseif ( 2 == $column_number ) {
$travel_way_list_classes .= " col-sm-6";
} elseif ( 3 == $column_number ) {
$travel_way_list_classes .= " col-sm-4 col-md-4";
} else {
$travel_way_list_classes .= " col-sm-4 col-md-3";
}
?>
<div class="<?php echo esc_attr( $travel_way_list_classes ); ?>">
<a href="<?php the_permalink();?>">
<?php the_post_thumbnail($travel_way_img_size)?>
<div class="caption">
<h3 class="at-woo-title"><?php the_title();?></h3>
<?php
woocommerce_template_loop_rating();
$currency = get_woocommerce_currency_symbol();
$price = get_post_meta( get_the_ID(), '_regular_price', true);
$sale = get_post_meta( get_the_ID(), '_sale_price', true);
if($sale) :
global $post, $product;
echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale">' . esc_html__( 'Sale!', 'travel-way' ) . '</span>', $post, $product );
?>
<p class="product-price">
<del>
<?php
echo esc_html($currency);
echo esc_html( $price );
?>
</del>
<?php
echo esc_html($currency);
echo esc_html( $sale . '/-' );
?>
</p>
<?php elseif($price) : ?>
<p class="product-price">
<?php
echo esc_html($currency);
echo esc_html( $price . '/-');
?>
</p>
<?php endif;
?>
</div>
</a>
</div><!--dynamic css-->
<?php
$travel_way_featured_index++;
endwhile;
?>
</div><!--featured entries-col-->
</div><!--cat product wrap-->
<?php
echo $args['after_widget'];
echo "<div class='clearfix'></div>";
// Reset the global $the_post as this query will have stomped on it
?>
</div>
</section>
<?php
endif;
wp_reset_postdata();
}
} // Class Travel_Way_Wc_Products ends here
} ```
You can use number_format. Should be something like:
$price = floatval($price);
$decimal_separator = wc_get_price_decimal_separator();
$thousand_separator = wc_get_price_thousand_separator();
$decimals = wc_get_price_decimals();
$formatted_price = number_format( $price, $decimals, $decimal_separator, $thousand_separator );
echo esc_html( $formatted_price . '/-');
Related
I need to show users order list with my own html and css, like the number and the thumbnail in the left part of the item, and in the right part it has to be an order date, an order status, the quantity and the price, and my own meta.
I've founded how to add an image with the hook, it's not a problem. The problem is - that I can't customize the native structure of woocommerce/myaccount/orders.php. Even when I change table, tr,td,tbody to div-s, my wrappers don't help. It's a loop. And all that I add is adding for all items
foreach ( $customer_orders->orders as $customer_order ) {
$order = wc_get_order( $customer_order ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$item_count = $order->get_item_count() - $order->get_item_count_refunded();
?>
<div class="woocommerce-orders-table__row woocommerce-orders-table__row--status-<?php echo esc_atdiv( $order->get_status() ); ?> order">
<?php foreach ( wc_get_account_orders_columns() as $column_id => $column_name ) : ?>
<div class="woocommerce-orders-table__cell woocommerce-orders-table__cell-<?php echo esc_atdiv( $column_id ); ?>" data-title="<?php echo esc_atdiv( $column_name ); ?>">
<?php if ( has_action( 'woocommerce_my_account_my_orders_column_' . $column_id ) ) : ?>
<?php do_action( 'woocommerce_my_account_my_orders_column_' . $column_id, $order ); ?>
<?php elseif ( 'order-number' === $column_id ) : ?>
<a href="<?php echo esc_url( $order->get_view_order_url() ); ?>">
<?php echo esc_html( _x( '#', 'hash before order number', 'woocommerce' ) . $order->get_order_number() ); ?>
</a>
<?php elseif ( 'order-date' === $column_id ) : ?>
<time datetime="<?php echo esc_atdiv( $order->get_date_created()->date( 'c' ) ); ?>"><?php echo esc_html( wc_format_datetime( $order->get_date_created() ) ); ?></time>
<?php elseif ( 'order-status' === $column_id ) : ?>
<?php echo esc_html( wc_get_order_status_name( $order->get_status() ) ); ?>
<?php elseif ( 'order-total' === $column_id ) : ?>
<?php
/* divanslators: 1: formatted order total 2: total order items */
echo wp_kses_post( sprintf( _n( '%1$s for %2$s item', '%1$s for %2$s items', $item_count, 'woocommerce' ), $order->get_formatted_order_total(), $item_count ) );
?>
<?php elseif ( 'order-actions' === $column_id ) : ?>
<?php
$actions = wc_get_account_orders_actions( $order );
if ( ! empty( $actions ) ) {
foreach ( $actions as $key => $action ) { // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
echo '' . esc_html( $action['name'] ) . '';
}
}
?>
<?php endif; ?>
</div>
<?php endforeach;
I need to separate the order-number and the added thumbnail to one wrapper, and all other metas to another.
I need something like global $product; product-> get_price(); but with the order.
Maybe there is some hooks of functions to display all order parts separately, and make a new loop?
As per our understanding, you want to create your own template page and show current user orders.
If I am right you should try like this:
<?php
/*
* Template Name: Order Page Template
*/
defined( 'ABSPATH' ) || exit;
global $woocommerce, $user_id;
if (!class_exists('WooCommerce') || !get_current_user_id()) {
return;
};
$user_id = get_current_user_id();
//$customer = wp_get_current_user();
$posts_per_page = 20;
// Get all customer orders
$customer__all_orders = get_posts(apply_filters('woocommerce_my_account_my_orders_query', array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'orderby' => 'date',
'order' => 'DESC',
'meta_value' => $user_id ,
'post_type' => wc_get_order_types(),
'post_status' => array_keys(wc_get_order_statuses()), 'post_status' => array('wc-processing'),
)));
$paged = isset($_REQUEST['order_page']) ? $_REQUEST['order_page'] : 1;
$total_records = count($customer__all_orders);
$total_pages = ceil($total_records / $posts_per_page);
$customer_orders = get_posts(array(
'meta_key' => '_customer_user',
'order' => 'DESC',
'meta_value' => $user_id ,
'post_type' => wc_get_order_types(),
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'post_status' => array_keys(wc_get_order_statuses()), 'post_status' => array('wc-processing'),
));
?>
<?php if (!empty($customer_orders)) : ?>
<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive my_account_orders account-orders-table">
<thead>
<tr>
<?php foreach ( wc_get_account_orders_columns() as $column_id => $column_name ) : ?>
<th class="woocommerce-orders-table__header woocommerce-orders-table__header-<?php echo esc_attr( $column_id ); ?>"><span class="nobr"><?php echo esc_html( $column_name ); ?></span></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order );
$item_count = $order->get_item_count() - $order->get_item_count_refunded();
?>
<tr class="woocommerce-orders-table__row woocommerce-orders-table__row--status-<?php echo esc_attr( $order->get_status() ); ?> order">
<?php foreach ( wc_get_account_orders_columns() as $column_id => $column_name ) : ?>
<td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-<?php echo esc_attr( $column_id ); ?>" data-title="<?php echo esc_attr( $column_name ); ?>">
<?php if ( has_action( 'woocommerce_my_account_my_orders_column_' . $column_id ) ) : ?>
<?php do_action( 'woocommerce_my_account_my_orders_column_' . $column_id, $order ); ?>
<?php elseif ( 'order-number' === $column_id ) : ?>
<a href="<?php echo esc_url( $order->get_view_order_url() ); ?>">
<?php echo esc_html( _x( '#', 'hash before order number', 'woocommerce' ) . $order->get_order_number() ); ?>
</a>
<?php elseif ( 'order-date' === $column_id ) : ?>
<time datetime="<?php echo esc_attr( $order->get_date_created()->date( 'c' ) ); ?>"><?php echo esc_html( wc_format_datetime( $order->get_date_created() ) ); ?></time>
<?php elseif ( 'order-status' === $column_id ) : ?>
<?php echo esc_html( wc_get_order_status_name( $order->get_status() ) ); ?>
<?php elseif ( 'order-total' === $column_id ) : ?>
<?php
/* translators: 1: formatted order total 2: total order items */
echo wp_kses_post( sprintf( _n( '%1$s for %2$s item', '%1$s for %2$s items', $item_count, 'woocommerce' ), $order->get_formatted_order_total(), $item_count ) );
?>
<?php elseif ( 'order-actions' === $column_id ) : ?>
<?php
$actions = wc_get_account_orders_actions( $order );
if ( ! empty( $actions ) ) {
foreach ( $actions as $key => $action ) { // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
echo '' . esc_html( $action['name'] ) . '';
}
}
?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="pagination">
<?php
$args = array(
'base' => '%_%',
'format' => '?order_page=%#%',
'total' => $total_pages,
'current' => $paged,
'show_all' => False,
'end_size' => 5,
'mid_size' => 5,
'prev_next' => True,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
'type' => 'plain',
'add_args' => False,
'add_fragment' => ''
);
echo paginate_links($args);
?>
</div>
<?php else : ?>
<div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
<a class="woocommerce-Button button" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>"><?php esc_html_e( 'Browse products', 'woocommerce' ); ?></a>
<?php esc_html_e( 'No order has been made yet.', 'woocommerce' ); ?>
</div>
<?php endif; ?>
Steps:
Create new page inside your active theme - template-order.php
Copy past above code inside your template-order.php apge and save.
Goto wordpress admin dashboard pages menu and click on new page
After create new page assign templete "Order Page Templete" and save
Now open your new page and you will get or order related to current logged in user
Note: You can also modify above code accordingly
I have created a custom template for search our products with lots of filters and one input field to search with characters. However, it works only with one or two characters like "a", "ag" but not with more than two characters. If I search for something like "pol" or "polar" it redirects me to WordPress 404 - PAGE NOT FOUND.
Update:
I have tried two solutions: one with the custom query ajax and that works fine with a search but the only problem I faced is with the pagination; the other one used WordPress standard query object, it works well with pagination but I'm getting a problem with search character length. Below are the two attempts that I tried.
Attempt #1: with the Ajax. this code is written down in function.php file
function get_search_results()
{
global $wpdb;
if(!empty($_POST['search_input'])) {
$search_input = $_POST['search_input'];
$where = 'pm.meta_value LIKE '. "'%".$search_input."%'".' AND pm.meta_key LIKE "%pattern_number"';
$where1 = 'p.post_title LIKE '."'%".$search_input."%'".' AND p.post_type = "product"';
$search_sql = 'SELECT DISTINCT(pm.post_id), ph.lightness, ph.color_label FROM wp_posts p
INNER JOIN wp_products_huecolor ph on p.ID = ph.post_id
INNER JOIN wp_postmeta pm ON p.ID = pm.post_id
WHERE p.post_status = "publish" AND p.post_type = "product" AND (('.$where.') OR ('.$where1.')) ORDER BY ph.color_label, ph.lightness ASC';
$total_query = "SELECT COUNT(1) FROM (${search_sql}) AS combined_table";
$total = $wpdb->get_var( $total_query );
$items_per_page = 10;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$page = $wpdb->get_results( $search_sql.' LIMIT '.$offset.', '.$items_per_page );
//echo "SQL = ".$wpdb->last_query; wp_die();
echo '<ul>';
foreach ($page as $object)
{
// get custom fields values related to a post by post id
$fields = get_fields($object->post_id);
// get post details by post id
$post_detail = get_post($object->post_id, $object );
$brand_name = $fields[brand]->name;
$full_sheet_image = $fields[full_sheet_image][sizes][thumbnail];
$post_title = $post_detail->post_title;
$post_name = $post_detail->post_name;
?>
<li class="post-pattern">
<div class="search-productsBoxSecond">
<a target="_blank" href="<?php echo site_url( '/products/'.$post_name.'', 'http' ); ?>"><img src="<?php echo $full_sheet_image; ?>" alt="" class="vc_single_image-img attachment-full"></a>
<div class="search-productNameSecond"><a target="_blank" href="<?php echo site_url( '/products/'.$post_name.'', 'http' ); ?>"><?php echo $post_title; ?></a></div>
<div class="search-productBrandSecond"><?php echo $brand_name; ?></div>
</div>
</li>
<?php
}
echo '</ul>';
echo '<div class="search-product-navigation">';
echo paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%', site_url( '/pattern-search/' ) ),
'format' => '',
'prev_text' => __('«'),
'next_text' => __('»'),
'total' => ceil($total / $items_per_page),
'current' => $page
));
echo '</div>';
}
exit();
}
add_action('wp_ajax_nopriv_filter_featured_products','filter_featured_products');
add_action('wp_ajax_filter_featured_products','filter_featured_products');
Attempt #2: with Standard WP_Query in the custom template.
<?php
$args = array();
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$search_keywords = ( get_query_var( 's' ) ) ? get_query_var( 's' ) : "";
if(isset($search_keywords) && $search_keywords != ''){
$args = array(
'post_type' => 'product',
'search_prod_title' => $search_keywords,
'post_status' => 'publish',
'posts_per_page' => 10,
'paged' => $paged,
'wildcard_on_key' => true,
'meta_query' => array(
array(
'key' => 'product_type_%_pattern_number',
'value' => $search_keywords,
'compare' => 'LIKE',
),
)
);
}else{
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 10,
'paged' => $paged
);
}
// query for getting featured product
add_filter( 'posts_fields', 'products_posts_select_filter', 10, 2 );
add_filter( 'posts_join', 'products_posts_join_filter', 10, 2 );
add_filter( 'posts_where', 'title_filter', 10, 2 );
add_filter( 'posts_orderby', 'products_posts_orderby', 10, 2 );
add_filter('posts_groupby', 'products_posts_groupby', 10, 2);
$sql_query = new WP_Query( $args );
//echo $wpdb->last_query; die();
//echo '<pre>'; print_r($sql_query); die;
//echo $sql_query->request; die;
remove_filter( 'posts_fields', 'products_posts_select_filter', 10, 2 );
remove_filter( 'posts_join', 'products_posts_join_filter', 10, 2 );
remove_filter( 'posts_where', 'title_filter', 10, 2 );
remove_filter( 'posts_orderby', 'products_posts_posts_orderby', 10, 2 );
remove_filter('posts_groupby', 'products_posts_groupby', 10, 2);
if( $sql_query->have_posts()):
echo '<ul>';
while( $sql_query->have_posts()): $sql_query->the_post();
{
//get custom fields meta values related to a post
$fields = get_fields($post->ID);
$full_sheet_image = $fields[full_sheet_image][sizes][thumbnail];
//echo'<pre>'; print_r($post_detail); die;
?>
<li class="post-pattern">
<div class="search-productsBoxSecond">
<a target="_blank" href="<?php echo site_url( '/products/'.$post->post_name.'', 'http' ); ?>"><img src="<?php echo $full_sheet_image; ?>" alt="" class="vc_single_image-img attachment-full"></a>
<div class="search-productNameSecond"><a target="_blank" href="<?php echo site_url( '/products/'.$post->post_name.'', 'http' ); ?>"><?php echo $post->post_title; ?></a></div>
<div class="search-productBrandSecond"><?php echo $fields[brand]->name; ?></div>
</div>
</li>
<?php
}
endwhile; ?>
</ul>
<!-- pagination -->
<div class="search-product-navigation">
<?php
echo paginate_links(array(
'total' => $sql_query->max_num_pages
));
?>
</div>
<?php endif; ?>
here are the filter functions thats written in the function.php
/*Replaced meta_key = with meta_key LIKE */
add_filter( 'posts_where', function ( $where, \WP_Query $q )
{
// Check for our custom query var
if ( true !== $q->get( 'wildcard_on_key' ) )
return $where;
// Lets filter the clause
$where = str_replace( 'meta_key =', 'meta_key LIKE', $where );
return $where;
}, 10, 2 );
function title_filter( $where, &$wp_query )
{
global $wpdb;
if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
$post_title_clause = '('.$wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\') OR';
$where = substr_replace($where, $post_title_clause , 6, 0);
}
return $where;
}
function products_posts_select_filter( $fields, &$wp_query ){
$fields = 'DISTINCT(wp_posts.ID), wp_posts.post_title, wp_posts.post_name, ph.lightness, ph.color_label';
return $fields;
}
function products_posts_join_filter( $join, &$wp_query ){
$join .= " INNER JOIN wp_products_huecolor ph on wp_posts.ID = ph.post_id";
return $join ;
}
function products_posts_orderby( $orderby, &$wp_query ){
$orderby = 'ph.color_label, ph.lightness ASC';
return $orderby;
}
function products_posts_groupby( $groupby, &$wp_query ){
return $groupby = '';
}
I am trying to get grouped products highest price so that i can show only highest price on custom template page.I am using WP_Query to get list of products.
Here is the snippet:
$series_term = $_GET['series'];
$args=array(
'series' => $term_name->slug,
'post_type' => 'product',
'posts_per_page' => 8,
'filter' =>$valuecol,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'hidden' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)
)
);
// $do_not_duplicate[] = $post->ID;
$my_query = null;
$my_query = new WP_Query($args);
/* Start the Loop */
while ($my_query->have_posts()) : $my_query->the_post();
$feat_prod_img = wp_get_attachment_image_src(get_post_thumbnail_id(), 'post-thumb-single');
$feat_product_img = wp_get_attachment_url( get_post_thumbnail_id($my_query->post->ID) );
?>
<div class="col-md-3 col-sm-4 col-xs-6">
<div class="product-detail">
<div class="product-thmbnial">
<a href="<?php the_permalink(); ?>">
<img src="<?php $src=$feat_product_img; echo image_product_resize_crop( $src, $w=440, $h=275, $dest = null, $override = false, $createNewIfExists = false ); ?>" alt="<?php the_title(); ?>"/>
</a>
</div>
<div class="info"><p><?php the_title(); ?><br/>
<span>
<?php $wp_product = new WC_Product( get_the_ID() );
echo get_woocommerce_currency_symbol(); ?></sup><?php
echo $wp_product->get_price();?></span></p></div>
</div>
</div>
<?php endwhile; ?>
I want grouped product highest price to show in place of $wp_product->get_price();
I tried to get children products and but the array is empty.
foreach ( $wp_product->get_children() as $child_id ) {
$child_prices[] = get_post_meta( $child_id, '_price', true );
}
can anyone suggest me how i can get highest price.
Thanks in advance.
I found the solution.. I tried the same solution earlier but that time it wasn't working.
Here is the fix:
$series_term = $_GET['series'];
$args=array(
'series' => $term_name->slug,
'post_type' => 'product',
'posts_per_page' => 8,
'filter' =>$valuecol,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'hidden' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)
)
);
// $do_not_duplicate[] = $post->ID;
$my_query = null;
$my_query = new WP_Query($args);
/* Start the Loop */
while ($my_query->have_posts()) : $my_query->the_post();
$feat_prod_img = wp_get_attachment_image_src(get_post_thumbnail_id(), 'post-thumb-single');
$feat_product_img = wp_get_attachment_url( get_post_thumbnail_id($my_query->post->ID) );
?>
<div class="col-md-3 col-sm-4 col-xs-6">
<div class="product-detail">
<div class="product-thmbnial">
<a href="<?php the_permalink(); ?>">
<img src="<?php $src=$feat_product_img; echo image_product_resize_crop( $src, $w=440, $h=275, $dest = null, $override = false, $createNewIfExists = false ); ?>" alt="<?php the_title(); ?>"/>
</a>
</div>
<div class="info"><p><?php the_title(); ?><br/>
<span>
<?php $wp_product = new WC_Product( get_the_ID() );
$child_prices = array();
foreach ( $product->get_children() as $child_id ) {
$child_prices[] = get_post_meta( $child_id, '_price', true );
}
$child_prices = array_unique( $child_prices );
if ( ! empty( $child_prices ) ) {
$min_price = min( $child_prices );
$max_price = max( $child_prices );
} else {
$min_price = '';
$max_price = '';
}
if($min_price == $max_price && !empty($min_price))
{
echo get_woocommerce_currency_symbol(); ?></sup><?php
echo $min_price;
}
elseif(!empty($max_price))
{
echo get_woocommerce_currency_symbol(); ?></sup><?php
echo $max_price;
}
else
{
echo get_woocommerce_currency_symbol(); ?></sup><?php
echo $wp_product->get_price();
}
?></span></p></div>
</div>
</div>
<?php endwhile; ?>
I have a question: In wordpress, how can I display posts in a category on a page ?. I have many categories, and in a page, I just only want posts in a category are displayed.
Thanks for your support !
Here is an alternative to a plugin. This is a dynamic page template. This template lets you choose which category's posts to display on the specific page. You can use this template over and over inside the same theme
Add this to your functions.php or any functions related file
<?php
/**-----------------------------------------------------------------------------
*
*Add a post metabox with options to the admin page screen.
*After selcting the page-pop.php template as a page template,
*this metabox will appear in the admin page screen.
*From here you can choose which category's posts to display
*and how the posts will be displayed on the page
*
* #package WordPress
* #subpackage Twenty_Fourteen
* #since Twenty Fourteen 1.0
*
*------------------------------------------------------------------------------*/
/**-----------------------------------------------------------------------------
*
*1. Only add meta boxes for the pop template
*
* #since Twenty Fourteen 1.0
*
*------------------------------------------------------------------------------*/
add_action('admin_init', 'pietergoosen_add_pop_meta_box');
function pietergoosen_add_pop_meta_box(){
$post_id = isset( $_GET['post'] ) ? $_GET['post'] : 0 ;
if($post_id) {
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
if ($template_file == 'page-pop.php') {
add_meta_box('pop_meta_box', __( 'Page of Posts with the same name', 'pietergoosen' ), 'pietergoosen_pop_meta_options', 'page', 'side', 'core');
} else {
$meta = get_post_meta($post_id, '_cat_id', true);
if( $meta ) {
pietergoosen_pop_update_post_meta($post_id, '_cat_id', '');
pietergoosen_pop_update_post_meta($post_id, '_page_title', '');
pietergoosen_pop_update_post_meta($post_id, '_posts_title', '');
pietergoosen_pop_update_post_meta($post_id, '_order_by', '');
pietergoosen_pop_update_post_meta($post_id, '_asc', '');
pietergoosen_pop_update_post_meta($post_id, '_post_count', '');
pietergoosen_pop_update_post_meta($post_id, '_days', '');
remove_meta_box( 'pop_meta_box', 'page', 'side' );
}
}
}
add_action('save_post', 'pietergoosen_pop_update_post_meta_box');
}
/**-----------------------------------------------------------------------------
*
*2. Built the list to display the options in the metabox
*
* #since Twenty Fourteen 1.0
*
*------------------------------------------------------------------------------*/
$order_list = array(
'none' => array( 'value' => 'none','label' => 'None' ),
'id' => array( 'value' => 'ID','label' => 'Post ID' ),
'author' => array( 'value' => 'author','label' => 'Author' ),
'title' => array( 'value' => 'title','label' => 'Post Title' ),
'date' => array( 'value' => 'date', 'label' => 'Post Date'),
'modified' => array( 'value' => 'modified','label' => 'Modified Date' ),
'parent' => array( 'value' => 'parent','label' => 'Parent Post' ),
'rand' => array( 'value' => 'rand','label' => 'Random' ),
'comment_count' => array( 'value' => 'comment_count','label' => 'Comment Count' ),
'menu_order' => array( 'value' => 'menu_order','label' => 'Menu Order' ),
);
$sort = array(
'DESC' => array( 'value' => 'DESC','label' => 'Descending' ),
'ASC' => array( 'value' => 'ASC','label' => 'Ascending' ),
);
function pietergoosen_pop_meta_options(){
$post_id = !empty($_GET['post']) ? $_GET['post'] : 0;
if( !$post_id ) return;
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
if ($template_file != 'page-pop.php') return;
global $order_list,$post_styles,$sort;
$categories = get_categories();
//Check if we have values
$post_meta=array();
$post_meta = get_post_meta( $post_id,false );
$cat_id = isset( $post_meta['_cat_id'] ) ? $post_meta['_cat_id'][0] : 1;
$page_title = isset( $post_meta['_page_title'] ) && $post_meta['_page_title'] ? $post_meta['_page_title'][0] : '';
$posts_title = isset( $post_meta['_posts_title'] ) && $post_meta['_posts_title'] ? $post_meta['_posts_title'][0] : '';
$order_by = isset( $post_meta['_order_by'] ) ? $post_meta['_order_by'][0] : 'date';
$asc = isset( $post_meta['_asc'] ) ? $post_meta['_asc'][0] : 'DESC';
$post_count = isset( $post_meta['_post_count'] ) ? $post_meta['_post_count'][0] : get_option('posts_per_page');
if(!$post_count || !is_numeric( $post_count )) $post_count = get_option('posts_per_page');
$days = isset( $post_meta['_days'] ) ? $post_meta['_days'][0] : '0';
if($days && !is_numeric( $days )) $days = '0';
?>
<!-- Sart the meta boxes -->
<div class="inside">
<p><label><strong><?php _e( 'Page Title', 'pietergoosen' ); ?></strong></label></p>
<input id="_posts_title" name="_posts_title" type="text" style="width: 98%;" value="<?php echo $posts_title; ?>"/>
<p><label><strong><?php _e( 'Post Title', 'pietergoosen' ); ?></strong></label></p>
<input id="_page_title" name="_page_title" type="text" style="width: 98%;" value="<?php echo $page_title; ?>"/>
<p><label><strong><?php _e( 'Category', 'pietergoosen' ); ?></strong></label></p>
<select id="_cat_id" name="_cat_id">
<?php
//Category List
foreach ($categories as $cat) :
$selected = ( $cat->cat_ID == $cat_id ) ? ' selected = "selected" ' : '';
$option = '<option '.$selected .'value="' . $cat->cat_ID;
$option = $option .'">';
$option = $option .$cat->cat_name;
$option = $option .'</option>';
echo $option;
endforeach;
?>
</select>
<p><label><strong><?php _e( 'Sort by', 'pietergoosen' )?></strong></label></p>
<select id="_order_by" name="_order_by">
<?php
foreach ($order_list as $output) :
$selected = ( $output['value'] == $order_by ) ? ' selected = "selected" ' : '';
$option = '<option '.$selected .'value="' . $output['value'];
$option = $option .'">';
$option = $option .$output['label'];
$option = $option .'</option>';
echo $option;
endforeach;
?>
</select>
<p><label><strong><?php _e( 'Order', 'pietergoosen' )?><strong></label></p>
<select id="_asc" name="_asc">
<?php
foreach ($sort as $output) :
$selected = ( $output['value'] == $asc ) ? ' selected = "selected" ' : '';
$option = '<option '.$selected .'value="' . $output['value'];
$option = $option .'">';
$option = $option .$output['label'];
$option = $option .'</option>';
echo $option;
endforeach;
?>
</select>
<p><strong><label><?php _e( 'Posts per Page', 'pageofposts' ); ?><strong></label></p>
<input id="_post_count" name="_post_count" type="text" value="<?php echo $post_count; ?>" size="3" />
<p><strong><label><?php _e( 'Posts in the last days', 'pageofposts' ); ?><strong></label></p>
<input id="_days" name="_days" type="text" value="<?php echo $days; ?>" size="3" />
</div>
<!-- End page of posts meta box -->
<?php
}
function pietergoosen_pop_update_post_meta_box( $post_id ){
if ( empty( $_POST ) ) {
return;
} else {
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
if ($template_file != 'page-pop.php') return;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return $post_id;
} else {
if ( $_POST['post_type'] == 'page' ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
$meta = isset( $_POST['_cat_id'] ) ? $_POST['_cat_id'] : 1;
pietergoosen_pop_update_post_meta($post_id, '_cat_id', $meta);
$meta = isset( $_POST['_page_title'] ) ? $_POST['_page_title'] : '';
pietergoosen_pop_update_post_meta($post_id, '_page_title', $meta);
$meta = isset( $_POST['_posts_title'] ) ? $_POST['_posts_title'] : '';
pietergoosen_pop_update_post_meta($post_id, '_posts_title', $meta);
$meta = isset( $_POST['_order_by'] ) ? $_POST['_order_by'] : 'date';
pietergoosen_pop_update_post_meta($post_id, '_order_by', $meta);
$meta = isset( $_POST['_asc'] ) ? $_POST['_asc'] : 'DESC';
pietergoosen_pop_update_post_meta($post_id, '_asc', $meta);
$meta = isset( $_POST['_post_count'] ) ? $_POST['_post_count'] : get_option('posts_per_page');
pietergoosen_pop_update_post_meta($post_id, '_post_count', $meta);
$meta = isset( $_POST['_days'] ) ? $_POST['_days'] : 0;
pietergoosen_pop_update_post_meta($post_id, '_days', $meta);
return;
}
}
}
function pietergoosen_pop_update_post_meta($post_id, $key, $data) {
$post_meta = get_post_meta($post_id, $key, true);
if( $data != '' && $post_meta != $data) {
update_post_meta($post_id, $key, $data);
} elseif ( $post_meta != '' && $data == '' ) {
delete_post_meta($post_id, $key);
}
}
?>
Secondly, the page template. You have to call this template page-pop.php
<?php
/**
* Template Name: Page of Posts
*/
get_header(); ?>
<?php
//See if we have any values
$post_meta=array();
$post_meta = get_post_meta( $post->ID,false );
$catid = isset( $post_meta['_cat_id'] ) ? $post_meta['_cat_id'][0] : 1;
$page_title = isset( $post_meta['_page_title'] ) ? $post_meta['_page_title'][0] : '';
$posts_title = isset( $post_meta['_posts_title'] ) ? $post_meta['_posts_title'][0] : '';
$orderby = isset( $post_meta['_order_by'] ) ? $post_meta['_order_by'][0] : 'date';
$asc = isset( $post_meta['_asc'] ) ? $post_meta['_asc'][0] : 'DESC';
$list_style = isset( $post_meta['_list_style'] ) ? $post_meta['_list_style'][0] : 'default';
$post_count = isset( $post_meta['_post_count'] ) ? $post_meta['_post_count'][0] : get_option('posts_per_page');
if(!$post_count || !is_numeric( $post_count )) $post_count = get_option('posts_per_page');
$days = isset( $post_meta['_days'] ) ? $post_meta['_days'][0] : 0;
if($days && !is_numeric( $days )) $days = 0;
$do_not_show_stickies = ($list_style == 'default') ? 0 : 1;
?>
<div id="main-content" class="main-content">
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<!-- Page Title -->
<?php if( $posts_title ) : ?>
<article id="posts-title">
<header class="entry-header">
<h2 class="entry-title"><?php echo $posts_title; ?></h2>
</header><!-- .entry-header -->
</article><!-- #posts-title -->
<?php endif; ?>
<?php the_post(); ?>
<?php global $post;
if( $post->post_content || $page_title ) : ?>
<div class="entry-content">
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if( $page_title ) : ?>
<header class="entry-header">
<h1 class="entry-title"><?php echo $page_title; ?></h1>
</header><!-- .entry-header -->
<?php endif; ?>
<?php if( $post->post_content ) : ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'pietergoosen' ) . '</span>', 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<footer class="entry-meta">
</footer><!-- .entry-meta -->
<?php endif; ?>
</article><!-- #post-<?php the_ID(); ?> -->
</div>
<?php endif; ?>
<?php
/* Do we have any category */
global $post;
// Save posts for later use
$tmp_post = $post;
$args = array(
'cat' => $catid,
'posts_per_page' => $post_count,
'paged' => $paged,
'orderby' => $orderby,
'order' => $asc,
'ignore_sticky_posts' => $do_not_show_stickies,
);
if( $days ) {
function pop_filter_where( $where = '') {
global $days;
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-' .$days .' days')) . "'";
return $where;
}
add_filter( 'posts_where', 'pop_filter_where' );
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query( $args );
remove_filter( 'posts_where', 'pop_filter_where' );
} else {
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query( $args );
}
// Output
if ( $wp_query->have_posts() ) :
// Start the Loop.
while ( $wp_query->have_posts() ) : $wp_query->the_post();
get_template_part( 'content', get_post_format() );
endwhile;
pietergoosen_pagination();
else :
get_template_part( 'content', 'none' );
endif; ?>
<?php
// Reset the post to the page post
$post = $tmp_post;
?>
<?php if ( comments_open() || get_comments_number() ) {
comments_template();
} ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar( 'content' ); ?>
</div><!-- #main-content -->
<?php
get_footer();
You can now simply create a new page and choose the "page of posts" template, and publish your page. Once that is done, the Page of Posts metabox will appear. From that you can choose the category to display on that page.
There's a plugin that will do that. http://wordpress.org/plugins/posts-per-cat/
He used the plugin then set it to a ridiculous number so that it would show all the categories on the page. Here's the link to the website I found the answer on:
https://wordpress.stackexchange.com/questions/45856/show-posts-of-category-in-a-page
I hope that helps.
How can I test to see if a WP_Query object does not return any matches? I'd like to be able to do something like this is a template:
<?php
$my_query = new WP_Query(array('post_type' => 'biographies'))
if( ***HOW DO I TEST $my_query HERE*** ) {
//if $my_query finds anything loop through it here
} else {
//if $my_query does not find anything
}
?>
EDIT
Better example, I want to only display the h2 if the query finds anything:
<?php
$outside_leasing_query = new WP_Query(array( 'post_type' => 'resin_biographies', 'tax_query' => array(
'relation' => 'AND',
array( 'taxonomy' => 'resin_buildings', 'field' => 'slug', 'terms' => $page_slug ),
array( 'taxonomy' => 'resin_leasing_companies', 'field' => 'slug', 'terms' => 'rubenstein-partners', 'operator' => 'NOT IN' )
) )); // resin_buildings taxonomy term slug must match page slug
?>
<h2>Outside Leasing Contacts</h2>
<?php while ( $outside_leasing_query->have_posts() ) : $outside_leasing_query->the_post(); ?>
<article <?php post_class('group'); ?>>
<?php
if( get_post_meta( $post->ID, '_biography_headshot', true ) != '' ) {
echo '<img class="contact-thumb" src="' . get_post_meta( $post->ID, '_biography_headshot', true ) . '" alt="'. get_the_title() .'" />';
} else {
echo '<img class="contact-thumb-placeholder" src="' . get_bloginfo('template_url') . '/images/default_headshot.jpg" alt="'. get_the_title() . '" />';
}
?>
<div class="contact-info">
<hgroup>
<?php the_title( '<h3>', '</h3>' ); ?>
<h4 class="contact-title"><?php echo get_post_meta( $post->ID, '_biography_title', true ); ?></h4>
</hgroup>
<div class="contact-address"><?php echo wpautop( get_post_meta( $post->ID, '_biography_address', true ) ); ?></div>
<div class="contact-tel"><span>T</span> <?php echo get_post_meta( $post->ID, '_biography_tel', true ); ?></div>
<?php if( get_post_meta( $post->ID, '_biography_fax', true ) != '' ) { ?>
<div class="contact-fax"><span>F</span> <?php echo get_post_meta( $post->ID, '_biography_fax', true ); ?></div>
<?php } ?>
<div class="contact-email"><?php echo get_post_meta( $post->ID, '_biography_email', true ); ?></div>
</div>
</article>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
The standard Wordpress Loop does this for you using have_posts().
<?php
$my_query = new WP_Query(array('post_type' => 'biographies'));
if($my_query->have_posts()) : while($my_query->have_posts()) : $my_query->the_post();
?>
<!-- YOUR POST(S) -->
<?php endwhile; else : ?>
<p>No posts found</p>
<?php endif; ?>
I figure you could use:
!($my_query->have_posts())
so:
<?php
$my_query = new WP_Query(array('post_type' => 'biographies'))
if( !($my_query->have_posts())) {
//if $my_query finds anything loop through it here
} else {
//if $my_query does not find anything
}
?>
In your first example, where you have the comment:
//if $my_query does not find anything
Just set a parameter like this:
$my_query_found_something = 'not';
Then use it wherever you need like this:
if ($my_query_found_something == 'not') {
// keep looking
}