I have read some documentation and comparable questions from others about my issue with wpdb, but I've seen very different answers so I'm slightly confused.
What I'm trying to do is get custom meta data from (eventually) about 250 pages in Wordpress. The wpdb request will be in header.php, and the code has to build an array which will serve as input for a Google Map. The custom meta fields are called _ytF_f_name, _ytF_f_lat and _ytF_f_lng (don't ask me why :-)).
So the final output should be: [name1,lat1,lng1], [name2,lat2,lng2], etc.
I'm using a custom table for Wordpress, which has the prefix yt_ (which is defined in wp-config.php). The custom meta is built with WPAlchemy. I have checked the database and the meta data is there (in the postmeta table).
After combining several things, this is what I have now:
<?php
global $wpdb;
$querystr = "SELECT ".$wpdb->prefix."postmeta._ytF_f_name, ".$wpdb->prefix."postmeta._ytF_f_lat, ".$wpdb->prefix."postmeta._ytF_f_lng FROM ".$wpdb->prefix."postmeta WHERE post_type='page'";
$vars = $wpdb->get_results($querystr);
foreach ($vars as $var) {
echo '[' . $var->_ytF_f_name . ',' . $var->_ytF_f_lat . ',' . $var->_ytF_f_lat . '],';
}
?>
The output is blank, so what am I missing here?
Another question related to this is; I've read something about 'prepare' to protect against sql injections.
Is the correct use of the prepare class to change
$vars = $wpdb->get_results($querystr);
into:
$vars = $wpdb->get_results($wpdb->prepare($querystr));
?
About your problem, I don't see the error, so verify if you have SQL errors with $wpdb->show_errors(); before your query (doc here).
The prepare method protects you against SQL injections.
As the doc said, it works like the following :
$wpdb->query(
$wpdb->prepare(
"INSERT INTO ___
( attr1, attr2 )
VALUES ( %s, %d )",
$valueOfAttr1,
$valueOfAttr2
)
);
Of course, you must change the types and values to your needs.
Related
I'm working on a project where I upload a file and use its path in a shortcode. Right now I've hard-coded the post's ID into my code but I want to make it dynamic so that new posts automatically get the correct shortcode.
<?php
global $wpdb;
$thepost = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = 5574" ) );
echo do_shortcode ('[sgpx gpx="'.'/wp-content/uploads/' . $thepost->meta_value . '"]');
?>
Going off of what #Damocles said, you are really setting yourself up for trouble with your current path. Instead, there are built-in WordPress functions that abstract away the database and utilize caching that you are strongly encouraged to use.
// Get the current WordPress post
$the_post = get_post();
//If we have a value (there are cases where this will be empty)
if($the_post){
// Get the value from the post meta table by the current post's ID
$the_post_meta = get_post_meta($the_post->ID, 'YOUR_META_KEY_HERE', true);
// Double-check that we have a value
if($the_post_meta) {
// Finally, echo the shortcode
echo do_shortcode ('[sgpx gpx="'.'/wp-content/uploads/' . $the_post_meta . '"]');
}
}
There are several ways to get the current post however get_post() is the most common. If you are in a custom loop, however, you might need to adjust accordingly.
To access the meta, use get_post_meta() which includes some optimizations including use a cache instead of the database.
Although there are definitely exceptions, generally speaking, if you are working with WordPress and you find yourself writing SQL statements, there is almost always a better, safer, faster, etc. way to do it using core functions.
I followed the syntax the best I could to create a shortcode on execution, I got the wsod. Once removed, all was well. But I don't know what is wrong with my code. This code sits inside 'My Custom Functions', a plugin for wp.
In researching how to write a custom shortcode, I discovered instructions here: https://torquemag.io/2017/06/custom-shortcode/ My expertise is in mysql and use mostly plugins in our wordpress website. I am very limited with coding.
function last_updated_shortcode {
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM
qgotv.last_updated");
return $last_updated;
}
add_shortcode( 'last_updated', 'last_updated_shortcode' );
This shortcode should retrieve a max(datetime value) from a db table so it can be displayed on a page. The query works. The qgotv db is separate from the wordpress db but can be accessed through wp.
Two issues I can see, one is that you have a syntax error in your function. When defining a function in PHP, you need to include the arguments parenthesis: function my_function(){ /* Do Stuff */ }. Also, you probably need to reference the $wpdb with the global keyword.
You can read up a bit on the $wpdb class as well as creating your own functions.
This should get you sorted out:
add_shortcode( 'last_updated', 'last_updated_shortcode' );
function last_updated_shortcode(){
global $wpdb;
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM qgotv.last_updated");
return $last_updated;
}
I'm trying to access a plugin's database from functions.php. With the code below, there are no errors, but there is no data echoing either. By looking around the web there are so many answers for so many different circumstances and none helped me apply any fixes to this particular code.
function show_review_count() {
global $wpdb;
$dbtable = 'wpcreviews';
$pageID = 4745;
$row = $wpdb->get_results("SELECT COUNT(*) AS `total` FROM `$dbtable` WHERE `page_id`=$pageID AND `status`=1");
echo $row[0]->total;
}
You're missing $wpdb's table prefix:
$dbtable = $wpdb->prefix . 'wpcreviews';
I have a Wordpress-powered website with several custom post types, and I'm struggling to find a way to load the latest uploaded images from one of the custom post types only.
In other words, I know how to ask for the most recent 4 images added to the Wordpress media library, but I can't find a way to filter the attachments depending of the post type of their parent page (in this case, show only the images uploaded to 'Image Gallery' posts - not regular posts, not 'Video Gallery' posts, etc).
It feels like a very basic question, but for some reason I can't get this work and I'm really frustrated. Is there any way to get the post type of the post parent in the query? Or I should approach this issue from another angle?
I don't believe it's possible to use WP_Query to filter based on the post type of the parent. The most straightforward way around this is to use SQL and $wpdb->get_results() directly. This will also bypass all built in caching, etc so think about how your implementation will be used.
global $wpdb;
// the SQL statement to only fetch the N last attachments
$sql = <<<SQL
SELECT attachments.*
FROM {$wpdb->posts} attachments
-- join the parent post based on the parent_post value to filter by cpt
JOIN {$wpdb->posts} post
ON post.ID = attachments.post_parent
AND post.post_status = 'publish'
-- pass in the custom post type
AND post.post_type = %s
WHERE
-- only fetch images, double percents for prepare()
attachments.post_mime_type LIKE 'image%%'
ORDER BY attachments.post_date DESC
-- pass in the number to fetch
LIMIT %d
SQL;
$cpt = "your_custom_post_type";
$limit = 4;
$attachments = $wpdb->get_results( $wpdb->prepare( $sql, $cpt, $limit ) );
foreach ( $attachments as $attachment ){
// $attachment will have all the rows from the posts table.
$id = $attachment->ID;
}
I am building my first plugin, and I am using as a reference the following link.
http://www.sitepoint.com/create-a-voting-plugin-for-wordpress/
and I am trying to underestand the following part of the code:
function voteme_addvote()
{
$results = '';
global $wpdb;
$post_ID = $_POST['postid'];
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votemecountNew = $votemecount + 1;
update_post_meta($post_ID, '_votemecount', $votemecountNew);
$results.='<div class="votescore" >'.$votemecountNew.'</div>';
// Return the String
die($results);
}
I run the code and it works, but I just dont understand the following:
What is "get_post_meta" doing?
Does it create a custom meta field, the same as add_post_meta?, if it doesnt why there is not an add_post_meta?
I checked the DB, and it looks like it is creating a custom meta field... so in that order what is the difference between get_post_meta and add_post_meta?
Thanks very much for helping me understand this.
The first time your code runs, get_post_meta returns '' so $votemecount is set to 0. The following update_post_meta creates the new meta field as documented below. Values that start with _ are not displayed (are hidden meta fields).
The function, update_post_meta(), updates the value of an existing meta key (custom field) for the specified post.
This may be used in place of add_post_meta() function. The first thing this function will do is make sure that $meta_key already exists on $post_id. If it does not, add_post_meta($post_id, $meta_key, $meta_value) is called instead and its result is returned.