how can we get details from another database inside a plugin in wordpress - 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.

Related

Id changing variable

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.

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

Uniquely Identy Wordpress Installation

I am working on an API for wordpress and I am looking for a way to uniquely identify a wordpress installation that is requesting the API. Does anyone know of a install id or unique wordpress blog id? Is that even a thing?
I have written 2 APIs and have worked with several, I stumbled upon this question long time back...
I like to keep the stuff simple... so I use site_url() as identity of the blog, since I'm sure no other installation would run on the same site url so whenever there is an issue to debug, I know site ID is the url.
Saved one extra field in my DB ( If I had ID different, I'd need another field for site url ).
You can also go for complex solutions like using md5 of site_url along with some random generated strings to name a few.
Update
This will generate an ID on activation and save it in the database.
function generate_password($length = 12) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$password = '';
for ($i = 0; $i < $length; $i++) {
$password. = substr($chars, rand(0, strlen($chars) - 1), 1);
}
return $password;
}
function my_plugin_activated() {
$id = generate_password();
add_option('my_plugin_installation_id', $id);
}
register_activation_hook( __FILE__, 'my_plugin_activated' );
Code in my_plugin_activated() is executed only once on activation of plugin ( you can do the same for theme 😉 ), you can, in activation hook itself, make a call to your api and get the site registered in your db.
Hope that helps.

How to get data from array object in WordPress plugin api

http://localhost/wordpress/give-api/forms/?key=15443f18029e6f5d3b65d04e1640ffbe&token=c3de770a410282359413c74a588c5c74
The above link is a plugin api link. Above link won't work to your browser.
when I set the above link in the browser , it returns array object like http://postimg.org/image/6ozmjy0e7/ .
My question is , how can I set this url in a variable in wordpress and how can I get the data from that array object. I just want to get the data from that array object. If any other process is available, then please suggest me. Thanks...
In functions.php:
function displayApiUrl() {
global $apiUrl; // you probably don't actually need to set it global as it is a function
$apiUrl = 'http://localhost/wordpress/give-api/forms/?key=15443f18029e6f5d3b65d04e1640ffbe&token=c3de770a410282359413c74a588c5c74';
return $apiUrl;
}
In your theme you can now use:
<?php $api = displayApiUrl(); ?>
With that you can process your array in a foreach loop:
<?php
$json_url = file_get_contents($api);
$json_data = json_decode($json_url, true);
foreach ($json_data['forms'] as $form) {
$form_id = $form['info']['id'];
echo $form_id;
}
?>
The new "standard" for WordPress rest apis is Json Rest API, which will be partially integrated into WordPress core in the next release.
You can get it here https://wordpress.org/plugins/json-rest-api/ and documentation at http://wp-api.org/
In terms of the question how to put array information into the URL, the format is
http://www.example.com/wp-json/endpoint?array_1[key1]=Pensacola&array_1[key2]=Florida
The URL of course changes, and the wp-json/endpoint is replaced with whatever the final endpoint is for which ever rest api you choose to use.

Wordpress - Encrypt passwords of imported users

I am about to import about 10,000 users to my Wordpress site from another CMS. Problem is, none of their passwords are going to work because they are not encrypted.
How do I encrypt all of these passwords quickly and in a way that Wordpress will recognize and accept so that users can login?
As encryption and hashing are different stuff, I assume all these passwords are in plain text format. In this case, all you have to do is to apply the md5 algorithm on them.
You can do it from a SQL or a PHP importing script. Take a look at the Resetting Your Password Codex page, and that should give you some light.
Anyway, you won't go too far from:
require_once( ABSPATH . WPINC . '/registration.php');
$sql = "SELECT ALL USERS FROM YOUR TABLE";
$db = new wpdb (DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$result = $db->get_results($sql);
foreach ($result as as $r) {
wp_update_user(array(
'user_login' => $r->username,
'user_pass' => $r->password,
'user_firstname' => $r->first_name
));
}
Take a look on the get_userdata function documentation to see what user info you can import at first moment.
As it turns out, I found a couple of other ways to do this. One is done through your mysql phpmyadmin area (on the "sql" tab once you've selected the right database) and was posted by Andrew Vit on another thread within stackoverflow:
UPDATE wp_users SET user_pass = MD5(user_pass) WHERE ...
for the "where" condition, if all your passwords are the same length, you might use the following condition:
WHERE CHAR_LENGTH(wp_users.user_pass) = 12
Of course, if your password length is different, simply change the "12" above to whatever the length of your passwords is. If they are NOT the same character length then you'll have to use some other criteria for determining which passwords to encrypt (unless they ALL need to be encrypted, in which case you can leave the "where" condition off entirely.
I personally ended up using a php script to do the work, so that the passwords could be encrypted by Wordpress itself (or at least using the method that Wordpress uses). Here are the contents of my php file:
<?php
require_once '/home/evaluate/public_html/members-blog/wp-config.php';
$sql="SELECT user_pass,ID FROM wp_users WHERE CHAR_LENGTH(wp_users.user_pass) = 12";
$find = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($find))
{
$current_password = $row['user_pass'];
$current_id = $row['ID'];
$hashed_password = wp_hash_password( $current_password );
$update_sql= "UPDATE wp_users SET user_pass = '" . $hashed_password . "' WHERE ID = " . $current_id . "";
$update = mysql_query($update_sql) or die(mysql_error());
echo $current_id . " " . $hashed_password;
echo "<br />";
}
?>
Done this way, not only are the passwords encrypted using Wordpress' own method, but, you also get a printout on your screen each time you run the script, showing you the ID of all the records that were updated and providing the corresponding hashed password.

Resources