Currently i have 2 categories and 1 custom field
Category = CAT01 and CAT02 / ID's 1 and 2
Custom Field = Test01
What I want is the average of all values entered in my custom field (Test01), but from 1 category.
I'm new to Wordpress, but I got the following:
$wp_query = new WP_Query( array (
'category_id' => '1',
'meta_key' => 'Test01',
)
);
Without the category id it seems to do something, but not what I want.
Can anyone help me out with this, really appreciate the effort :)
I think using WP_Query adds needless overhead to this. I would do a custom SQL query (although you'd have to keep an eye on if WP changes their taxonomy DB structure in the future).
It would look something like this:
global $wpdb;
$term = get_term(1, 'category'); //need the term_taxonomy_id, not always the same as term_id
$sqlQuery = "SELECT AVG(meta_value) FROM $wpdb->postmeta WHERE meta_key = 'Test01' AND post_id IN(SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = '" . $term->term_taxonomy_id . "') ";
$avg = $wpdb->get_var($sqlQuery);
Related
I am trying to query some data onto my page on WordPress, but I am not sure where to actually put my SQL function. It has been driving me crazy for 2 days and have not found out an answer. I've look through my phpadmin, wp-db.php .. Am I missing something here? Could somebody please post the very first steps on getting this started..? I have experience in writing code and SQL, so if I just know where to put my code in I could get started. Thank you so much for your help.
You can use WordPress Query to fetch data from your database . Instead of writing SQL query, you can fetch from $wpdb . query_posts() or WP_Query() are the predefined functions in WordPress . For fetching all pages, you can just use : query_posts('post_type=page'); similarlly posts query_posts('post_type=post');
Other conditions can be specified in the args section , ie for particular page name :
query_posts('post_type=page&post_name=contact');
Thank You
Here is the simple example query:
<?php
global $wpdb;
global $post;
$querystr = "
SELECT DISTINCT wposts.*
FROM $wpdb->posts wposts
LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id
LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb-
>term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb-
>term_relationships.term_taxonomy_id = $wpdb-
>term_taxonomy.term_taxonomy_id)
WHERE wpostmeta.meta_key = 'customDateField'
AND wpostmeta.meta_value >= CURDATE()
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id IN(1,2)
ORDER BY wpostmeta.meta_value ASC
LIMIT 4
";
?>
Use WP_QUERY class for your queries. You can write the code in template files of your theme.
$query = new WP_Query( array( 'post_type' => 'page', 'post__in' => array( 2, 5, 12, 14, 20 ) ) );
Here you will find examples and documentation.
https://codex.wordpress.org/Class_Reference/WP_Query
for custom queries use wpdb class:
https://codex.wordpress.org/Class_Reference/wpdb
// 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
// 2nd Method - Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice )
$results = $GLOBALS['wpdb']->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
I'm having the following problem. I have set up a Wordpress site with WooCommerce to serve a webshop with only books.
I have created some product attributes that are based on taxonomies like 'publisher' and 'author' (as multiple products can share an author or a publisher)
I would like to be able to sort my products not only on the Woocommerce default fields like 'title' and 'price' but also on these taxonomy fields.
Say for example:
order by Author ASC or order by publisher DESC
As far as I have discovered there is no way to do this with Wordpress core functions. Some say this is because it makes no sense to sort by taxonomy fields, but with the above example I can't understand why you don't want to sort by for example author.
I have played around with sortby meta_value, but this is just querying the direct postmeta, not the taxonomies.
I have knowledge of php, so any solutions involving additional code in my functions.php file will do.
I found out a way how to solve this:
https://gist.github.com/jayarnielsen/12f3a586900aa6759639
I slightly modified the code so it equals the way Woocommerce uses to sort by the system fields "title" and "price" which is adding a url query-param named "sortby" a value structured like this: "field"-"direction"
So to sort by a product property called "pa_tax1" ascending you'll need to add to the url: sortby=pa_tax1-asc
add_filter('posts_clauses', 'posts_clauses_with_tax', 10, 2);
function posts_clauses_with_tax( $clauses, $wp_query ) {
global $wpdb;
// Array of taxonomies you want to sort on
// in case of Woocommerce Properties, be sure to add the pa_ prefix
$taxonomies = array('pa_tax1', 'pa_tax2', 'pa_tax3');
// If no orderby query param is found, do nothing
if( !isset($wp_query->query['orderby']) ) {
return $clauses;
}
// Explode the orderby query-param
$orderQuery = explode('-', $wp_query->query['orderby']);
$orderBy = [];
$orderBy['field'] = $orderQuery[0];
$orderBy['direction'] = (isset($orderQuery[1])) ? strtoupper($orderQuery[1]) : 'ASC';
// Only add clauses, if the sortby field is in our array
if( in_array($orderBy['field'], $taxonomies) ) {
$clauses['join'] .= "
LEFT OUTER JOIN {$wpdb->term_relationships} AS rel2 ON {$wpdb->posts}.ID = rel2.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} AS tax2 ON rel2.term_taxonomy_id = tax2.term_taxonomy_id
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
";
$clauses['where'] .= " AND (taxonomy = '".$orderBy['field']."' OR taxonomy IS NULL)";
$clauses['groupby'] = "rel2.object_id";
$clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
$clauses['orderby'] .= ( 'ASC' == strtoupper( $orderBy['direction'] ) ) ? 'ASC' : 'DESC';
return $clauses;
}
else {
return $clauses;
}
}
I am using cpt-archive plugin to generate archive by month in my wordpress post. Here the plugin using this code,
$query = "SELECT YEAR( post_date ) AS `year`,
MONTH(post_date) AS `month`,
count(ID) as posts
FROM $wpdb->posts $join $where
GROUP BY YEAR(post_date),
MONTH(post_date)
ORDER BY post_date DESC $limit";
$arcresults = $wpdb->get_results($query);
Here it's working fine with post_date. I need to customize this to get archived by meta fields. I have two meta keys such as _event_start_date and _event_end_date.
edit
now i am getting all the custom post type months based on the _event_end _date with the following query
$months = $wpdb->get_results("SELECT DISTINCT YEAR(meta_value) AS year, MONTH(meta_value) AS month FROM $wpdb->postmeta WHERE meta_key = '_event_end_date' WHERE meta_value <= now( )ORDER BY meta_value ASC");
but i want only past months only. how to do change this query for getting only archived months.
Why don't you use wp_get_archives?
Something like this
<?php wp_get_archives( array( 'type' => 'monthly', 'meta_value' => array('_event_start_date', '_event_end_date') ) ); ?>
I need to show a list of Wordpress categories only if the category name begins with an "*" (asterisk).
I know I can display the list of categories based on some criteria using the template tags:
<?php wp_list_categories( $args ); ?>
What I don't know how to do is write the if statement that checks to see if the category name starts with an *.
I think, you may try this
global $wpdb;
$query = SELECT GROUP_CONCAT( wp_terms.term_id ) AS IDS FROM wp_term_relationships LEFT JOIN wp_term_taxonomy ON ( wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id ) LEFT JOIN wp_terms ON wp_term_taxonomy.term_taxonomy_id = wp_terms.term_id WHERE wp_term_taxonomy.taxonomy = 'category' AND wp_terms.name LIKE '*%'
$ids = $wpdb->get_var($query);
wp_list_categories("include=$ids");
Example, I have a post's meta_key is 'name', meta_value is 'Jason',
and this meta_id in MySQL is 128
How can I get this meta_value by meta_id ?
The best way to do this is to use WordPress's built-in function, get_metadata_by_mid().
So in your case:
$value = get_metadata_by_mid( 'post', 128 );
I found this which might help you.
It describes How to get the Meta ID by Meta Key, so it is not exactly what you need but quite similar. Maybe all that is required is to modify that query a little.
get_metadata_by_mid( $meta_type, $meta_key ) will work for most situations. It returns an object with all the postmeta data.
$jason = get_metadata_by_mid( 'post', 128 );
echo 'Meta Value = ' . $jason->meta_value;
echo 'Post ID = ' . $jason->post_id;
// Results
Meta Value = Jason
Post ID = 123
If you need to do something a bit more custom such as get stock status of product using the meta id. You can use this.
global $wpdb;
$meta_id = 128;
$postmeta_post_id = $wpdb->get_var( $wpdb->prepare("SELECT post_id FROM {$wpdb->prefix}postmeta WHERE meta_id = %d", $meta_id) );
$stock_status = get_post_meta( $postmeta_post_id, '_stock_status', single );
echo 'Product status: ' . $stock_status;
//results
Product status: outofstock