What I am trying to do is query a WordPress custom post type using meta keys from a search form. The search form takes user inputs and show the results based on the matching criteria, Some of the form's fields might be blank, so I need to make sure I don't pass any blank value to the query argument. I need to use if within the arguments array.
I'll be grateful for any type of help.
This is the code I am using, but getting an error message.
Parse error: syntax error, unexpected T_IF, expecting ')'
Here is my code:
if (isset($POST['stock']) && !empty($POST['stock'])) {
$stock = $POST['stock'];
}
if (isset($POST['mineral']) && !empty($POST['mineral'])) {
$mineral = $POST['mineral'];
}
if (isset($POST['species']) && !empty($POST['species'])) {
$species = $POST['species'];
}
if (isset($POST['color']) && !empty($POST['color'])) {
$color = $POST['color'];
}
if (isset($POST['chemicalclass']) && !empty($POST['chemicalclass'])) {
$chemicalclass = $POST['chemicalclass'];
}
if (isset($POST['locality']) && !empty($POST['locality'])) {
$locality = $POST['locality'];
}
if (isset($POST['description']) && !empty($POST['description'])) {
$description = $POST['description'];
}
if (isset($POST['size']) && !empty($POST['size'])) {
$size = $POST['size'];
}
if (isset($POST['pricegt'])) {
$pricegt = $POST['pricegt'];
} else {
$pricegt = 0;
}
if (isset($POST['pricelt'])) {
$pricelt = $POST['pricelt'];
} else {
$pricelt = 999999;
}
$args = array(
'post_type' => 'products',
'productspecies' => $species,
'localities' => $locality,
'meta_query' => array(
//'relation' => 'OR',
array(
'key' => '_price',
'value' => array( $pricegt, $pricelt ),
'compare' => 'BETWEEN',
'type' => 'numeric',
),
if ($mineral) {
array(
'key' => '_components',
'value' => $mineral,
),
}
if ($stock) {
array(
'key' => '_lotnum',
'value' => $stock,
),
}
if ($color) {
array(
'key' => '_color',
'value' => $color,
),
}
if ($description) {
array(
'key' => '_smalldesc',
'value' => $description,
'compare' => 'LIKE',
),
}
if ($size) {
array(
'key' => '_size',
'value' => $size,
),
}
if ($chemicalclass) {
array(
'key' => '_chemicalclass',
'valeu' => $chemicalclass,
),
}
),
);
?>
<?php $query = new WP_Query( $args ); ?>
<div class="postcount">We Found A Total Of <span><?php echo $query->post_count;?></span> Items Maching Your Search</div>
<?php if ( $query->have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
What I am doing wrong?
You are trying to pass if statements as arguments to the array() function. PHP does not allow that. One thing you can do is build the array without the optional parts and then add them later if necessary:
if ($stock) {
$args['metaquery'][] = array(
'key' => '_lotnum',
'value' => $stock
);
}
You can't insert instructions in the array initialization code.
Do it this way:
$args = array();
if (something){
$args['metaquery'][] = array(contentsOfTheInnerArray);
}
if (something2){
$args['metaquery'][] = array(contentsOfTheInnerArray2);
}
Not completely sure if this works (in php that is) but you can do something like this:
$array = array(
'price' => isset($POST['pricegt']) ? $POST['pricegt'] : 0,
...
);
Related
Scenario:
Variable product has attribute color, term is 'yellow'
Variation with yellow term is disabled
Customer filters product by color 'yellow'
Parent product is displayed even if variation which uses the color 'yellow' is not enabled
Note: Query should contain simple and variation product types.
The query is being called by ajax function, I'm not sure how to use filters if its possible.
The query:
add_action('wp_ajax_getProducts', 'getProducts');
add_action('wp_ajax_nopriv_getProducts', 'getProducts');
function getProducts(){
$input = [
'currentTerm' => $_POST['currentTerm'],
'searchTerms' => $_POST['searchTerms'],
'page' => $_POST['page'],
'color' => $_POST['color'],
'sortBy' => $_POST['sortBy'],
'sortDirection' => $_POST['sortDirection'],
'beltWidth' => $_POST['beltWidth'],
];
// args init
$args = array(
'post_type' => 'product',
'posts_per_page' => 12,
'post_status' => 'publish',
'lang' => pll_current_language()
);
$args['meta_query'] = array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock'
),
);
$args['tax_query'] = array(
'relation' => 'AND',
);
// 0. Search
if( isset() ) {
$sargs = array(
's' => $input['searchquery'],
);
$args = array_merge($sargs, $args);
}
// 1. Terms
if( isset($input['currentTerm']) ) {
$cat_tax = array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $input['currentTerm'],
);
array_push($args['tax_query'], $cat_tax);
}
// 2. Page
if( isset($input['page']) ) {
$args['paged'] = $input['page'];
}
// 3. color
if( isset($input['color']) && $input['color'] != 'clear') {
$color_tax = array(
'taxonomy' => 'pa_color',
'field' => 'slug',
'terms' => $input['color'],
'operator' => 'IN'
);
array_push($args['tax_query'], $color_tax);
}
// 4. sort
if ( isset($input['sortBy']) ) {
if ( $input['sortBy'] == 'price' ) {
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = '_price';
} elseif ( $input['sortBy'] == 'name' ) {
$args['orderby'] = 'title';
} else {
$args['orderby'] = 'date';
}
}
if ( isset($input['sortDirection'])) {
if ( $_POST['sortDirection'] == 'asc') {
$args['order'] = 'asc';
} else {
$args['order'] = 'desc';
}
}
// query
$wp_query = new WP_Query( $args );
...
echo json_encode($products);
...
}
The query works fine, and I've found the way to clear results, by filtering the results; but it returns uneven number of products per page, which is not very user friendly.
The solution is to do something like code below within the query arguments, not inside the results loop.
if( isset($input['color']) && $input['color'] != 'clear') {
if ($product['terms']) {
foreach($product['terms'] as $item) {
if ((string) $item['slug'] == $input['color']) {
array_push($products, $product);
}
}
}
}
Basically, I want to check a post if it's in a specific category but for the life of me, I'm doing something wrong. Here's the current code
$post_catz = wp_get_post_categories( $this->post->ID );
$catz = array();
foreach($post_catz as $c){
$cat = get_category( $c );
$catz[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
if ($catz['slug'] = 'featured') {
$colorslist = 'colorlistingfeat';
}
}
$colorslist is a variable that I want to change, if the post is from that specific category.
Your code having a bug in checking the array. Try this instead.
<?php
$post_catz = wp_get_post_categories(get_the_ID());
$catz = array();
foreach($post_catz as $c){
$cat = get_category( $c );
$catz[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
}
foreach($catz as $cs){
if($cs['slug'] == 'featured') {
$colorslist = 'colorlistingfeat';
}
}
echo $colorslist;
?>
But ensure that $this->post->ID returning post ID.
if ($catz['slug'] = 'featured') { $colorslist = 'colorlistingfeat'; }
For comparison operators you have to use == not =
http://php.net/manual/en/language.operators.comparison.php
Hope this help.
I believe this is because your code $catz[] = array( 'name' => $cat->name, 'slug' => $cat->slug );. Notice $catz[] is an array variable.. so you should get the slug as $catz[0]['slug] or else the $catz will just return Null value. Much better to edit your code as $catz = array( 'name' => $cat->name, 'slug' => $cat->slug );
And also notice your if statement. should be if( cond == cond )
In my below code I am trying to check whether the $query['skill'] value is contained in $c_skills. However it keeps failing. When I use the actual string that I am looking for, e.g. "test" then it functions as intended. My only thought is perhaps $query['skill'] doesn't return as a string, but I can't do a var_dump to find out since I am using wordpress and I am changing code to effect ajax query.
global $user_ID;
$query = $_REQUEST['query'];
if (isset($_REQUEST['query']['skill'])) {
if (isset($query['skill']) && $query['skill'] != '') {
global $wp_query, $ae_post_factory, $post, $current_user;
$post_object = $ae_post_factory->get(PROFILE);
$profile_id = get_user_meta( $user_ID, 'user_profile_id', true);
$profile = array('id' => 0, 'ID' => 0);
if($profile_id) {
$profile_post = get_post( $profile_id );
if($profile_post && !is_wp_error( $profile_post )){
$profile = $post_object->convert($profile_post);
}
}
$current_skills = get_the_terms( $profile, 'skill' );
if (!empty($current_skills)) {
$c_skills = array();
foreach ($current_skills as $key => $value) {
$c_skills[] = $value->name;
};
if(in_array( $query['skill'], $c_skills )) {
$query_args['tax_query'] = array(
'skill' => array(
'taxonomy' => 'skill',
'terms' => 'test',
'field' => 'slug'
)
);
}
}
I think your problem come from $query_args['tax_query'].
For me, the Key (skill) has nothing to do here.
Try to make it simple with
$query_args['tax_query'] = array(
array(
'taxonomy' => 'skill',
'terms' => 'test',
'field' => 'slug'
)
);
The place you use for skill between the two array is intended to be use for relation if you want to query more than one taxonomy.
Hope it works after this.
Alright guys, I'm in way over my head.
I'm trying to build a filter for a custom post type, 'Villas'. These villas have multiple custom fields, these custom fields exist in a group named 'features'.
I've build a search / filter form that POST's the data, which I'm then able to capture using a $_GET request.
The data I'm sending includes:
- Region, type, style select fields;
- Sea view, Sea access, Swimming pool, Reform project checkboxes;
- Price input field
What I'm trying to accomplish is get a query going that filters all 'Villas' using the form values. After extensive googling I found it is possible to loop through custom post_type's with custom fields by using meta_key's. Basicly what I'm trying to do is:
$propertyPrice = $_GET['price'];
$propertyRegion = $_GET['region'];
$propertyType = $_GET['type'];
$propertyStyle = $_GET['style'];
$hasSeaview = $_GET['seaview'];
$hasSeaAccess = $_GET['sea-access'];
$hasSwimmingPool = $_GET['swimming-pool'];
$hasReformProject = $_GET['reform-project'];
if( isset($propertyPrice) || isset($propertyRegion || isset($propertyType)) || isset($propertyStyle) || isset($hasSeaview) || isset($hasSeaAccess) || isset($hasSwimmingPool) || isset($hasReformProject)) {
$args = array(
'meta_query' => array(
'relation' => 'OR'
array(
'key' => 'property-price',
'value' => $propertyPrice,
),
array(
'key' => 'property-region',
'value' => $propertyRegion,
),
array(
'key' => 'property-type',
'value' => $propertyType,
),
etc......
)
);
}
However, I cannot for the life of me figure out how to filter through the posts with variable meta values, send from the form.
If anyone could point me in the right direction, it would be extremely appreciated.
To give you an idea, this is what the filter looks like:
Custom post type filter
EDIT
After xphan's suggestion I edited my code like so, however the var_dump returns nothing even though the _GET's are filled correctly.
<?php
$propertyPrice = $_GET['price'];
$propertyRegion = $_GET['region'];
if($propertyRegion === 'all') { $propertyRegion = array('ibiza-city', 'southwest', 'north', 'east', 'center'); }
$propertyType = $_GET['type'];
if($propertyType === 'all') { $propertyType = array('villa', 'apartment', 'plot'); }
$propertyStyle = $_GET['style'];
if($propertyStyle === 'all') { $propertyStyle = array('rustic', 'modern'); }
$hasSeaview = $_GET['seaview'];
if( isset($hasSeaview) ) { $hasSeaview = 1; }
$hasSeaAccess = $_GET['sea-access'];
if( isset($hasSeaAccess) ) { $hasSeaAccess = 1; }
$hasSwimmingPool = $_GET['swimming-pool'];
if( isset($hasSwimmingPool) ) { $hasSwimmingPool = 1; }
$hasReformProject = $_GET['reform-project'];
if( isset($hasReformProject) ) { $hasReformProject = 1; }
?>
<?php
echo $propertyRegion .'<br>';
echo $propertyType .'<br>';
echo $propertyStyle .'<br>';
echo $propertyPrice .'<br>';
?>
<?php if( isset($propertyPrice) || isset($propertyRegion) || isset($propertyType) || isset($propertyStyle) || isset($hasSeaview) || isset($hasSeaAccess) || isset($hasSwimmingPool) || isset($hasReformProject)) {
$args = array(
'post_type' => 'villas',
'meta_query' => array(
array(
'key' => 'property-price',
'value' => $propertyPrice
),
array(
'key' => 'property-region',
'value' => $propertyRegion,
'compare' => 'IN'
),
array(
'key' => 'property-type',
'value' => $propertyType,
'compare' => 'IN'
),
array(
'key' => 'property-style',
'value' => $propertyStyle,
'compare' => 'IN'
),
array(
'key' => 'sea-view',
'value' => $hasSeaview
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
<?php var_dump($the_query->the_post()); ?>
<?php
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
}
You can pass an array of values to the value attribute of your meta_query. Further you can specify the relation the target meta values must have with your provided values.
Here is an example where you search for a post that has (besides the matching propert-price meta value) either value1 or value2 saved in the meta field property-region
$args = array(
'meta_query' => array(
'relation' => 'OR'
array(
'key' => 'property-price',
'value' => $propertyPrice,
),
array(
'key' => 'property-region',
'value' => array('value1', 'value2'),
'compare' => 'IN'
)
)
);
I have been struggling for a couple days with trying to use the data in a custom field to return posts. Here is my function that I have in functions.php. I am able to return my posts, except that they aren't limited to the ones defined in the $json variable. I can decode the json and return the array...but I can't seem to convert it in such a way that it fills in my array properly for the "posts__in" in the $dishes_arg.
Can anyone help me identify what I am doing wrong?
add_action ('woo_loop_before', 'hgf_home_menu');
function hgf_home_menu () {
if (is_home() || is_front_page()) {
wp_reset_query();
global $posts;
$menu_args = array(
'post_type'=>'single_menu',
'posts_per_page' => 1,
'meta_key' => 'orderby_date',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'orderby_date', // Order-By Date field is upcoming
'value' => date("Y-m-d"),
'compare' => '>='
),
array(
'key' => 'orderby_date', // Order-By Date isn't more than two weeks out
'value' => date("Y-m-d", strtotime( "+2 weeks")),
'compare' => '<='
)
),
);
// Get menu that meets criteria
$menus = new WP_Query( $menu_args );
// Show menu that meets criteria
if ( $menus->have_posts() ) {
while ( $menus->have_posts() ) {
$menus->the_post();
}
wp_reset_postdata();
// Get the menu's product/post listing
$json = '[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]';
$array = json_decode($json);
$include = array();
foreach($array as $a) {
$include[] = $a->ID;
}
$args = array(
'posts_per_page' => -1,
'include' => $include);
$posts = get_posts($args);
$dish_args = array(
'post_type' => 'product',
'post__in' => $posts,
);
// Get dishes in menu listing
$dishes = get_posts( $dish_args );
if ($dishes) {
foreach ($dishes as $dish) {
}
}
} else { // no posts found }
/* Restore original Post Data */
wp_reset_postdata();
}
}
You jSon property is id not ID
$include[] = $a->ID;
Should be
$include[] = $a->ID;
Where/why is there jSon here? Is this coming from something else.
Otherwise that could just be a simple delimitated list or even a normal PHP array.
I figured it out...turns out I just had to cut out a bunch of code that was getting in the way: $include = array() ... $args = array() ... $dish_args = array() ... $dishes = get_posts(). Here is the corrected portion:
$json = '[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]';
$dishes = json_decode($json);
if ($dishes) {
foreach ($dishes as $dish) {
// Echo titles and permalinks
}
}