$wpdb->insert() is giving error undefined function - wordpress

I have created a new file inside wp-content/theme/mytheme folder.
Inside the file I have written simple query
global $wpdb;
$insert= $wpdb->insert('wp_test', array(
'orderID' =>$_GET['orderID'],'amount'=>$_GET['amount'],'acceptance'=>$_GET['ACCEPTANCE'],'status'=>$_GET['STATUS'],
));
I am getting error "Call to undefined function". Do I have to include file inside this file?

Try this : include wp-load.php at beginning of file.
File is located at theme folder.
require_once('../../../wp-load.php'); //<-----please include this
global $wpdb;
$insert= $wpdb->insert('wp_test', array(
'orderID' =>$_GET['orderID'],'amount'=>$_GET['amount'],'acceptance'=>$_GET['ACCEPTANCE'],'status'=>$_GET['STATUS'],
));

According to this document : https://codex.wordpress.org/Class_Reference/wpdb
you must change your code to this:
global $wpdb;
$wpdb->insert(
'wp_test',
array(
'orderID' => $_GET['orderID'],
'amount' => $_GET['amount'],
'acceptance' => $_GET['ACCEPTANCE'],
'status' => $_GET['STATUS'],
),
array( '%d', '%d', '%s','%s' )
);

By these ways , You can do it easily,
First define $wpdb globally as like global $wpdb;
require_once('../wp-load.php'); // relative path
<?php
$wpdb->insert("wp_submitted_form", array(
"col_nmae" => $value,
));
?>
Second Way is
$sql = $wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(col_nmae)
values ($val)");
$wpdb->query($sql);
Third is
$sql = "INSERT INTO `wp_submitted_form`
(col_nmae)
values ($val)";
$wpdb->query($sql);
If you are beginner then read more here https://codex.wordpress.org/Class_Reference/wpdb

Related

How to get post count of a custom query in wordpress?

When I try to get the post count of a custom query in wordpress I get the following error as output.
Warning: array_map(): Argument #2 should be an array in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/class-wp-query.php on line 1918
Warning: implode(): Invalid arguments passed in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/class-wp-query.php on line 1918
0
So below is my function:
if( !function_exists('my_likes') ){
function my_likes() {
global $current_user;
$current_user = get_current_user_id();
// The Query
$args = array(
'meta_key' =>'likes_count',
'orderby' => 'date',
'post__in' => $current_user
);
$obj_name = new WP_Query($args);
$num = $obj_name->post_count;
print $num;
}
add_action('my_likes', 'my_likes');
}
count($obj_name->posts)
This is an inefficient way to count user posts as it gets all the post object. Perhaps just use a raw SQL query
The line 'post__in' => $current_user is incorrect the post__in should be an array so if you want to use it like this you would need to do 'post__in' => array($current_user)
Also from the context i am not sure is you want to use this line at all, if you want to count posts posted by user identified by $current_user then instead of 'post__in' => $current_user you should use 'author' => $current_user
BTW. the line global $current_user; is not needed there at all and overtwites the global $current_user value.
The complete code should look like this i think
function my_likes() {
$current_user = get_current_user_id();
// The Query
$args = array(
'meta_key' =>'likes_count',
'orderby' => 'date',
'post__in' => array($current_user),
// or 'author' => $current_user
);
$obj_name = new WP_Query($args);
$num = $obj_name->post_count;
print $num;
}

WordPress get_template_part pass variable

