Id changing variable - wordpress

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.

Related

Custom function error to produce a shortcode resulted in white screen of death

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

trying to display a custom field

Guys I'm writting a wordpress site to run a knowldge base for our Service desk. As one person will be updating it i needed to have a field for who wrote the kb artical. I'm tring to add a custom field into my wordpress theme to display writtenby using Advance custom Fields. Now I'm using echo Knowledge Base plugin for knowldge base.
I've got as far add ing code below will display the text below the last up date value that plugin creates. However i cannot get it to put value from the custom field on the page after this. The plugin creates the page using php below the ive added the two lines as below.
$wb = get_post_meta($post->ID, 'Writtenby', true);
echo ' Last Update Writtenby:'.$wb.' ';
// LAST UPDATED ON
public static function last_updated_on( $args ) {
echo '' . esc_html( $args['config']['last_udpated_on_text'] ) . ' ' . EPKB_Utilities::get_formatted_datetime_string( $args['article']->post_modified, 'F d, Y' ).'';
$wb = get_post_meta($post->ID, 'Writtenby', true);
echo ' Last Update Written by:'.$wb.' ';
}
Advanced Custom Fields plugin use a little bit different system to store postmeta. Try to use get_field() instead get_post_meta()
If you have the ID
$customField = get_post_meta($my_id, "_mcf_customField", true);
However if you want to get the ID from the object:
$customField = get_post_meta($post_id->ID, "_mcf_customField", true);
After much more work looks like at the point the page was being created it had no reference to partical page not even a current one. They where writting to an array all artical numbers and info.
So by telling get_field which artical to get the writtenby field from it now displayed data and not blank
$wb= get_field('Writtenby', $args['article']->ID);

how can we get details from another database inside a plugin in wordpress

I created a plugin in wordpress to display earnings by using a shortcode.The details to display while using shortcode are stored in another database.I used direct database connection in plugin to fetch details from the that database.I used the following code
function earnings_shortcode($atts, $content, $tag)
{ //echo $atts[0];echo '<br>';
$str=base64_encode(1);
base64_decode($str);
$length = 4;
$res = trim(preg_replace("/[^0-9]/", "", $atts[0]));
$mydb1 = new wpdb('root','','db_test','localhost');
$rows = $mydb1->get_row("SELECT total,paydate FROM `tbl_shotcode` WHERE userid = $res", ARRAY_A);
echo "Payout on -" .$rows['paydate']; echo '<br/>';
echo "Total for next Pay Period:-" .$rows['total'];
}
Is there any better option to access another database inside a plugin with out hard coding the username and password.please suggest a solution.
No, you have to access the database and be authenticated to do queries. You can't get into a properly configured database without login in.
You can, however, make your $mydb1 variable global and define it at the top of your file (or in your constructor class) to be accessed by all your functions. I recommend putting it in a class to manage it more easily.

Select custom meta (WPAlchemy) from pages with wpdb

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.

Add Meta Post function not working

I am using add post meta function to save some data and its not working
<?php
//include '../../../wp-blog-header.php';
$unique = "true";
$pageID = $_GET['postID'];
echo "pageID:";
echo $pageID;
echo "</br>";
$num_posts = $_GET['num_posts'];
echo "num_posts: ";
echo $num_posts;
echo "</br>";
$num_posts_meta_key = "num_posts";
add_post_meta($pageID, $num_posts_meta_key, $num_posts , $unique) or update_post_meta($pageID, "num_posts" , $num_posts);
?>
Can someone help me out?
In first page I am getting all values from textboxes or checkboxes in javascript and then i am passing it in URL to next page where add_post_meta function is there.
I tried using method POST ...but then it doesnt work for me. It just submit the page and come back w/o doing anything on 1st page. I tried with GET method..but nothing works.
Hence I decided to take all values like num of post, post id in javascript and then from there pass it with url by using window.location.
I am very new to wordpress plugin coding. I thought POST method in my plugin is conflicting with some other post method in post.php..not sure though..
I am writing plugin for admin panel.
not sure what your problem is.. are you sure you're passing the right postID parameter? does the post exist in the database?
You don't really need to do add_post_meta() or update_post_meta.
From the manual:
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.
<?php
// This minimum code should work, though you should really check that a post
// with this id does exist.
update_post_meta($_GET['postID'], "num_posts" , $_GET['num_posts']);
?>

Resources