WordPress Custom Query WHERE? - wordpress

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 );

Related

Wordpress - Copy media library or categorize?

I have a plugin in mind for Wordpress (that I'm aiming to create) that bascially are going to use the same features of the media - library (uploading / viewing / setting descriptions etc on images).
Is there a way of "copying" the media library and then use it/modifiy it as you wish?
Background:
I want to categories these photos for different customers (that the owner of the site uploads). I believe the built-in media library should be used for site-specific photos (like logos, product photos etc). I don't want mix built-in "media-library" with specific customers photos.
Guidelines
Maybe there's a better approach. (Is it better to create categories in the media-categories for each customer?) If there is, please tell me. I'm looking for guidelines - not a solution.
Solution 1:
First query posts, and then for each one of them use something like this code:
$images = get_children( array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1
) );
foreach ( (array) $images as $image ) {
print wp_get_attachment_url( $image->ID );
}
I don't like this solution because it will generate many SQL queries.
Solution 2:
Write your own SQL query which will select all images at once. It should look something like this:
// change this to your custom post type, attachment in your case.
$post_type = 'attachment';
global $wpdb;
$where = get_posts_by_author_sql( $post_type );
$query = "SELECT * FROM $wpdb->posts p where p.post_type = 'attachment' AND (p.post_mime_type LIKE 'image/%') AND (p.post_status = 'inherit') AND p.post_parent IN (SELECT $wpdb->posts.ID FROM $wpdb->posts {$where} ) ORDER BY p.post_date DESC";
$results = $wpdb->get_results( $query );
if ( $results ) {
foreach ( (array) $results as $image ) {
print wp_get_attachment_url( $image->ID );
}
}
The way I would build that plugin, is creating a custom post type, similar to the media upload type, and then modify it as you wish (adding a category for example).
I like the idea of the plugin, so let me you know then you finish, Good luck.
Edit: If you are actually want to copy all the image files to another directory you could do something like this using :
$source = wp_upload_dir(); // get WordPress upload directory
$dest= "wp-content/My-new-Directory"; // where you would like to copy
mkdir($dest, 0755);
foreach (
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $item
) {
if ($item->isDir()) {
mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
} else {
copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
Theoretically, you could copy the whole media gallery.
Media gallery (in admin panel) is basically a post type archive. Post type in question being attachment.
By defining your custom post type, you could add all the action, display and functionality hooks needed to replicate the attachment functionality.
If you want to categorize your attachment either by using a hierarchical or non hiearchical taxonomy you could register a custom taxonomy for the attachment post type.
Both ways are semi-complex, and are perhaps unneeded. Would you be so kind to describe your usage scenario in more detail, so I could help you better.

wordpress get post_id where meta_value =

I am trying to query the wordpress post_meta table by meta_value.
I would like to output all post_id's where the meta_value is = to _parent_product. Here is my code:
$posts = $wpdb->get_results("SELECT *, FROM $table WHERE meta_key='_parent_product' ");
foreach ( $posts as $post ){
$id = $post->post_id;
echo $id;
}
The above outputs nothing and im not quite sure why? Can anyone see anything wrong?
As stated in the comment,
There is a comma (,) behind SELECT *,. Therefor the given SQL is invalid and will fail to retrieve any results.

Wordpress - Order Custom Post Type By Custom Taxonomy

I have the following piece of code:
$args = array( 'post_status'=>"publish",
'posts_per_page' => 20,
'post_type'=>"equipment",
'orderby'=>"title",
'order'=>"ASC");
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
This all works fine but what I would like to do is to be able to specify the order of the posts by the category within the custom taxonomy.
Is this possible?
Have been trying to use the category array but with no luck.
Just to give all the information, my custom taxonomy is called 'equipcats' and under here I have several categories, e.g. 'Visuals', 'Stage', 'Lighting', 'Sound'...
As it currently stands the order of the posts will be shown as alphabetically ascending so the order will be:
Lighting
Sound
Stage
Visuals
What I would like to do is to be able to have strict control over this ordering, so for example:
Stage
Visuals
Lighting
Sound
All help is greatly appreciated.
Basically, the code below sets up filters to add a "join" clause to include the terms tables in the query, to restrict it to categories, and then to sort by the category ID. And then it re-queries, using the existing query variables (such as page number, etc.).
<?php add_filter('posts_join', create_function('$a', 'global $wpdb; return $a . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";'));
add_filter('posts_where', create_function('$a', 'global $wpdb; return $a . " AND $wpdb->term_taxonomy.taxonomy = \'category\'";'));
add_filter('posts_orderby', create_function('$a','global $wpdb; return "$wpdb->term_taxonomy.term_id DESC";'));
query_posts('');
?>
<?php while ( have_posts() ) : the_post() ?>

Wordpress WP_QUERY with Category and Meta_key

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);

wordpress get_terms function not working in my plugin

hello again from a far far away place.
you know i`m trying to list all of terms from a custom taxonomy , when i use below code :
$terms = get_terms($taxonomy , 'hide_empty=0');
print_r($terms);
$count = count($terms);
if ( $count > 0 ){
echo "<ul>";
foreach ( $terms as $term ) {
echo "<li>" . $term->name . "</li>";
}
echo "</ul>";
wp return a crazy error that says : INVALID TAXONOMY :
WP_Error Object
(
[errors] => Array
(
[invalid_taxonomy] => Array
(
[0] => Invalid Taxonomy
)
)
[error_data] => Array
(
)
)
it is very interesting that you know , when i use above code in single.php, i have not see any error and it works fine.
somebody please help me !
Resolved
I am trying to use:
get_terms( 'event_category', array('hide_empty'=>FALSE) );
to use my admin theme option and face same problem when using:
add_action( 'init', 'register_features_taxonomy_event_category' );
But now its resolved using:
add_action( 'after_setup_theme', 'register_features_taxonomy_event_category' );
get_terms return invalid taxonomy error because:
you have a custom taxonomy registered in the "init" hook
so in the wp-admin it doesn´t work -> your taxonomy is registered after you call "get_term"
https://wordpress.stackexchange.com/questions/13480/get-terms-return-errors/13482#13482
Oh my ... i solve this by a crazy solution temporary.look below :
function load_terms($taxonomy){
global $wpdb;
$query = 'SELECT DISTINCT
t.name
FROM
`wp-cls`.wp_terms t
INNER JOIN
`wp-cls`.wp_term_taxonomy tax
ON
`tax`.term_id = `t`.term_id
WHERE
( `tax`.taxonomy = \'' . $taxonomy . '\')';
$result = $wpdb->get_results($query , ARRAY_A);
return $result;
}
As you can see i use a query, but i cant apply this plugin to my programming team.i still awaiting for a correct solution/usage for get_terms function in wordpress plugins.
regards.
Nothing really to add but to make it clear: get_terms()doesn't work in "admin_init" action hook!
I did like bizzr3. Just put my code here because I was a bit confuse with bizzr3's code:
function load_terms($taxonomy){
global $wpdb;
$query = 'SELECT DISTINCT
t.name
FROM
wp_terms t
INNER JOIN
wp_term_taxonomy tax
ON
tax.term_id = t.term_id
WHERE
( tax.taxonomy = \'' . $taxonomy . '\')';
$result = $wpdb->get_results($query , ARRAY_A);
return $result;
}
then just call load_terms() in your "admin_init" function:
//get all terms from taxonomy Category
$terms = load_terms('category');
and thanks, works like a charm.
I know I'm late to the party.
To optimise bizzr3's code just a bit; You should use the $wpdb object properties for your table names, as "wp_" is just the default but it could change from site to site. Using the object property you make sure it should work for other WordPress sites as well if they have a different table prefix.
function load_terms( $taxonomy ){
global $wpdb;
$query = "SELECT DISTINCT
t.name
FROM
{$wpdb->terms} t
INNER JOIN
{$wpdb->term_taxonomy} tax
ON
tax.term_id = t.term_id
WHERE
( tax.taxonomy = '{$taxonomy}')";
$result = $wpdb->get_results( $query , ARRAY_A );
return $result;
}
Also changed the single quotes to double quotes to use {$variables}

Resources