I have three drop-down select option. Inside each drop-down, I have shown the Sub-category for example shown below.
Service
Mobile development
Web development
Software development
Technology
Android
IOS
Java
Industry
Commerce
Education
Lifestyle
Here Service, Technology, and Industry are the category of CPT and inside it like Mobile Development, IOS and Commerce are the sub-categories of the main category.
Now what I want to do on change of any of the three category show post of that sub-category only.
For example, if I select IOS then show the post of IOS only similar with others if the user selects IOS, Mobile Development, and Lifestyle then show post of all three.
To achieve this I have to use the change jQuery function and calling the ajax on change event. The problem is I am getting the same post for all the post select please help me through it.
You Can achieve this by Following this -
Firstly You Register a Custom Post Type like 'Course' in my Code.
Then you need to Add Custom Taxonomy For this like 'Course Type' in my Code.
Then get All Posts with using Page Template or Any other method which you are followed.
I add this code in my Page Template then attach those Page Template to a Page, Here i get all posts when page reload with thre Select boxes for Parent Terms like 'Service', 'Technology', 'Industry' -
<div class="course_content">
<?php $parent_terms = get_terms( 'course_type', array( 'parent' => 0 ) );
foreach( $parent_terms as $parent_term ){
$children_terms = get_terms('course_type', array('parent' => $parent_term->term_id) );
if($children_terms){
?>
<select class="select_course_type <?php echo 'course_type-'.$parent_term->slug; ?>">
<option value=""><?php echo 'Select '.$parent_term->name; ?></option>
<?php
foreach( $children_terms as $children_term ){
echo '<option value="'.$children_term->slug.'">'.$children_term->name.'</option>';
}
?>
</select>
<?php
}
}
?>
<input type="hidden" value="" id="selected_course_type" />
<div class="display_posts">
<?php
$args = array(
'post_type' => 'course',
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) :
echo '<ul>';
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<h4><?php the_title() ;?></h4>
</li>
<?php endwhile;
echo '</ul>';
endif;
wp_reset_query(); ?>
</div>
</div>
Then you add jquery code in your JS File For Calling Ajax, like this -
$('.select_course_type').on('change', function(){
var s = $(this).val();
$("option", this).removeAttr('selected');
$("option[value='" + s + "']", this).attr('selected', 'selected');
ct_Array = [];
$('.select_course_type').each(function(){
var t = $(this).val();
if(t != ''){
ct_Array.push($(this).val());
}
});
var ajax_url = FrontAjax.ajaxurl;
data = {
action: 'ajax_filter_for_courses',
s_ctValues: ct_Array,
};
$.post( ajax_url, data, function(response) {
if( response ){
$('.display_posts').html(response);
}
});
});
Then add this code in Functions.php File for getting Posts after Filter-
add_action('wp_ajax_nopriv_ajax_filter_for_courses', 'filter_for_courses');
add_action('wp_ajax_ajax_filter_for_courses', 'filter_for_courses');
function filter_for_courses() {
$explode_ct = $_POST['s_ctValues'];
$tax_query = array();
if(isset($explode_ct)) {
$tax_query[] = array(
'taxonomy' => 'course_type',
'field' => 'slug',
'terms' => $explode_ct
);
}
$args = array(
'post_type' => 'course',
'tax_query' => $tax_query
);
$filter_query = new WP_Query( $args );
if ( $filter_query->have_posts() ) {
echo '<ul>';
while ( $filter_query->have_posts() ) : $filter_query->the_post();
?>
<li>
<h4><?php the_title() ;?></h4>
</li>
<?php
endwhile;
echo '</ul>';
}
wp_reset_query();
die(); //stop "0" from being output
}
$posts_array = get_posts(
array(
'posts_per_page' => 6,
'post_type' => 'acme_portfolio',
'tax_query' => array(
array(
'taxonomy' => 'portfolio_category',
'field' => 'term_id',
'terms' => array($post_id),
)
)
));
Put this in function.php
Related
Try to achieve this:
I made a ACF (custom field) in my WooCommerce Product and now I try to get this field shown in my template with this code:
<ul class="products">
<?php
$args = array(
'posts_per_page' => 20,
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_type',
'field' => 'name',
'terms' => 'grouped',
),
),
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$linked_with_items = the_field('linked_with_items');
the_title('<strong>', '</strong>'); echo '<br />';
echo $linked_with_items;
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->
But whatever I try also with get_field() the field does not show in my template.
Can someone help?
https://www.advancedcustomfields.com/
This is the final code fyi
<?php if( have_rows('catalogue') ): ?>
<?php
while( have_rows('catalogue') ): the_row(); // catalogue is the field
the_sub_field('linked_with_items'); ?>
<?php endwhile; ?>
<?php endif; ?>
You could try with this:
$linked_with_items = get_field('linked_with_items', get_the_ID());
If that doesn't work, just as a test, you could try to simply loop over posts with a foreach
foreach ( $loop->posts as $post ) {
$linked_with_items = get_field('linked_with_items', $post->ID);
}
If none of those work, please make sure that your product actually have that custom field, double check the ACF field settings (rule section), the field slug, and double check your product edit page to see if the fields shows there.
Maybe this questions already asked but that not helpful for my question.
Am creating a API for my WordPress project. So i want to send API for to get all products with pagination.
I get products list using this code:
android/all_products.php
<?php
require_once('../wp-load.php');
$args = array(
'post_type' => 'product',
'posts_per_page' => 10
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<br />' . woocommerce_get_product_thumbnail().' '.get_the_title().'';
endwhile;
wp_reset_query();
?>
I got all products, but i want to show products with pagination.
Note: all the API's are written in inside android folder.
Thanks in advance.
below pagination code is to show next products you can also do it to show previous product by applying same method
if(isset( $_GET['page_num'] ) ) {
$page_number = $_GET['page_num'];
} else {
$page_number = 2;
}
$args = array (
'limit' => 3,
'page' => $page_number,
);
$products = wc_get_products( $args );
foreach( $products as $product ) {`enter code here`
//your data here
// e.g $product_name = $product->get_name();
}
Next
If you want to create API's then just use Woocommerce rest API's which are built in function given in wordpress please use below url it will give you list of products with lots of options:
{{your_url}}/wp-json/wc/v2/products
Go to wp-admin and go to Woocommerce -> settings -> API
-> Enable rest API
-> Go to Key/Apps and create Auth Keys both secret and Private (Copy that keys)
Then give this above url to add it for use in application with o_auth of secret key and private key.
Please see this link for all woocommerce API's : https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-a-product
Finally i creating a code and send the date using API.
<?php
require_once('../wp-load.php');
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$brand_product_list = new WP_Query( $args);
$pagination_count = 1;
while($brand_product_list->have_posts()) : $brand_product_list->the_post();
$pagination_count++;
endwhile; wp_reset_query();
//echo'<pre>';print_r($pagination_count/12); exit;
wp_reset_query();
?>
<?php
$pagination = round($pagination_count/12);
for($i=1;$i<=$pagination;$i++)
{
$pagination_no[] = $i;
?>
<!-- <a class="product-category-view-all" href="?pagination=<?php echo $i; ?>"><?php echo $i; ?></a> -->
<?php } ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : $_GET['pagination'];
$args = array(
'post_type' => 'product',
'paged' => $paged,
'posts_per_page' => 12,
);
$wp_query = new WP_Query($args);
while($wp_query->have_posts()) : $wp_query->the_post();
$product_data = wc_get_product( $post->ID );
if(!empty(get_the_post_thumbnail_url($product_data->get_id())))
{
$img = get_the_post_thumbnail_url($product_data->get_id());
}
else
{
$img = "";
}
$product_list[] = array(
'product_id' => $product_data->get_id(),
'product_name' => $product_data->get_title(),
'product_regular_price' => $product_data->get_regular_price(),
'product_sale_price' => $product_data->get_sale_price(),
'product_price' => $product_data->get_price(),
'img' => $img,
'rating' => $product_data->get_average_rating(),
'stock_quantity' => $product_data->get_stock_quantity(),
'stock' => $product_data->is_in_stock(),
);
endwhile; wp_reset_query();
$data[] = array(
'pagination' => $pagination_no,
'product_list' => $product_list
);
//echo json_encode($peoduct_list, $pagination)
echo json_encode($data)
?>
I am trying to display same custom post query multiple time in same page. The between the post is it will call different custom taxonomy based on one custom post type. When I am trying to call same custom post second time its not working. But showposts =2 is working but I need to display one post for a single post query. Here is the codes:
<div class="col-sm-6">
<?php
$querevent = new WP_Query( array(
'post_type' => 'tatstory', // name of post type.
'showposts' => 1,
) );
if ( $querevent->have_posts() ):
// Yep, we have posts, so let's loop through them.
while ( $querevent->have_posts() ) : $querevent->the_post(); ?>
<?php if ( has_term('event','eventname' ) && has_term('featured-in-story-page','fetstory' )) { ?>
<div class="listing_inner">
<div class="listing_img">
<?php the_post_thumbnail( 'shop-story', array( 'class' => 'img-fluid' ) ); ?>
</div>
<div class="listing_texts">
<p class="event yellow">Event</p>
<h2><?php the_title(); ?></h2>
</div>
</div>
<?php
} ?>
<?php endwhile;
else :
// No, we don't have any posts, so maybe we display a nice message
echo "<p class='no-posts'>" . __( "Sorry, there are no posts at this time." ) . "</p>";
endif;
?>
</div>
<div class="col-sm-6">
<?php
$quernews = new WP_Query( array(
'post_type' => 'tatstory', // name of post type.
'showposts' => 1,
) );
if ( $quernews->have_posts() ):
// Yep, we have posts, so let's loop through them.
while ( $quernews->have_posts() ) : $quernews->the_post(); ?>
<?php if ( has_term('news','eventname' ) && has_term('featured-in-story-page','fetstory' )) { ?>
<div class="listing_inner">
<div class="listing_img">
<?php the_post_thumbnail( 'shop-newscat', array( 'class' => 'img-fluid' ) ); ?>
</div>
<div class="listing_texts_right">
<p class="event blue">News</p>
<h2><?php the_title(); ?></h2>
</div>
</div>
<?php } ?>
<?php endwhile;
wp_reset_postdata();
else :
// No, we don't have any posts, so maybe we display a nice message
echo "<p class='no-posts'>" . __( "Sorry, there are no posts at this time." ) . "</p>";
endif;
?>
First i would change your WP_Query, example:
$query = new WP_Query( array(
'post_type' => 'tatstory',
'posts_per_page' => '1',
'tax_query' => array(
array (
'taxonomy' => 'eventname',
'field' => 'slug',
'terms' => 'news',
),
array (
'taxonomy' => 'fetstory',
'field' => 'slug',
'terms' => 'featured-in-story-page',
)
),
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// display content
}
} else {
// display when no posts found
}
wp_reset_postdata(); // Restore original Post Data
The query will only collect posts that have the correct terms set.
Restoring original Post Data on the end (wp_reset_postdata()) may help you with calling a new WP_Query again. But I don't know of any reason why you cannot call it twice in a single page template.
I am trying to get an image URL with attachment size using an advanced custom field. The field is set to ID. I've used this approach to get other images by ID with no problem. Yet this one isn't pulling the rendered image. It's pulling the ID number and displaying it on the page. I'm stumped...
<?php
$the_query = new WP_Query( array(
'post_type' => 'listicles',
'tax_query' => array(
array (
'taxonomy' => 'visibility',
'field' => 'slug',
'terms' => 'listicles-resortsvisible',
),
),
) );
$listicleimage = the_field('listicle_featured_image', $post->ID);
$listicleimgsize = 'listicle-thumb';
$listicleimg_array = wp_get_attachment_image_src($listicleimage, $listicleimgsize);
$listicleimg_url = $listicleimg_array[0];
?>
<ul
class="row small-up-1 medium-up-2">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li class="small-12 medium-6 column">
<img
src="<?php echo $listicleimg_url; ?>"
class="align-center" />
//THE REST OF MY CONTENT//
</li>
<?php endwhile;?>
<?php endif; ?>
</ul>
<?php wp_reset_query(); ?>
You only need to change
the_field('listicle_featured_image', $post->ID);
to
get_field('listicle_featured_image', $post->ID);
You should be using wp_get_attachment_image and not wp_get_attachment_image_src.
wp_get_attachment_image accepts ID's as an argument.
Source: https://developer.wordpress.org/reference/functions/wp_get_attachment_image/
Add this to functions.php
function img_by_id($id, $size, $url) {
$the_img = wp_get_attachment_image($id, $size);
if ($url != true) {
return $the_img;
}
else {
$img_src = get_attr($the_img, 'src');
return $img_src;
}
}
function get_attr($html, $attr) {
$pc = explode($attr.'="', $html);
$pc2 = explode('"', $pc[1]);
return $pc2[0];
}
Then
<?php
$the_query = new WP_Query( array(
'post_type' => 'listicles',
'tax_query' => array(
array (
'taxonomy' => 'visibility',
'field' => 'slug',
'terms' => 'listicles-resortsvisible',
),
),
) );
$listicleimage = the_field('listicle_featured_image', $post->ID);
$listicleimg_url = img_by_id( $listicleimage, 'listicle-thumb', true);
?>
if you need full image attribute with sizes $img = img_by_id( $listicleimage, 'listicle-thumb', false);
If you need specific attribute from html tag $attr = get_attr($html, $attr);
I have this on my blank WP theme template.
I am looking to have a drop down menu at the top of a category page that will allow me to then filter the posts by date.
I will most probably have to make use of custom fields, but that isn't the issue.
I know you can make a custom post query using GET style variables, but with pretty URLs enabled, I cannot seem to use the GET variables to filter specific posts (e.g. www.domain.com/category/?orderby=title&order=ASC etc etc )
I have tried looking for plugins, but nothing seems to jump out at me for what I need, and I have also noticed a lot of talk on here about similar subjects, with no decent solutions for my situation.
The general query would be this like :
<?php $posts = query_posts( $query_string . '&orderby=date&order=asc' ); ?>
<?php if( $posts ) : ?>
//whatever
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
//whatever
<p><?php the_content(); ?></p>
<?php endforeach; ?>
<?php endif; ?>
For dropdown, you can do something like this :
$args = $args=array(
'cat' => $cat_id,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'DATE',
'order' => 'ASC' // or DESC
);
<form action="<? bloginfo('url'); ?>" method="get">
<select name="page_id" id="page_id">
<?php
global $post;
$args = array( 'numberposts' => -1);
$posts = get_posts($args);
foreach( $posts as $post ) : setup_postdata($post); ?>
<option value="<? echo $post->ID; ?>"><?php the_title(); ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="view" />
</form>
And another option :
<?php
$cat_id = get_cat_ID('uncategorized'); //your-category
$args=array(
'cat' => $cat_id,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'DATE',
'order' => 'ASC' // or DESC
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
?>
<form name="jump">
<select name="menu">
<?php
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<option value="<?php the_permalink() ?>"><?php the_title(); ?></option>
<?php
endwhile;
}
?>
</select>
<input type="button" onClick="location=document.jump.menu.options[document.jump.menu.selectedIndex].value;" value="Go">
</form>
<?php
wp_reset_query();
?>
i was looking for search posts by date. didn't able to found suitable solution on stackoverflow. i then printed the wp_query object and sorted this thing out. it worked for me. in my scenario m searching for posts by their title or by date. here is the code for the hook.
function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
// check if query is a date
$search_query = $query->query['s'];
$date_format = DateTime::createFromFormat('d/M/Y', $search_query);
if ($date_format)
{
$dte = date('j',$date_format->getTimestamp());
$month = date('n',$date_format->getTimestamp());
$year = date('Y',$date_format->getTimestamp());
}
if (isset($dte) && isset($month) && isset($year)) {
unset($query->query['s']);
unset($query->query_vars['s']);
$query->query['date_query'] = array(
array(
'year' => $year,
'month' => $month,
'day' => $dte,
)
);
$query->set('date_query', array(
array(
'year' => $year,
'month' => $month,
'day' => $dte,
)
)
);
}
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
as u can notice this filter automatically checks if passed param is string or date. m using
$query->set('post_type', 'post')
to get results of post only other wise it will fetch page too.
suppose u have date under each post u can add href to that date. so to get all posts of that date
on the end of href add search param like ?s=something
http://my.blog?s=1/Jun/2015
and so on the template u dont need to write ur custom forwhile just use default template functions like have_posts()