This is the custom query I'm running to display post from 2 categories.
I have installed WordPress Plugin "Featured Post" but the featured post is not excluding from the displayed list.
<?php
$category_id = get_cat_ID($strReports || $strInsights);
$custom_query = new WP_Query( 'cat=' .$category_id. '&featured=no&posts_per_page=6&order=desc' );
while($custom_query->have_posts()) : $custom_query->the_post();
?>
HTML Content Here
<?php endwhile; ?>
<?php wp_reset_query(); // reset the query ?>
Looking through "Featured Post" you can see that it just test against yes value. What feature=yes does is just check a meta field, so I think you can do the reverse way to achieve what you want, like this:
$args = array(
'cat' => $category_id,
'posts_per_page' => 6,
'order' => 'DESC', // since order default value is already DESC you can remove this line
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_is_featured',
'value' => 'yes',
'compare' => '!=',
),
array(
'key' => '_is_featured',
'value' => 'foo', // Prior to WP 3.9 we have to provide any non-empty string here
'compare' => 'NOT EXISTS',
),
) ,
);
$custom_query = new WP_Query($args);
Hope it helps!
your'e running an invalid argument on get_cat_ID.
should be something like this:
<?php
$cat_names = array('Cat_Name1', 'Cat_Name2');
$category_Name = implode(',', $cat_names);
$args = array(
'category_name' => $category_Name,
'posts_per_page' => 6,
'meta_query' => array(
array(
'key' => 'featured',
'value' => true,
'compare' => '!=',
),
),
);
$custom_query = new WP_Query( $args );
while($custom_query->have_posts()) : $custom_query->the_post();
?>
<?php the_title();?>
<?php endwhile; ?>
<?php wp_reset_query(); // reset the query ?>
create your custom query and add filter.
function SearchFilter($query){
$query=" SELECT Distinct SQL_CALC_FOUND_ROWS p.* FROM `$wpdb->posts` as p left join `$wpdb->postmeta` as m on m.post_id=p.ID "
." left join `$wpdb->term_relationships` as r ON (p.ID = r.object_id) "
." left join `$wpdb->term_taxonomy` as x ON (x.term_taxonomy_id = r.term_taxonomy_id) "
." left join `$wpdb->terms` as t ON (t.term_id = x.term_id AND x.taxonomy='category') "
." WHERE p.post_type = 'post' AND p.post_status = 'publish' "
." AND t.term_id='$idcategorie' "
return $query;
}
add_filter( 'posts_request', 'SearchFilter' );
Related
I have multiple products, whose sku names are like AL-888, A-2323, AL-etrere.
I want to find products on basis of this sku name's first two words.
I am creating shortcode for this purpose, but can't able to get it work.
Any help should be appreciated.
Code for this shortcode:
function all_state_list_function(){
$name = $_GET['sku']; //this give sku value from url like Al:2323
echo $name;
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'DESC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'free_form',
'value' => '1',
),
array(
'key' => '_sku',
'value' => $name.'-%',
'compare' => 'LIKE',
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$product_id = get_the_ID();
echo $product_id;
endwhile;
wp_reset_query();
}
add_shortcode( 'all_state_list_shortcode', 'all_state_list_function' );
Based on your first version code that had an SQL query, here is the correct way to get product IDs from first SKU characters value using GET method from an URL:
add_shortcode( 'all_state_list_shortcode', 'all_state_list_function' );
function all_state_list_function(){
if ( isset($_GET['sku']) && ! empty($_GET['sku']) ) {
ob_start();
$sku = esc_attr( $_GET['sku'] ) .'%';
global $wpdb;
$results = $wpdb->get_col( "
SELECT p.ID FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type LIKE 'product' AND p.post_status LIKE 'publish'
AND meta_key LIKE '_sku' AND meta_value LIKE '$sku'
" );
if( count($results) > 0 ) {
echo implode(',', $results);
} else {
echo 'Nothing found';
}
return ob_get_clean();
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I have very annoying problem with WP_query and repeater . I try display something if $_GET is not equal to value in my DB. But when compare => NOT LIKE it now working correctly.
Here is my code:
function wyszukiwanie_trasy()
{
echo '<form action="" method="get">';
echo '<input type="text" name="od" placeholder="Stacja początkowa">';
echo '<input type="text" name="do" placeholder="Stacja końcowa">';
echo '<input type="date" name="data">';
echo '<input type="submit" value="Wyszukaj">';
echo '</form>';
$loop = new WP_Query(array('meta_query' => array(
'relation' => 'AND',
array(
'key' => 'date_%_daty_wykluczone',
'value' => str_replace("-","",$_GET['data'],$i),
'compare' => 'NOT LIKE'),
),
array(
'value' => $_GET['od'],
),
array(
'value' => $_GET['do'],
),'post_type' => 'trasy', 'posts_per_page' => -1));
while ($loop->have_posts()) : $loop->the_post();
$id = get_the_ID();
if($_GET['od'] && $_GET['do'] && $_GET['data'] && $_GET['od']!=$_GET['do'])
{
if( have_rows('location') ):
// loop through the rows of data
while ( have_rows('location') ) : the_row();
// display a sub field value
?>
<span style="font-weight: bold"><?php the_sub_field('lokacja');?></span>
<?php
echo ' ';
endwhile;
echo '<br />';
else :
echo 'Brak połączeń';
endif;
}
echo $loop->request;
endwhile; wp_reset_query();
}
Here is my SQL request:
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( ( wp_postmeta.meta_key LIKE 'date_%_daty_wykluczone' AND wp_postmeta.meta_value LIKE '%20180715%' ) ) AND wp_posts.post_type = 'trasy' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC
Imo is is something wrong with 'key' => 'date_%_daty_wykluczone', in my DB that meta keys looks like: date_0_daty_wykluczone date_1_daty_wykluczone, cause when i change this 'key' => 'date_%_daty_wykluczone', to 'key' => 'date_1_daty_wykluczone', 'NOT LIKE' works correctly
Thanks in advance :)
Try this code structure,
Using the "Relation" for the Meta Query, you can select multiple Meta Keys. You can change the "Compare" to any of the operations available for that function. (From the Codex) compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' and 'NOT EXISTS'. Default value is '='.
// WP_Query arguments
$args = array (
'post_type' => 'your-post-type',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => 'Red',
'compare' => 'LIKE',
),
array(
'key' => 'color',
'value' => 'Plain',
'compare' => 'Like'
),
),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
Meta_query compare operator explanation
The first several work about like you would expect:
= equals
!= does not equal
> greater than
>= greater than or equal to
< less than
<= less than or equal to
LIKE and NOT LIKE are SQL operators that let you add in wild-card symbols, so you could have a meta query that looks like this:
array(
'key' => 'name',
'value' => 'Pat',
'compare' => 'LIKE'
)
This would return all posts where the meta value "name" has the string "Pat". In this case, "Pat" "Patricia" and "Patrick" would all be returned back to you. There's a non-WordPress tutorial explanation here
I have this code, its working good, but its gets posts from all categories. I need to get posts only from category ID 2. I tried to add "AND term_taxonomy_id = 2" to my code, but this didint work. Can somebody help me with this, my code:
<?php //loops all posts
$my_query = $wpdb->get_results
("SELECT * FROM `{$table_prefix}posts`, {$table_prefix}postmeta
WHERE {$table_prefix}posts.post_status = 'publish'
AND {$table_prefix}posts.id = {$table_prefix}postmeta.post_id
AND {$table_prefix}postmeta.`meta_key` = 'wpcf-data-nuo' ORDER BY if({$table_prefix}postmeta.`meta_value` = '' or {$table_prefix}postmeta.`meta_value` is null,1,0), {$table_prefix}postmeta.`meta_value` ASC LIMIT 12");
foreach($my_query as $post) {
setup_postdata($post);
?>
Please follow below code, Hope! its working
You can define the meta key for orderby parameter using the old method (I tested on WP 3.1.1)...
query_posts(
array( 'post_type' => 'services',
'order' => 'ASC',
'meta_key' => 'some_key',
'orderby' => 'meta_value', //or 'meta_value_num'
'meta_query' => array(
array('key' => 'order_in_archive',
'value' => 'some_value'
)
)
)
);
OR
For me, I wanted to order by a numeric field and I had to use 'type' => 'NUMERIC' inside the meta query.
This issue in general is cleared up in WordPress 4.2 by using named queries. e.g.
$args = array(
'post_type' => 'services',
'orderby' => 'order_clause',
'meta_query' => array(
'order_clause' => array(
'key' => 'order_in_archive',
'value' => 'some_value',
'type' => 'NUMERIC' // unless the field is not a number
)));
Reference link for set the meta value in query: https://rudrastyh.com/wordpress/meta_query.html
You can do it by WP_QUERY instead writing custom Query.
The query to get the results and then your custom sort order by altering the WP_QUERY if default order parameters not work as expected.
$args = array(
'post_type' => 'post',
'posts_per_page' => 8,
'cat' => 2,
'meta_key' => 'wpcf-data-nuo',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
add_filter('posts_orderby', 'filter_query');
$q = new WP_Query($args);
remove_filter('posts_orderby', 'filter_query');
function filter_query( $orderby_statement ) {
global $table_prefix;
$orderby_statement .= " if({$table_prefix}postmeta.`meta_value` = '' ";
$orderby_statement .= " or {$table_prefix}postmeta.`meta_value` is null,1,0), {$table_prefix}postmeta.`meta_value`";
return $orderby_statement;
}
Note: Do not remove spaces from $orderby_statement .= because it require spaces while running query.
If it still doesn't work, then add var_dump($orderby_statement); before return $orderby_statement; then copy the SQL and add it in your question so it will help us to understand what is the issue.
Ive written a query that searches for all posts that have X as a meta/custom field value.
// PSV National Query
if ($_POST['vehicleType'] == 'psv' && $_POST['coverageRegion'] == 'national' ) {
$customkey = 'vehicleType';
$customvalue = $_POST['vehicleType'];
$customkey1 = 'coverageRegion';
$customvalue1 = $_POST['coverageRegion'];
$customkey2 = 'locationType';
$customvalue2 = $_POST['locationType'];
global $wpdb;
$my_posts = $wpdb->get_results("
SELECT $wpdb->posts.*
FROM $wpdb->posts, $wpdb->postmeta, $wpdb->postmeta AS mt1
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND $wpdb->postmeta.meta_key = '$customkey'
AND $wpdb->postmeta.meta_value = '$customvalue'
AND mt1.meta_key = '$customkey1'
AND mt1.meta_value = '$customvalue1'
AND mt2.meta_key = '$customkey2'
AND mt2.meta_value = '$customvalue2'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
ORDER BY $wpdb->posts.post_date DESC
");
$args = array(
'meta_query' => array(
array(
'key' => $customkey,
'value' => $customvalue,
'compare' => '='
),
array(
'key' => $customkey1,
'value' => $customvalue1,
'compare' => '='
),
array(
'key' => $customkey2,
'value' => $customvalue2,
'compare' => '='
)
)
);
$query = new WP_Query( $args );
foreach ($query as $post) :
setup_postdata($post);
echo '<div><a href="';
the_permalink();
echo '"></div>';
the_title();
endforeach;
}
Now for my post I have 1 value for each meta key and this works fine, I want to however have multiple values.
For example...
"gas, electricity, water"
When I add multiple values however the query returns null, I presumer its because im saying if...
postmeta.meta_value = '$customvalue'
Can anybody give me advice on where im going wrong?
Why don't you use the built in WP QUERY, it supports meta field array operators.
for example:
$query = new WP_Query( array(
'meta_key' => 'color',
'meta_value' => 'blue',
'meta_compare' => '!='
));
Ref: http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
If you are using multiple matches in a query's where clause you should use the IN variant istead of the =.
The only row I see in your query where you use $customvalue is here
AND $wpdb->postmeta.meta_value = '$customvalue'
You should change the = to IN and seperate the values with a , and quotes ' ' like this for example
AND $wpdb->postmeta.meta_value IN ('gas','electricity','water')
I ditched the $customvalue in the above code to make the point of the seperator of the IN value.
Hopefully this puts you on the right track.
I'm trying to filter my posts to only show the ones with that have a custom value for the field "Model" while sorting the posts by another custom field called "Price."
Here's the function I'm using (not working):
<?php
global $query_string;
query_posts( $query_string . "&meta_value=Model&orderby=meta_value&meta_key=Price&order=ASC");
?>
This function only shows Models, yet doesn't sort the posts by Price. If i add &meta_value=Model after order=ASC it sorts by Price but shows all posts, and not just Models.
Have you looked at http://codex.wordpress.org/Class_Reference/WP_Query
Specifically this section:
Multiple Custom Field Handling:
Display posts from several custom field:
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'NOT LIKE'
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);
$query = new WP_Query( $args );
did you try and array?
$args = array(
'meta_value' => array('Model','Price')
);
query_posts($args);
I know this is an old question, but I needed the answer today and couldn't find it anywhere. I found the question and then created an answer (shown below):
<?php
$sql = "
SELECT ID, meta1.meta_value, meta2.meta_value from $wpdb->posts p
JOIN $wpdb->postmeta meta1 ON meta1.post_id = p.ID
JOIN $wpdb->postmeta meta2 ON meta2.post_id = p.ID
WHERE p.post_status = 'publish'
AND p.post_type = 'post'
AND meta1.meta_key = 'Model'
AND meta2.meta_key = 'Price'
ORDER BY meta2.meta_value DESC
";
$posts_with_meta = $wpdb->get_col($sql);
$my_query = new WP_Query();
foreach ($posts_with_meta as $p) {
$post = get_post(intval($p));
setup_postdata($post);
print_r($post);
}
?>