That code work only set a variable not by form.
function.php
<?php
function title_filter( $where, &$wp_query ) {
global $wpdb;
if ( $search_term = $wp_query->get( 'search_title' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
}
return $where;
}
add_filter( 'posts_where', 'title_filter', 10, 2 );
?>
form.php
<form role="search" method="get" id="form_percorsi" action="<?php bloginfo('url'); ?>/category/percorsi/" style="float:left;margin-right:10px;">
<h1>Search</h1>
<input placeholder="Cerca…" value="" id="search_them" name="search_title" title="Search for:" type="search">
</form>
my query for display items
$search_them = $_GET['search_them'];
$args = array( 'paged' => $paged, 'orderby' => $order_by, 'order' => $order, 'search_title' => $search_them );
if i search a title by form non work...
have a solution?
Related
I'm trying to make the default wp_dropdown_categories select dropdown as a radio input with submit button.
This is on the front end.
<form id="filter-select" class="filter-select" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
<?php wp_dropdown_categories(); ?>
<input type="submit" name="submit" value="view" />
</form>
Then in my functions.php I tried to do this
add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);
function dropdown_filter( $output, $r ) {
$output = preg_replace( '/<option/i', '<input type="radio"', $output );
$output = str_replace( 'class="level-0"', 'name="filter"', $output );
$output = str_replace( "value=\"{$value}\"", "value=\"{$value}\" selected", $output );
return $output;
}
This actually works in swapping out the select dropbox for a radio field. But it does not actually work correctly.
Instead of going to /category/CATEGORYNAME - Like the default select box does.
It goes /?filter=6&submit=view
Any advice is greatly appreciated, thank you.
Try with a custom Walker to output category names instead of IDs.
<div class="radiobuttons">
<?php
$args = array(
'orderby' => 'name',
'hide_title_if_empty' => true,
'title_li' => '',
'walker' => new List_Categories_Radiobuttons
);
wp_list_categories( $args );
?>
</div>
The custom Walker in functions.php:
/**
* Custom Walker to list categories with radio buttons
*/
class List_Categories_Radiobuttons extends Walker_Category {
function start_el(&$output, $category, $depth=0, $args=array()) {
$category_name = esc_attr( $category->name );
$radiobutton = '<input type="radio" name="filtercategory" value="' . $category_name . '">';
$output .= '<div class="radiobutton">' . $radiobutton;
}
function end_el(&$output, $category, $depth=0, $args=array()) {
$output .= "</div>\n";
}
}
Does this point you in the right direction?
I need to create a custom WordPress search form, with multiple text input fields. Each text field should search its corresponding meta key. Frontend would look like this:
Search form:
<form role="search" action="/" method="get" id="searchform">
<input type="text" name="s" placeholder="Name"/>
<input type="text" name="hometown" placeholder="Hometown"/>
<input type="text" name="branch" placeholder="Branch of Service"/>
<input type="text" name="birth" placeholder="Birth Year"/>
<input type="text" name="casualty" placeholder="Casualty Year"/>
<input type="text" name="location" placeholder="Casualty Location">
<input type="hidden" name="post_type" value="veterans" />
<input type="submit" alt="Search" value="Search" />
</form>
The "Name" field should search the post title only. The rest of the input fields would search a specific custom meta key. It would use an "AND" relationship when multiple fields are used.
Is this possible? Here is what I have tried, but it doesn't search if the name ("s") is empty, and it doesn't seem to be affected at all by what I enter into the custom fields for Hometown or Branch.
// register query vars
function sm_register_query_vars( $vars ) {
$vars[] = 'hometown';
$vars[] = 'branch';
return $vars;
}
add_filter( 'query_vars', 'sm_register_query_vars' );
// pre get posts
function sm_pre_get_posts( $query ) {
if ( is_admin() || ! $query->is_main_query() ){
return;
}
if ( !is_post_type_archive( 'veterans' ) ){
return;
}
$meta_query = array();
// add meta_query elements
if( !empty( get_query_var( 'hometown' ) ) ){
$meta_query[] = array( 'key' => 'hometown', 'value' => get_query_var( 'hometown' ), 'compare' => 'LIKE' );
}
if( !empty( get_query_var( 'branch' ) ) ){
$meta_query[] = array( 'key' => 'branch', 'value' => get_query_var( 'branch' ), 'compare' => 'LIKE' );
}
if( count( $meta_query ) > 1 ){
$meta_query['relation'] = 'AND';
}
if( count( $meta_query ) > 0 ){
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'sm_pre_get_posts', 1 );
// the search form (display via shortcode)
function sm_search_form( $args ){
$output = '<form id="smform" action="' . esc_url( home_url() ) . '" method="GET" role="search">';
$output .= '<div class="smtextfield"><input type="text" name="s" placeholder="Name" value="' . get_search_query() . '" /></div>';
$output .= '<div class="smtextfield"><input type="text" name="hometown" placeholder="Hometown" value="' . get_search_query() . '" /></div>';
$output .= '<div class="smtextfield"><input type="text" name="branch" placeholder="Branch" value="' . get_search_query() . '" /></div>';
$output .= '<input type="hidden" name="post_type" value="veterans" />';
$output .= '<p><input type="submit" value="Search" class="button" /></p></form>';
return $output;
}
The above query looks like this when attempting to search:
site.com/?s=john+doe&branch=army&hometown=new+york&post_type=veterans
After checking if there are any terms in your search by something like
if($_GET['myfield'])...
try storing each type of your search in a var and then build a custom query with all the items that are in your search. ie :
<?php
$title=$_GET['name']; // Get the name
$params=[]; // Create an array with all the parameters you've got except the name
function populate_array($term) // Create a function to populate your array
{
if ($_GET[$term]) {
$params[$term] = $_GET[$term];
}
}
populate_array('hometown');
populate_array('branch');
//(...)
$args=array( // Initialize your query
'post_type' => 'my_post_type', // Just set your post type if needed
);
if($title){ // If there is a title add it to the query
$args['title']=$title;
}
if(count($params)>0){. // If there are any params
$meta=array('relation'=>'AND'); // Because you asked for it
foreach($params as $param => $value){
$meta[]=array( // Adding each meta tou your query
'key' => $param, // considering you name your meta as your parameter
'value' => $value,
'compare' => '='
);
}
$args['meta_query']=$meta; // Adding your meta to your main query
}
$query = new WP_Query( $args ); // And now you can request your query with all your parameters
I have not tested this but it should work... Maybe some improvements are needed. Test it and come back to me :)
Hi I would like to add country of origin while adding products and then sort products based on country of origin
Can I achieve this?
Add these functions to your theme's 'functions.php'.
Display & Save the Custom Field in Admin
// display field in admin
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_country_field');
function woocommerce_product_country_field()
{
global $woocommerce, $post;
$countries_obj = new WC_Countries();
$options = $countries_obj->__get('countries');
echo '<div class="product_country_field">';
woocommerce_wp_select(
array(
'id' => '_country_origin',
'label' => __('Country of origin', 'woocommerce'),
'options' => $options,
'desc_tip' => 'true'
)
);
echo '</div>';
}
// save fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_country_fields_save');
function woocommerce_product_country_fields_save($post_id)
{
$woocommerce_country_origin = $_POST['_country_origin'];
if (!empty($woocommerce_country_origin))
update_post_meta($post_id, '_country_origin', esc_attr($woocommerce_country_origin));
}
Sort by Custom Field in Front-End
// sort field
function custom_add_country_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
switch( $orderby_value ) {
case '_country_origin':
$sort_args['orderby'] = 'meta_value';
$sort_args['order'] = 'asc';
$sort_args['meta_key'] = '_country_origin';
break;
case '_country_origin-desc':
$sort_args['orderby'] = 'meta_value';
$sort_args['order'] = 'desc';
$sort_args['meta_key'] = '_country_origin';
break;
}
return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_add_country_ordering_args' );
//change sort dropdown
function custom_add_country_orderby( $sortby ) {
//remove default sorting
unset($sortby["popularity"]);
unset($sortby["rating"]);
unset($sortby["date"]);
unset($sortby["price"]);
unset($sortby["price-desc"]);
$sortby['_country_origin'] = __( 'Sort by Country of origin', 'woocommerce' );
$sortby['_country_origin-desc'] = __( 'Sort by Country of origin descending', 'woocommerce' );
return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_add_country_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_add_country_orderby' );
Please note that the products which has 'Country of origin' will only be displayed while sorting.
Filter by Custom Field in Front-End
Add this if you want filter rather than sort.
//add custom filter
add_action( 'woocommerce_before_shop_loop', 'filter_loop_start' );
function filter_loop_start( $query ){
$countries_obj = new WC_Countries();
$options = $countries_obj->__get('countries');
?>
<form name="product_filter_form" class="woocommerce-filtering" method="get">
<select name="country_origin" class="filterby" onChange="document.product_filter_form.submit();">
<option value="">Filter by Country of origin</option>
<?php foreach ($options as $key => $value) { ?>
<option value="<?php echo $key; ?>"<?php if($_GET['country_origin']==$key) echo ' selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>
<input name="paged" value="1" type="hidden">
</form>
<?php
}
//modify query for filter
add_filter( 'pre_get_posts', 'my_modify_main_query' );
function my_modify_main_query( $query ) {
if( ! isset( $_GET['country_origin'] ) ) return $query;
$meta_query_args = array(
'meta_query' => array(
array(
'key' => '_country_origin',
'value' => sanitize_text_field( $_GET['country_origin'] ),
'compare' => 'LIKE',
)
)
);
$query->set('meta_query', $meta_query_args);
return $query;
}
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 want to create a widget that will be created in wordpress when the shortcode is activated in a post. I tried to get some things to $all and then return it but didnt work out. I want to do it without using any plugins.
function movie($atts) {
class wpb_widget extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget',
// Widget name will appear in UI
__('WPBeginner Widget', 'wpb_widget_domain'),
// Widget description
array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), )
);
}
// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
global $wpdb;
$b = shortcode_atts(array(
'name' => 'Deadpool',
), $atts);
$vypis = $wpdb->get_row ("SELECT * FROM hodnoceni WHERE nazev = '" . $atts['name'] . "'", ARRAY_A);
$all = $args['before_widget'];
if ( ! empty( $vypis['nazev'] ) )
// This is where you run the code and display the output
$all .= $args['before_title'] . $title . $args['after_title'] . '<p style="margin:0px;">' . $vypis['rok'] . '<br>' . $vypis['delka'] . ' min</p><div class="my-image"><img src="' . $vypis['src'] . '" height="130" alt="' . $vypis['nazev'] . '"> </div> <div class="my-content">' . $vypis['clanek'] . '</div> </div>';
$all .= $args['after_widget'];
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class wpb_widget ends here
return $all;
}
function wpb_load_widget() {
register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );
function register_shortcodes(){
add_shortcode('bacon', 'bacon_function');
add_shortcode('movie_form', 'movie_form');
add_shortcode('movie', 'movie');
}
add_action( 'init', 'register_shortcodes');
For your widget class "wpb_widget" you can use this code:
<?php add_shortcode( 'show_movie', 'movie_shortcode' );
function movie_shortcode( $atts ) {
// Configure defaults and extract the attributes into variables
extract( shortcode_atts(
array(
'type' => 'wpb_widget'
),
$atts
));
$args = array( //optional markup:
'before_widget' => '<div class="box widget scheme-' . $scheme . ' ">',
'after_widget' => '</div>',
'before_title' => '<div class="widget-title">',
'after_title' => '</div>',
);
ob_start();
the_widget( $type, $atts, $args );
$output = ob_get_clean();
return $output;
}
and then use this code
[show_movie]
to run the widget.