I am using custom field on custom post types.
To display value of single custom field I use this code:
$gym_title = get_post_meta($post->ID, 'cast', true);
echo $gym_title;
Is there a way to display all custom fields with key ="gym" ?
(I have tried to use foreach and to write custom database search but no luck for now.)
Here's an example function which queries the database for all posts and returns all custom fields with a specific key:
function get_all_custom_fields( $key ) {
global $wpdb;
$r = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
", $key) );
return $r;
}
Usage:
$gym_titles = get_all_custom_fields('gym');
Related
I'm using the DevBridge jQuery Autocomplete plugin with the ajax option (using serviceURL instead NOT lookup). I have a php file that queries the db (WordPress FYI) and gets all the results just fine. So when users type into my autocomplete field, it's showing ALL the results with their query highlighted. Apparently my server-side script is supposed to handle the searching and return ONLY the filtered results based on the user's on-the-fly input. I'm just not sure how to go about doing that.
I've found a ton of posts online stating this is how it's supposed to work but can't find any working examples of a serviceURL file that returns filtered results based on what the user is typing.
Here's the code I have so far...
My jQuery...
$('#product_sku_autocomplete').autocomplete({
serviceUrl: '/blah/blah/ajax-product-sku.php',
minChars: 1,
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
the contents of my ajax-product-sku.php file. This gets all the various meta values for a custom field (sku) across all 'products'
if ( ! defined('ABSPATH') ) {
require_once( '../../../../wp-load.php' );
}
global $wpdb;
$term = $_GET['query'];
$query = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = %s
AND p.post_status = %s
AND p.post_type = %s
", 'sku', 'publish', 'products' ) );
$reply = array();
$reply['query'] = $term;
$reply['suggestions'] = array();
foreach ($query as $sku) {
$reply['suggestions'][] = array(
"value" => $sku,
"data" => $sku
);
}
echo json_encode($reply);
The results if I access ajax-product-sku.php directly...
{"query":null,"suggestions":[{"value":"52N242","data":"52N242"},{"value":"52F230","data":"52F230"},{"value":"52F235","data":"52F235"}]}
So I'm getting my full list of results (properly formatted as far as I can tell) and the autocomplete field retrieves those BUT when you type into the autocomplete field it's showing ALL the results not just the ones that match what the user has typed in.
I suspect that I need to add the $term var somewhere within my db $query statement but not sure how. Any help is greatly appreciated.
I think I've got it. Pretty simple solution but my sql chops are lacking obviously. Need to add a LIKE condition to the sql statement. Here's the revised ajax-product-sku.php file contents.
If anyone has a more efficient way to handle this from a coding or performance standpoint, I'd welcome the knowledge...
ajax-product-sku.php
if ( ! defined('ABSPATH') ) {
require_once( '../../../../wp-load.php' );
}
global $wpdb;
$term = $_GET['query']; // this is the var that autocomplete sends as users type.
//$term = '1';
$query = $wpdb->get_col( $wpdb->prepare( "
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = %s
AND p.post_status = %s
AND p.post_type = %s
AND pm.meta_value LIKE '%{$term}%'
", 'sku', 'publish', 'products' ) );
$reply = array();
$reply['query'] = $term;
$reply['suggestions'] = array();
foreach ($query as $sku) {
$reply['suggestions'][] = array(
"value" => $sku,
"data" => $sku
);
}
echo json_encode($reply);
I've been searching through the past two days to find out where exactly could the Woocommerce products thumbnails (images) texts and URL's are stored inside the database tables, but still cannot figure this out!
I'm in a situation where I must use SQL queries to move the products data into another tables, and I have to implement the process from my phpmyadmin panel.
I already searched the wp_posts and wp_postmeta tables, wp_posts contains a guide column for the url to the product which post_type like 'product%', So far I know that in general the post stores it's thumbnalis link inside one of the posts with a type of attachment , while I need the posts with a post_type of product or like so.
Hope I can find some answers here, Thanks.
You can use the Wordpress WP_Query to get the thumbnail image of product.
$args = array(
'post_type' => 'product', //post type of product
'posts_per_page' => -1
);
$query= new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
global $product;
//woocommerce_get_product_thumbnail is use to get the product thumbnail link
echo '<br />' . woocommerce_get_product_thumbnail().' '.get_the_title().'';
endwhile;
wp_reset_query();
Solution 2- using the custom query as you mention in query.
//Using custom query get the details from wp_postmeta and wp_posts
//_wp_attached_file - meta key for image
$querystr = "SELECT p.*, pm2.meta_value as product_image FROM wp_posts p LEFT JOIN
wp_postmeta pm ON (
pm.post_id = p.id
AND pm.meta_value IS NOT NULL
AND pm.meta_key = '_thumbnail_id'
)
LEFT JOIN wp_postmeta pm2 ON (pm.meta_value = pm2.post_id AND pm2.meta_key = '_wp_attached_file'
AND pm2.meta_value IS NOT NULL) WHERE p.post_status='publish' AND p.post_type='product'
ORDER BY p.post_date DESC";
$upload_dir = wp_upload_dir();
//get wp_upload url
$wp_upload_url = $upload_dir['baseurl'];
$pageposts = $wpdb->get_results($querystr, OBJECT);
foreach ($pageposts as $post){
echo "<br /><a href='".$post->guid."'><img src='". $wp_upload_url.'/'.$post->product_image."'>".$post->post_title."</a>";
}
I try to get the post_ids from postmeta where the _sale_price_dates_to are less the now. And I did something like this:
global $wpdb;
$publishid = $wpdb->get_results('SELECT meta_value FROM ' . $wpdb->postmeta . ' WHERE meta_key="_sale_price_dates_to" and meta_value<=' .time().'') or die("Error: Cannot create object");
But it doesn't work. Maybe because the _sale_price_dates_to has format longtext not date. how to change it in the query?
But It's not over. I want to add the condition that the products have to be published then I have to join:
$publishid = $wpdb->get_results('SELECT meta_value FROM ' . $wpdb->postmeta . 'join' . $wpdb->posts . ' ON wp_posts.ID = wp_postmeta.post_id WHERE wp_postmeta.meta_key="_sale_price_dates_to" and wp_postmeta.meta_value<=' .time().' and wp_posts.post_status="publish" ') or die("Error: Cannot create object");
But because of the first problem, I don't know it works.
Update: Setting up the right time zone in the code
Try the following to make a functional SQL query using WPDB to get the Post IDs where post meta _sale_price_dates_to timestamp is less the now time stamp:
global $wpdb;
// Set the correct time zone (http://php.net/manual/en/timezones.php)
date_default_timezone_set('Europe/Paris');
// An array of IDs
$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_status = 'publish'
AND pm.meta_key = '_sale_price_dates_to'
AND pm.meta_value <= '".time()."'
AND pm.meta_value != ''
");
// Raw Output (array of post IDs)
print_r($results);
Tested and works.
meta_value != '' is needed to avoid Post IDs with empty values to be queried.
I'm currently making a plug-in and need some help regarding a subject. I want to use all the the_loop goodness but need a raw sql query.
/**
* Get all the posts neccessarry
* return array<WP_Post> returns an array of all constructed WP_Posts
*/
public static function get_posts($o){
global $wpdb;
$posts = array();
$tax= $o['tax'];
$q=$wpdb->get_results(
"SELECT * FROM {$wpdb->posts} p
LEFT OUTER JOIN
(SELECT * FROM {$wpdb->postmeta}
WHERE meta_key='/$p/_faq_prio'
GROUP BY post_id
) AS pm
ON ( p.ID = pm.post_ID ),
{$wpdb->term_relationships} t
WHERE p.post_type='faq' AND t.object_id = p.ID AND t.term_taxonomy_id = '{$tax}'
ORDER BY pm.meta_value ASC, ISNULL(pm.meta_key)", OBJECT_K);
foreach ($q as $p) {
array_push($posts, get_post($p) );
}
return $posts;
}
I have the following questions:
Does the get_post constructs a WP_Post object based on the data it
receives, or does it extract the post_id parameters and queries the
database yet again? I couldn't find this behavior from the
reference guides.
How can I initilize a WP_Query object based on all the Posts object (should I manually set all parameters like postcount, etc or is there a better way?
I am running a competition which is based on WP Custom Fields. I am trying to count all meta values of a meta_key='odd' for a specific user. I am using the formula below but it's not returning any result.
$meta_key = 'odd';
$post_author = 'Admin';
$odd = $wpdb->get_var( $wpdb->prepare(
"
SELECT Count(meta_value)
FROM $wpdb->postmeta
INNER JOIN $wpdb->posts ON $wpdb->postmeta->post_id = $wpdb->posts->ID
WHERE $wpdb->postmeta->meta_key = 'odd' AND $wpdb->posts->post_author = 'Admin'
",
$meta_key, $post_author
) );
echo "<p>Total odd {$odd}</p>";
Anyone can help me? Thanks in advance.
You are mixing up the $wpdb variables and the $post variables - for your JOIN, for example, you can't use $wpdb->postmeta->post_id, it would be {$wpdb->postmeta}.post_id, and would be even better to just use table aliases. Your prepare() is also not passing in your meta_key or author because you don't have %s placeholders for them
$odd = $wpdb->get_var( $wpdb->prepare(
"
SELECT count(meta_value)
FROM {$wpdb->postmeta} pm
INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
WHERE pm.meta_key = %s AND p.post_author = %s
",
$meta_key, $post_author
) );