Is there a way of passing a variable to get_template_part() in wordpress:
<?php get_template_part( 'element-templates/front', 'top' ); ?>
<?php get_template_part( 'element-templates/front', 'main' ); ?>
In the front-top.php and front-main.php (which the above is calling) I need to access numeric variables (a different one for each section). Is there a way of passing a variable to each of the calls above?
Thank you
Using WordPress 5.5+
As of WordPress 5.5, passing variables via get_template_part is part of core.
Starting in WordPress 5.5, the template loading functions will now
allow additional arguments to be passed through to the matched
template file using a new $args parameter.
get_template_part( string $slug, string $name = null, array $args = null )
Example:
get_template_part( 'template-parts/featured-image', null,
array(
'class' => 'featured-home',
'data' => array(
'size' => 'large',
'is-active' => true,
)
)
);
and then in the included file (i.e. template-parts/featured-image.php), you can either just display the variables (as per above example):
if ( $args['class'] ) {
echo $args['class'];
}
or
echo $args['data']['size'];
Alternatively, setup defaults first, using wp_parse_args:
// Setup defaults
$array_defaults = array(
'class' => 'featured',
'data' => array(
'size' => 'medium',
'is-active' => false,
)
);
$args = wp_parse_args($args, $array_defaults );
<div class="widget <?php echo esc_html( $args['class'] ); ?>">
<?php echo esc_html( $args['data']['size'] ); ?>
</div>
To be backwards compatible in your theme, you should probably also check the current WordPress version.
Using set_query_vars
The original answer to this question was to use set_query_var
In your theme:
<?php
set_query_var( 'my_var_name', 'my_var_value' );
get_template_part( 'template-parts/contact' );
?>
In the template part:
<?php
$newValue = get_query_var( 'my_var_name' );
if ( $newValue ) {
// do something
}
?>
The core get_template_part() function doesn't support the passing of variables. It only accepts two parameters, slug and name. While there is no built-in solution to this problem, the best approach is to create a function that closely mimics get_template_part() to handle it.
Normally I would create a function that just takes the name of the template file and the variables I want to pass in as an array. In your example however, you're using both arguments for get_template_part() already which means you'll need a slightly more complex function. I'm going to post both versions below.
Simplified Version - Name (slug) and Data
function wpse_get_partial($template_name, $data = []) {
$template = locate_template($template_name . '.php', false);
if (!$template) {
return;
}
if ($data) {
extract($data);
}
include($template);
}
Usage example: wpse_get_partial('header-promotion', ['message' => 'Example message']);
This would load up a file named header-promotion.php with $message available inside of it. Since the second parameter is an array, you can pass in as many variables as you need.
Copy of get_template_part - adding a third parameter
If you don't need both $slug and $name when you call get_template_part(), you probably want the simplified version. For those that do, here's the more complex option.
function wpse_get_template_part($slug, $name = null, $data = []) {
// here we're copying more of what get_template_part is doing.
$templates = [];
$name = (string) $name;
if ('' !== $name) {
$templates[] = "{$slug}-{$name}.php";
}
$templates[] = "{$slug}.php";
$template = locate_template($templates, false);
if (!$template) {
return;
}
if ($data) {
extract($data);
}
include($template);
}
Usage example: wpse_get_template_part('header-promotion', 'top', [$message => 'Example message']);
Neither function is a perfect copy of get_template_part(). I've skipped all of the extra filters the core function uses for the sake of simplicity.
What about globals or query vars
Globals are pretty commonplace in WordPress but are generally best avoided. They will work but start to get messy when you use the same template part more than once on a single page.
Query vars (get_query_var() / set_query_var()) aren't made for that purpose. It's a hacky workaround that can introduce unintended side-effects.
As of WordPress 5.5, you're be able to achieve this using the following method:
<?php
get_template_part(
'my-template-name',
null,
array(
'my_data' => array(
'var_one' => 'abc',
'var_two' => true,
)
)
);
In your template, you can then parse the date and escape it in the following way:
<?php
$args = wp_parse_args(
$args,
array(
'my_data' => array(
'var_one' => 'xyz', // default value
'var_two' => false, // default value
)
)
);
?>
<?php echo esc_html( $args['my_data']['var_one'] ); ?>
you can pass data to tempalte part via Global varible
like this
$var = 'smoe data here';
<?php get_template_part( 'element-templates/front', 'top' ); ?>
then in your template part file use
<?php
global $var;
echo $var; // smoe data here
?>
Like mentioned by thetwopct - since WP 5.5, you can pass $args to the get_template_part function like so:
$value_of_first = 'pizza';
$value_of_second = 'hamburger';
$value_of_first = 'milkshake';
$args = array(
'first' => $value_of_first,
'second' => $value_of_second,
'third' => $value_of_third,
)
get_template_part( 'element-templates/front', 'top', $args );
then, in element-templates/front-top.php get the vars like so:
[
'first' => $value_of_first,
'second' => $value_of_second,
'third' => $value_of_third,
] = $args;
echo 'I like to eat '.$value_of_first.' and '.$value_of_second.' and then drink '.$value_of_third.';
// will print "I like to eat pizza and hamburger and then drink milkshake"
Note: the method described above for getting the vars in the template file uses associative array restructuring, available only from PHP 7.1. You can also do something like:
echo 'I like to eat '.$args[value_of_first].' and ...
A quick and dirty workaround can be made using PHP Constants:
In your theme:
define("A_CONSTANT_FOR_TEMPLATE_PART", "foo");
get_template_part("slug", "name" );
Now in slug-name.php template file you can use the A_CONSTANT_FOR_TEMPLATE_PART constant. Be sure not override system constants by using a custom prefix for your constant name.
In your template part file:
echo A_CONSTANT_FOR_TEMPLATE_PART;
You should see "foo".

