I am new to wordpress I am try to create table and insert data to that table. so within the wordpress database I created table called 'album' then I created directory called 'my-codes'(within root directory/ same level with 'wp-admin' , 'wp-content, 'wp-includes' directories)
within that directory I created insert.php then i added following code
<?php
global $wpdb;
$wpdb->insert($wpdb->album , array("ID"=>1, "Name"=>'something'), array("%d", "%s"));
?>
but it give this error Fatal error: Call to a member function insert() on a non-object in C:\wamp\www\wordpress\my-codes\insert.php what is the mistake I did, please help me.
You have to load the Wordpress files within your script, so that you have access to Wordpress' $wpdb object:
require_once( '../wp-load.php' );
This will load all of Wordpress, even the functionality you don't need. If you want to only load the database part, read this article.
Update - The first argument to the insert method should be the name of your table:
$wpdb->insert(
'album',
array("ID"=>1, "Name"=>'something'),
array("%d", "%s")
);
require (dirname(dirname(__FILE__)) . '/wp-blog-header.php');
require (ABSPATH . WPINC . '/compat.php');
require (ABSPATH . WPINC . '/functions.php');
require (ABSPATH . WPINC . '/classes.php');
require_wp_db();
global $wpdb; // Look look! Over here! line 270 in wp-settings.php
if ( !empty($wpdb->error) )
dead_db();
//Execute your query here
I would recommend using the WordPress Options API instead of creating a custom table, unless options won't fit your needs. Also, place all your code in your theme's functions.php. That way, you won't need to load any other WordPress files externally. They're already loaded for you automatically if your code is in functions.php.
Here's a quick example of how to store data in the database using options ( taken from the WP Codex article linked above ):
// Create an option to the database
add_option( $option, $value = , $deprecated = , $autoload = 'yes' );
// Removes option by name.
delete_option( $option );
// Fetch a saved option
get_option( $option, $default = false );
// Update the value of an option that was already added.
update_option( $option, $newvalue );
Options are much easier to implement and generally less error prone than direct database access. :)
Related
i've created a woocommerce plugin,
the plugin itself runs perfectly.
However as long as it takes for it to run, i'm experiencing wierd performances issues.
The website is totally inaccessible(both frontend and backend) ONLY from the browser that is logged in and ran the plugin.
Both frontend and backend are loading until the plugin finishes.
to make things even wierder it's working perfectly from another browser.
also this is run on a high-end dedicated server and when it's running the loads on the server are very low.
any clues?
require __DIR__ . '/vendor/autoload.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');
use Automattic\WooCommerce\Client;
$woocommerce = new Client(woocommerce_api_url, api_key, api_secret,['version' => 'wc/v3','timeout' => '99999',]);
echo '<pre>';
$db = new DBfdr();
$i=0;
$page = 1;
$products = [];
$all_products = [];
do{
try {
$products = $woocommerce->get('products',array('per_page' => 100, 'page' => $page));
} catch(HttpClientException $e) {
die("Can't get products: $e");
}
$all_products = array_merge($all_products,$products);
$page++;
Notes: the DBfdr class contains a simple function for managing pdo connections to the sql server.
That piece of code doesn't look so good, why would you need to make a plugin that externally loads wp then going through Woocommerce Client Api to get the list of products and then cycle all of them to make an if condition.
That would be so much more efficient if you would just pass inside WP standard plugin structure, using global $wpdb class and performing your queries with some join.
That said, the problem you are facing could be solved by adding this before your code:
ignore_user_abort( true );
/* Don't make the request block till we finish, if possible. */
if ( function_exists( 'fastcgi_finish_request' ) && version_compare( phpversion(), '7.0.16', '>=' ) ) {
fastcgi_finish_request();
}
The problems occurs because the wp-config.php is included in the beggining.
wp-config.php in the end has
require_once(ABSPATH . 'wp-settings.php');
which inits some core wordpress functions which in turn "locks" the session.
i managed to fix the issue by removing
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');
and replacing it with customs defines
I am working on a project where users can check and edit their own data and can also view their invoices.
I am writing the code for this project myself in PHP on my local machine but the invoices are made with the wp-invoice plugin on an existing and working wordpress site that's hosted somewhere else.
I want users to be able to log in to my web-app and then see their invoices that the web-app retreived from the wp-invoice api on the public wordpress site. The documentation for the wp-invoice api can be found here: https://www.usabilitydynamics.com/product/wp-invoice/docs/wp-invoice-api, it uses XML-RPC with which I am not familiar.
XML-RPC uses built-in wordpress functions to use the API. So I also downloaded and installed wordpress on my local machine and almost got it working (i believe). But when I load the wordpress functions into my web-app using "wp-load.php" it redirects me to the wordpress installer which says wordpress is already installed and there is a working wp-config.php file. This is correct because I installed wordpress successfully.
My code:
(This is my only code, there are no other files, functions or classes included using 'include_once')
define("ABSPATH", "C:/wamp64/www/mijnDashboard/WP");
define("WPINC", "/wp-includes");
include_once( ABSPATH . '/wp-load.php' );
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$client = new WP_HTTP_IXR_Client( 'http://MyWordpressSiteWithWP-INVOICEinstalled/xmlrpc.php' );
$client->query('wp.invoice', array(
$method = 'get_invoice',
$credentials = array('Username', 'Password'),
$args = array(
'ID' => 1032017043
)
));
$the_invoice = $client->getResponse();
echo "$the_invoice";
echo "hallo";
Result: (it redirected me from my self-written 'dashboard.php' to the wordpress page 'wp-admin/setup-config.php')
Tried solutions:
I searched the web for solutions and some people said it had something to do with my browser cache. I tried another browser and incognito mode in chrome but both got me the same result.
Beside that I tried to load the wordpress functions that I need to use XML-RPC using an other wordpress file called 'wp-blog-header.php' but it got me the same result.
I actually think this is easy to fix but I am new to XML-RPC and API's at all and I don't know how to properly include all wordpress functions in a non-wordpress, self-written file.
Thanks,
Elias
Okay, I figured it out. I didn't use my local machine anymore but I used a webserver instead. There are no errors and I am not being redirected when I load 'wp-load.php'.
It is strange that almost the same code runs fine on a public webserver but not on a local machine. But it's working now so it's fine.
The code: (I used this and uploaded it to the WordPress root directory which contains the other files like wp-config.php etc.)
<?php
define( 'WP_USE_THEMES', false );
require( 'wp-load.php' );
$rootD = $_SERVER['DOCUMENT_ROOT'];
define("ABSPATH", "$rootD/httpdocs");
define("WPINC", "/wp-includes");
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$client = new WP_HTTP_IXR_Client( 'http://mywordpresswebsite/xmlrpc.php' );
$client->query('wp.invoice', array(
$method = 'get_invoice',
$credentials = array('username', 'password'),
$args = array(
'ID' => 1032017039
)
));
$the_invoice = $client->getResponse();
foreach ($the_invoice as $key => $value) {
echo "$value";
}
?>
Thanks for all the help.
I want to create some variables / options to customize my wordpress theme.
At the moment I already have 5 variables which I set inside the functions.php file:
$isBoxedLayout = true;
$postCounter = 0;
$postDate = false;
$socialButtons;
$showCatLink = false;
I access them throughout the other files like header.php, content.php etc.:
global $isBoxedLayout;
global $postCounter;
At the top of the files. I think it would be better to have like only one array where I can store it all!? But how do I do it right?
Also, does somebody know how I can access a variable, set in the functions.php, inside the template-tags.php file?
I already tried this:
include '../functions.php'
But I get the following error:
include(../functions.php): failed to open stream: No such file or directory
When I want to access the variable in a file like content.php it works well. Where is the difference?
Maybe not exactly the answer you are looking for, but I would take a look at the Options API. It saves your options into the database and is very easy to use.
// Functions.php
add_option( 'isBoxedLayout', true, '', 'yes' );
// template-tags.php
$isBoxedLayout = get_option( 'isBoxedLayout' );
I have a plugin to be translated. I have done following tasks:
Loaded the TextDomain:
$my_td = 'mysignup';
function my_signup_textdomain_init() {
global $my_td;
load_plugin_textdomain( $my_td, false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'my_signup_textdomain_init');
Added language files(po, pot, mo) in wp_plugin_folder\my_signup\languages (for Bengali bn_BD):
mysignup.pot
mysignup.mo
bn_BD.po
bn_BD.mo
Changed the language code in wp_config.php file:
define('WPLANG', 'bn_BD');
But problem is nothing is changed. I am not sure what i have done as mistake. I already read lots of articles and answers. Still i need help to know how can i test everything is fine that i have done and how can i solve the issue.
Please help me. Thanks in advance.
First of all - what is global $nl_td; did you mean global $my_td; ?
Second - you seem to miss the .po file ( e.g. mysignup.po ) - and you do not need bn_BD.po and bn_BD.mo
Third - try to load like this ( without the unnecessary variable ) :
load_plugin_textdomain( 'mysignup', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
Fourth - Make sure ALL your strings are like so : __('string','mysignup');
EDIT I after comment :
In your comment you wrote :
__('First Name field is required', $nl_td) and _e('First Name field is required', $nl_td)
Again - As far as I can tell from your very restricted code - $nl_td is not defined . $my_td is defined .
Just replace all those variables with a simple string mysignup .
Your code is probably some kind of cut&paste - but you must understand what those variables mean if you want them to work correctly, or make sure they are consistent all over .
Edit II( now that you edited comment from $nl_td to $my_td it seems you start to understand - edit also your code .. :-) then it will work as long as it is global. but better just write a string . )
I am developing a plugin in which i need to include config and query the wordpress database on click ..My question is
How to get url of wp-config.php dynamically ..I have used
include_once $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php';
but i am getting error
include_once(): Failed opening /wp-config.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear')
and i have tried many options like
require_once('../../../wp-config.php');
require_once ("../wp-config.php");
I dunno wat is exact path ..
Any help is appreciated ..
In short, you shouldn't be trying to include wp-config.php from your plugin. There are few if any good reasons you would ever take this approach. Purists would go as far as to say it should never be done.
A WordPress plugin already has the proper context to access the global $wpdb variable for querying. Take a look at this example:
global $wpdb;
$results = $wpdb->get_results( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}your_table WHERE column = %s", $your_value) );
Suggested reading:
http://codex.wordpress.org/Class_Reference/wpdb
Querying the database in WordPress should be done through the global $wpdb variable. See the codex entry for that: http://codex.wordpress.org/Class_Reference/wpdb.
If you still want to avoid all the warnings to make good practices of coding, you can try this that include many paths where can find wp-config.php
if( !(include $_SERVER['DOCUMENT_ROOT'].'/wp-config.php') )
if( !(include 'wp-config.php') )
if( !(include '../../../wp-config.php') )
if( !(include '../../../../wp-config.php') )
if( !(include '../../../../../wp-config.php') )
die('<H1>Can\'t include config.</H1>');
Notes:
you can add lines with if( !(include 'my_custom_path/wp-config.php') )
you can't use wp_die() until wp-config be included, then use php function die()