I have created / mashed together a cool search through a specified category for my blog. Using Ajax to load the results without the reload.
When I search - no matter the term I search. I receive all posts.
I use ACF for the content & the author. I also reference products using the field featured_product_title. These fields are used within my page like this:
<?php if ( have_rows('case_study_page_content') ): ?>
<?php
while (have_rows('case_study_page_content')): the_row();
$title = get_sub_field('title');
$author = get_sub_field('author');
$content = get_sub_field('content');
?>
<div class="">
<h1 class=""><?php echo $title; ?></h3>
<h3 class=""><?php echo $author; ?></h4>
<p><?php echo $content; ?></p>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php
while (have_rows('featured_products')): the_row();
$featured_product_title = get_sub_field('featured_product_title', 'featured_products');
?>
With these in mind my current search looks like this (functions.php):
// CASE STUDY SEARCH
function my_search(){
$args = array(
'orderby' => 'date',
'order' => $_POST['date']
);
if( isset( $_POST['s'] ) ):
/*
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
's' => $_POST['s']
);
*/
if( have_rows('case_study_page_content') ):
while( have_rows('case_study_page_content') ) : the_row();
$title = get_sub_field('title');
$author = get_sub_field('author');
$content = get_sub_field('content');
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => $title,
'compare' => 'like',
'value' => '%'.$_POST['s'].'%',
),
array(
'key' => $author,
'compare' => 'like',
'value' => '%'.$_POST['s'].'%',
),
array(
'key' => $content,
'compare' => 'like',
'value' => '%'.$_POST['s'].'%',
)
)
);
endwhile;
endif;
$query = new WP_Query($args);
if( $query->have_posts() ):
while( $query->have_posts() ):
$query->the_post();
echo "<article class=\"post-box " . get_post_class() . "\">";
echo "";
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' );
echo "<img src=\"" . $url . "\" />";
echo "<h2>" . get_the_title() . "</h2>";
$case_study = get_field('case_study_page_content');
if( $case_study ):
while( have_rows('case_study_page_content') ): the_row();
$case_study_author = get_sub_field('author');
echo "<p>" . $case_study_author . "</p>";
endwhile;
endif;
echo "</article>";
endwhile;
wp_reset_postdata();
else :
echo 'No case studies found';
endif;
die();
endif;
}
add_action('wp_ajax_customsearch', 'my_search');
add_action('wp_ajax_nopriv_customsearch', 'my_search');
I guess my question is how do I add ACF's into the $args array...?
Please can someone help me successfully compare the 'key' to the 'value' in my WP_Query($args)?
Thanks everyone, Jason.
test this but without conviction
// args
$args = array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'case_study_page_content_title',
'compare' => 'like',
'value' => '%'.$_POST['s'].'',
),
array(
'key' => 'case_study_page_content_author',
'compare' => 'like',
'value' => '%'.$_POST['s'].'%',
),
array(
'key' => 'case_study_page_content_content',
'compare' => 'like',
'value' => '%'.$_POST['s'].'%',
)
)
);
function custom_search_query( $query ) {
if ( !is_admin() && $query->is_search ) {
$result = $query->query_vars['s'];
$query->query_vars['s'] = '';
$query->set('meta_query', array('relation' => 'OR',
array(
'key' => 'acf_name', // ACF FIELD NAME OR POST META
'value' => $result,
'compare' => 'LIKE',
)
));
$query->set('post_type', 'post'); // optional POST TYPE
}
}
add_filter( 'pre_get_posts', 'custom_search_query');
Related
i want to get the author's posts in spacific category and display it in author page
I tried this code and it didn't work, what is the problem? my code :
<?php
$url= get_site_url();
$author_id = get_the_author_meta('ID');
$args = array(
'author' => $author_id,
'tax_query' => array(
'relation' => 'AND',
array(
'cat' => '161,181,157',
'post_count' => '3',
),
),
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) {
$query->the_post();
$postid = get_the_ID();
echo '<a href='. $url .'?p='. $postid .'>' . get_the_title() . '</a>';
}
?>
Try the below code.
$url = get_site_url();
$author_id = get_the_author_meta('ID');
$args = array(
'author' => $author_id,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array(161,181,157)
),
),
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) {
$query->the_post();
$postid = get_the_ID();
echo '<a href='. $url .'?p='. $postid .'>' . get_the_title() . '</a>';
}
Im trying to make a custom shortcode in order to display some product variations that have no stock quantity with stock <= 0.
Here's what I did so far:
if( ! function_exists('preorable_products') ) {
// Add Shortcode
function preorable_products( $atts ) {
global $woocommerce_loop;
// Attributes
$atts = shortcode_atts(
array(
'columns' => '4',
'limit' => '20',
'preordable' => "yes",
'stock' => 0,
),
$atts, 'preorable_products'
);
$woocommerce_loop['columns'] = $atts['columns'];
// The WP_Query
$products_variation = new WP_Query( array (
'post_type' => 'product_variation',
'post_status' => 'publish',
'fields' => 'id=>parent',
'posts_per_page' => $atts['limit'],
'meta_query' => array(
'relation' => 'AND',
'preordable' => array(
'key' =>'_ab_preorder_checkbox',
'value' => "yes",
'compare' => '=='
),
'stock' => array(
'key' =>'_stock',
'value' => 0,
'compare' => '<='
),
)
));
$products = $products_variation;
ob_start();
if ( $products->have_posts() ) { ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
} else {
do_action( "woocommerce_shortcode_products_loop_no_results", $atts );
echo "<p>Aucun article disponible à la précommande.</p>";
}
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
}
add_shortcode( 'preorable_products', 'preorable_products' );
}
The WP Query part seems to work perfectly, but the code part to display the product seems wrong. I feel like $product variable doesn't have have_post method :
if ( $products->have_posts() ) { ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php
} else {
do_action( "woocommerce_shortcode_products_loop_no_results", $atts );
echo "<p>Aucun article disponible à la précommande.</p>";
}
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
Any help is welcome.
There are some errors and missing things in your code, use instead the following revisited code:
if( ! function_exists('get_preordable_products') ) {
function get_preordable_products( $atts ) {
// Shortcode Attributes
extract( shortcode_atts( array(
'columns' => '4',
'limit' => '20',
'preordable' => "yes",
'stock' => 0,
), $atts, 'preordable_products' ) );
// The WP_Query
$query = new WP_Query( array (
'post_type' => 'product_variation',
'post_status' => 'publish',
'posts_per_page' => $limit,
'meta_query' => array(
'relation' => 'AND',
'preordable' => array(
'key' =>'_ab_preorder_checkbox',
'value' => "yes",
'compare' => '=='
),
array(
'key' =>'_stock',
'value' => 0,
'compare' => '<='
),
)
) );
global $woocommerce_loop;
$woocommerce_loop['columns'] = $columns;
$woocommerce_loop['is_shortcode'] = 1;
$woocommerce_loop['name'] = 'preordable_products';
$woocommerce_loop['total'] = $query->post_count;
$woocommerce_loop['total_pages'] = $query->max_num_pages;
$woocommerce_loop['per_page'] = $limit;
ob_start();
if ( $query->have_posts() ) {
woocommerce_product_loop_start();
while ( $query->have_posts() ) {
$query->the_post();
wc_get_template_part( 'content', 'product' );
}
woocommerce_product_loop_end();
woocommerce_reset_loop();
wp_reset_postdata();
} else {
do_action( "woocommerce_shortcode_products_loop_no_results", $atts );
echo '<p>'. __("Aucun article disponible à la précommande.") . '</p>';
}
$content = ob_get_clean();
return '<div class="woocommerce columns-' . $columns . '">' . $content . '</div>';
}
add_shortcode( 'preordable_products', 'get_preordable_products' );
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Usage: [preordable_products] or in Php code echo do_shortcode('[preordable_products]');
I'm trying to create a custom easy digital downloads (EDD) shortcode and I can't make the atts working. Meaning I would like to be able to change the category and tag names while using the shortcode, e.g :
<?php echo do_shortcode( '[my_shortcode taxonomy="download_tag" field="name" terms="Premium"]' ); ?>
But all I get is the default term ( Free ).
The code:
function my_shortcode_function($product_args, $content = null) {
global $post;
$current_page = get_query_var('paged');
$offset = $current_page > 0 ? $per_page * ($current_page-1) : 0;
$product_args = array(
'post_type' => 'download',
'posts_per_page' => '6',
'tax_query' => array(
array(
'taxonomy' => 'download_tag',
'field' => 'name',
'terms' => 'Free'
),
),
'offset' => $offset
);
$products = new WP_Query($product_args);
if ($products->have_posts()) : $i = 1;
while ($products->have_posts()) : $products->the_post();
$tags = get_the_term_list( get_the_ID(), 'download_tag' );// get tags link
$tags = strip_tags( $tags ); // get rid of the tag link
$category = get_the_term_list( get_the_ID(), 'download_category' ); // get category link
echo '<div class="col-md-4 col-lg-4">';
get_template_part( 'template-parts/content-download-card-post' );
echo '</div>';
$i+=1;
endwhile;
else :
get_template_part( 'template-parts/content', 'none' );
endif;
}
add_shortcode( 'my_shortcode', 'my_shortcode_function' );
I'm sure there are better ways to do it but I'm still new in php and the EDD docs lacks of useful examples for newbies like me. So I'll appreciate any help. Thanks a lot.
It's funny that I implemented this from a woocommerce answer and it works like a charm. Now I can change the tag, category, or the number of posts. If anyone needs it here it is:
// Creating a shortcode that displays a random product image/thumbail
if( !function_exists('prod_listing_params') ) {
function prod_listing_params( $atts ) {
ob_start();
$atts = shortcode_atts( array (
'type' => 'download',
'order' => 'date',
'orderby' => 'title',
'posts' => 6,
'category' => '', // category name
'tag' => '', // tag name
), $atts, 'list_products' );
$query = new WP_Query( array(
'post_type' => $atts['type'],
'order' => $atts['order'],
'orderby' => $atts['orderby'],
'posts_per_page' => $atts['posts'],
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'download_category',
'field' => 'name',
'terms' => $atts['category'],
),
array(
'taxonomy' => 'download_tag',
'field' => 'name',
'terms' => $atts['tag'],
)
),
) );
if ( $query->have_posts() ) { $i = 1;
?>
<?php while ( $query->have_posts() ) : $query->the_post();
$tags = get_the_term_list( get_the_ID(), 'download_tag' );// get tags link
$tags = strip_tags( $tags ); // get rid of the tag link
$category = get_the_term_list( get_the_ID(), 'download_category' ); // get category link
?>
<?php echo '<div class="col-md-4 col-lg-4">';
get_template_part( 'template-parts/content-download-card-post' );
echo '</div>'; $i+=1; ?>
<?php endwhile;
wp_reset_postdata(); ?>
<?php
$myvar = ob_get_clean();
return $myvar;
}
}
add_shortcode( 'list_products', 'prod_listing_params' );
And the use:
<?php echo do_shortcode( '[list_products tag="Free" posts="3"]' ); ?>
I've got a wp-query that works a treat on a small section of my website's dashboard - it displays a list of repeat jobs (CPTs) that are due in 6 weeks time - I'm having issues with displaying a taxonomy related to the post.
So far I've got
<?php
// get posts
$before_date = date("Ymd", strtotime("+6 weeks"));
$posts = get_posts(array(
'post_type' => 'pre_jobs',
'posts_per_page' => -1,
'meta_key' => 'pre_job_due_date',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'pre_job_due_date',
'value' => $before_date,
'compare' => '<',
),
),
'tax_query' => array(
array(
'taxonomy' => 'pre_job_status',
'field' => 'slug',
'terms' => array( 'repeat' )
),
),
));
if( $posts ): ?>
<hr>
<div class="dashpanel">
<div class="duedate-head">Due Date</div>
<div class="jobnumber-head">Job Type</div>
<div class="client-head">Client/Requestor</div>
<div class="customer-head">Customer</div>
</div>
<hr>
<?php foreach( $posts as $post ):
setup_postdata( $post )
?>
<?php $job_type = get_field('pre_job_job_type', $client->ID ); ?>
<?php $customer = get_field('pre_job_customer', $client->ID ); ?>
<?php $job_client = get_field('pre_job_requestor', $client->ID ); ?>
<div class="dashpanel">
<a href="<?php the_permalink(); ?>">
<div class="duedate"><?php the_field('pre_job_due_date'); ?></div>
<div class="jobnumber"><?php echo $job_type[0]->post_title; ?></div>
<div class="client"><?php echo $job_client[0]->post_title; ?></div>
<div class="customer"><?php echo $customer[0]->post_title; ?></div></a>
</div>
<hr>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p>No upcoming jobs to book in.</p>
<?php endif; ?>
I'm not sure where I need to put the
<?php
$pre_job_type = get_field('pre_job_job_type');
if( $term ): ?>
Code - every time I add this code it breaks. Or am I going completely wrong somewhere?
You can add this code after you open the if ($posts) loop:
It will show the taxonomy to which this publication is related. with a link to it.
If you prefer, you can remove the link and display only the title of the term with the call $term->name
<?php
$terms = get_the_terms( $post->ID, 'YOUR_TAXONOMY_HERE' );
if ( $terms != null ) {
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'YOUR_TAXONOMY_HERE' );
echo '<li>' . $term->name . ' ' . $term->term_id . ' ' . $term->count . '</li>';
unset( $term );
}
}
?>
Have you created your expected taxonomy? If haven't at first create the taxonomy on your functions.php file or where you have created your custom post type.
Example:
/**
* Register a private 'Genre' taxonomy for post type 'book'.
*
* #see register_post_type() for registering post types.
*/
function wpdocs_register_taxonomy() {
$args = array(
'label' => __( 'Job Type', 'textdomain' ),
'public' => true,
'rewrite' => true,
'hierarchical' => true
);
register_taxonomy( 'pre_job_job_type', 'pre_jobs', $args );
}
add_action( 'init', 'wpdocs_register_taxonomy', 0 );
Or OOP approach:
public function wpdocs_register_taxonomy() {
$args = array(
'label' => __( 'Job Type', 'textdomain' ),
'public' => true,
'rewrite' => true,
'hierarchical' => true
);
register_taxonomy( 'pre_job_job_type', 'pre_jobs', $args );
}
/**
* When class is instantiated
*/
public function __construct() {
add_action('init', array($this, 'wpdocs_register_taxonomy'));// Register texonomy
}
Now your taxonomies are ready to display. Place this code where ever you want to display the taxonomies.
$pre_job_types = get_categories('taxonomy=pre_job_job_type&post_type=pre_jobs');
foreach ($pre_job_types as $job_type ) : ?>
<span> <?php echo $job_type->name; </span>
endforeach;
If you want to query your custom post with the taxonomy, follow this:
$args = array(
'post_type' => 'pre_jobs',
'status' => 'published',
'tax_query' => array(
array(
'taxonomy' => 'pre_job_job_type',
'field' => 'name',
'terms' => array( 'repeat' )
)
)
);
$query = new WP_Query( $args );
And then continue as a normal query. This query only display the posts whose taxonomy is "repeat".
I'm building a hotel finder site and want to filter my search results by custom fields when the user searches a location. So for example when a user types in 'London' it will find hotels in London based on some custom fields they have added. But it only works when the search is example.com/?s= if I search a location like example.com/?s=London my pagination doesn't show. But if I add no location and leave the search blank like example.com/?s= pagination shows and works correctly. Would anyone know why? I'm not that great at php so I really need some help. My current search.php file looks like this.
<?php $unique_id = esc_attr( uniqid( 'search-form-' ) ); ?>
<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="search" id="<?php echo $unique_id; ?>" class="search-field" value="<?php echo get_search_query(); ?>" name="s" />
<button type="submit" class="search-submit">Search</button>
</form>
<?php $searchm = get_search_query(); ?>
<?php if ( get_search_query() == '' ): ?>
<?php
$args_a = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'CurrentLocation',
'value' => array($areauserwants, areauserwants2),
'compare' => 'IN',
),
array(
'key' => 'AreaLookingFor',
'value' => $areaihave,
'type' => '',
'compare' => '=',
),
array(
'key' => 'NumberOfBeds',
'value' => $howmanybedsdoiwant,
'type' => '',
'compare' => 'IN',
),
array(
'key' => 'TypeOfHotel',
'value' => $hoteltype,
'type' => '',
'compare' => 'IN',
),
),
'paged' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
); ?>
<?php $query_a = new WP_Query( $args_a ); ?>
<?php else : ?>
<?php
$args_a = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'CurrentLocation',
'value' => $searchm,
'compare' => '=',
),
array(
'key' => 'AreaLookingFor',
'value' => $areaihave,
'type' => '',
'compare' => '=',
),
),
'paged' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
); ?>
<?php $query_a = new WP_Query( $args_a ); ?>
<?php endif; ?>
<?php if ( $query_a->have_posts() ) : ?>
<ul>
<!-- the loop -->
<?php while ( $query_a->have_posts() ) : $query_a->the_post(); ?>
<?php get_template_part( 'template-parts/post/content', 'excerpt' ); ?>
<?php endwhile; ?>
<!-- end of the loop -->
</ul>
<?php next_posts_link( 'Next', $custom_query->max_num_pages );
previous_posts_link( 'Previous' ); ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'No homes matched your criteria' ); ?></p>
<?php endif; ?>