getting error on wpdb line wordpress

getting error $wodb as Uncaught SyntaxError: Unexpected identifier
function store_db() {
global $wpdb; $fields = array('email');
$tbl_name = $wpdb->prefix.'feedback';
$kv_data = array( 's_email'=> $email) ;
$wpdb->insert( $tbl_name, $kv_data )
}
You should consider using an IDE such as Sublime Text, DreamWeaver, PHP Storm, etc. Any number of them would show you where the syntax error is. I pasted it into my IDE and it instantly told me there was a missing semi colon after this line $wpdb->insert( $tbl_name, $kv_data ).
Also you'll want to take care to manage your formatting/indentation - future you appreciates it!
function store_db() {
global $wpdb;
$field = array( 'email' );
$table = $wpdb->prefix.'feedback';
$kv_data = array( 's_email' => $email );
$wpdb->insert( $table, $kv_data ); // Added `;` to this line.
}

NinjaForm - How To Search & Retrieve By DateTime?

I'm using NinjaForm plugin on wordpress. Here how to search and retrieve data:
<?php
$args = array(
'form_id' => $form_id,
'user_id' => $user_id,
'fields' => array(
'34' => 'checked',
'54' => 'Hello World',
),
);
// This will return an array of sub objects.
$subs = Ninja_Forms()->subs()->get( $args );
// This is a basic example of how to interact with the returned objects.
// See other documentation for all the methods and properties of the submission object.
foreach ( $subs as $sub ) {
$form_id = $sub->form_id;
$user_id = $sub->user_id;
// Returns an array of [field_id] => [user_value] pairs
$all_fields = $sub->get_all_fields();
// Echoes out the submitted value for a field
echo $sub->get_field( 34 );
}
What I want to do is searching by DateTime fields. How do I do that?
I have tried change args like this but result same.
$args = array(
'form_id' => 5,
'date_modified'=> '2015-07-25 3:19:09'
);
or like this
$args = array(
'form_id' => 5,
'date_modified'=> '< 2015-07-25 3:19:09'
);
Did I do wrong?
Find Ninja DB Table:
Go into your database using phpmyadmin or something and find the table Ninja Forms is using. Hopefully they're using their own table. If not, you can search each wp table for some of the arg data that you know returns a form from Ninja_Forms(). Or go into the Ninja plugin code and try and find where they interact with the db to find which table they write into.
Write your own mysql search code:
Instead of using Ninja's class to search, use wordpress's built in mysql search and throw in the table you found in step 1.
GLOBAL $wpdb;
$wpdb->get_results($wpdb->prepare("SELECT * FROM `ninja_table` WHERE `date_modified` = %s", $strDate));
I haven't tested, but this would be my course of action.
Use begin_date and end_data parameters to get the submissions
$args = array(
'form_id' => $form_id,
'begin_date' => '2015-07-20 0:00:00',
'end_date' => '2015-07-25 3:19:09'
);
$subs = Ninja_Forms()->subs()->get( $args );

form input submit to database using $wpdb

I am wondering how to insert form input value to wordpress database.
In a wordpress theme, I want to add an input element and insert it to database.
Clicking the submit button, I think there is no effect to insert for the following codes.
wordpress_theme_file.php
<form id=”form_reply” action=”database.php” method=”post”>
…
<input type=”text” id=”newValue” name=”newValue” />
…
</form>
database.php
<?php
global $wpdb;
$inputValue = $_POST[‘ newValue ‘];
$wpdb->insert(‘wp_table_name’, ‘field_name’=>$inputValue); // wp_table_name and field_name in database
?>
You can insert to wordpress table like this
global $wpdb;
$inputValue = $_POST['newValue'];
$wpdb->insert(
'table_name',
array(
'column1' => $inputValue
),
array(
'%s' // if the field type is string
)
);
for more info
Sample code which help you to insert data to database in wordpress :
<?php
global $wpdb
$address = 'address';
$firstn = "First Name';
$wpdb->insert( 'users', array( 'address' => $address, 'first_name' => $firstn ), array( '%s', '%s' ) )
?>
In above "users" is table name and Fields are : address and first name.
Reference : http://codex.wordpress.org/Function_Reference/wpdb_Class#INSERT_rows

Resources