getting error on wpdb line wordpress - 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.
}

Related

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".

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

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

$wp_query and WP_QUERY - same arguments, different results

I spend this whole day trying to figure out a problem with a combination of a custom query and custom post types. This is my last resort...
The setting
I wrote a plugin that introduces some custom post types to my WordPress. To display them in the main query I hooked them into the query like this:
function add_cpt_to_query( $query ) {
*some code...*
// add custom post types to query
if ( !( is_admin() || is_post_type_archive() || is_page() ) && $query->is_main_query() ) {
$query->set('post_type', array_merge( array('post'), $cpt ) );
}
}
add_action('pre_get_posts','add_cpt_to_query');
In my theme on the other hand I setup ajax pagination like this:
function setup_pagination() {
global $wp_query;
$max_pages = $wp_query->max_num_pages;
$current_page = ( $wp_query->paged > 1 ) ? $wp_query->paged : 1;
$ajaxurl = admin_url( 'admin-ajax.php' );
wp_register_script( 'ajax-pagination', get_template_directory_uri() .'/js/dummy.js', array('jquery'), '', true);
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
'max_pages' => $max_pages,
'current_page' => $current_page,
'ajaxurl' => $ajaxurl,
'query_vars' => $wp_query->query_vars
));
wp_enqueue_script( 'ajax-pagination' );
}
add_action( 'wp_enqueue_scripts', 'setup_pagination' );
function pagination() {
$query = $_POST['query_vars'];
$query['paged'] = $_POST['next_page'];
/*
$query = array(
'paged' => 2,
'post_type' => array('post', 'custom_post_type_1', 'custom_post_type_2' )
);
*/
$posts = new WP_Query( $query );
$GLOBALS['wp_query'] = $posts;
// Start the loop.
while ( have_posts() ) : the_post();
?>
*some code...*
<?php endwhile;
die();
}
add_action( 'wp_ajax_nopriv_ajax_pagination', 'pagination' );
add_action( 'wp_ajax_ajax_pagination', 'pagination' );
and the script part:
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
next_page: parseInt(ajaxpagination.current_page) + 1
}
});
The problem
If I pass the query_vars array I get from $wp_query with the altered 'paged' value back to WP_QUERY, it returns the wrong set of posts. It looks like, that WP_QUERY does not account for the cpts in the loop. Though these cpts are mentioned in the 'post_type' of the query_vars array and thereby passed along to the new WP_QUERY.
When I manually set 'post_type' and only pass this argument, it works as intended. The aspect that blows my mind is, that the resulting query_vars used in the ajax call to WP_QUERY are exactly the same, but only when I manually set 'post_type' the pagination works as it should.
I dont know if this was a somewhat understandable explanation, but I'm thankful for every idea that could help me out. Big THX!
Ok... I got it now.
I made a mistake in wp_localize_script(). The query_vars should be a json-string, I on the other hand just passed the array itself. My code above has to be altered in two lines:
function mk_setup_pagination() {
...
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
...
'query_vars' => json_encode($wp_query->query_vars) <- convert to json-string
));
...
}
function mk_pagination() {
$query = json_decode( stripslashes( $_POST['query_vars'] ) , true); <- convert json-string to array
...
Works like a charm now. :)
btw: the code is based on a tutorial by wpmudev.org: Loading WordPress Posts Dynamically With AJAX

Get attachment ID by file path in WordPress

I know the path of the file and I like to get the attachment ID.
There's a function wp_get_attachment_url() which requires the ID to get the URL but I need it reverse (with path not URL though)
UPDATE: since wp 4.0.0 there's a new function that could do the job. I didn't tested it yet, but it's this:
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
OLD ANSWER: so far, the best solution I've found out there, is the following:
https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/
I think It's the best for 2 reasons:
It does some integrity checks
[important!] it's domain-agnostic. This makes for safe site moving. To me, this is a key feature.
I used this cool snipped by pippinsplugins.com
Add this function in your functions.php file
// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
Then use this code in your page or template to store / print / use the ID:
// set the image url
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';
// store the image ID in a var
$image_id = pippin_get_image_id($image_url);
// print the id
echo $image_id;
Original post here: https://pippinsplugins.com/retrieve-attachment-id-from-image-url/
Hope ti helps ;)
Francesco
Try attachment_url_to_postid function.
$rm_image_id = attachment_url_to_postid( 'http://example.com/wp-content/uploads/2016/05/castle-old.jpg' );
echo $rm_image_id;
More details
None of the other answers here appear to work properly or reliably for a file path. The answer using Pippin's function also is flawed, and doesn't really do things "the WordPress Way".
This function will support either a path OR a url, and relies on the built-in WordPress function attachment_url_to_postid to do the final processing properly:
/**
* Find the post ID for a file PATH or URL
*
* #param string $path
*
* #return int
*/
function find_post_id_from_path( $path ) {
// detect if is a media resize, and strip resize portion of file name
if ( preg_match( '/(-\d{1,4}x\d{1,4})\.(jpg|jpeg|png|gif)$/i', $path, $matches ) ) {
$path = str_ireplace( $matches[1], '', $path );
}
// process and include the year / month folders so WP function below finds properly
if ( preg_match( '/uploads\/(\d{1,4}\/)?(\d{1,2}\/)?(.+)$/i', $path, $matches ) ) {
unset( $matches[0] );
$path = implode( '', $matches );
}
// at this point, $path contains the year/month/file name (without resize info)
// call WP native function to find post ID properly
return attachment_url_to_postid( $path );
}
Cropped URLs
None of the previous answers supported ID lookup on attachment URLs that contain a crop.
e.g: /uploads/2018/02/my-image-300x250.jpg v.s. /uploads/2018/02/my-image.jpg
Solution
Micah at WP Scholar wrote a blog post and uploaded the code to this Gist. It handles both original and cropped URL lookup.
I included the code below as a reference but, if you find useful, I'd encourage you to leave a comment on his post or star the gist.
/**
* Get an attachment ID given a URL.
*
* #param string $url
*
* #return int Attachment ID on success, 0 on failure
*/
function get_attachment_id( $url ) {
$attachment_id = 0;
$dir = wp_upload_dir();
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { // Is URL in uploads directory?
$file = basename( $url );
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
'key' => '_wp_attachment_metadata',
),
)
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ) {
foreach ( $query->posts as $post_id ) {
$meta = wp_get_attachment_metadata( $post_id );
$original_file = basename( $meta['file'] );
$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' );
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
$attachment_id = $post_id;
break;
}
}
}
}
return $attachment_id;
}
Another pro with this solution is that we leverage the WP_Query class instead of making a direct SQL query to DB.
Find IDs for resized images, PDFs and more
Like GFargo pointed out, most of the answers assume the attachment is an image. Also attachment_url_to_postid assumes a url (not a file path).
I believe this better answers the actual question when supplied a file (with path):
function getAttachmentIDFromFile($filepath)
{
$file = basename($filepath);
$query_args = array(
'post_status' => 'any',
'post_type' => 'attachment',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
),
)
);
$query = new WP_Query($query_args);
if ($query->have_posts()) {
return $query->posts[0]; //assume the first is correct; or process further if you need
}
return 0;
}
Based on the answer from #FrancescoCarlucci I could do some improvements.
Sometimes, for example when you edit an image in WordPress, it creates a copy from the original and adds the copys upload path as post meta (key _wp_attached_file) which is not respected by the answer.
Here the refined query that includes these edits:
function jfw_get_image_id($file_url) {
$file_path = ltrim(str_replace(wp_upload_dir()['baseurl'], '', $file_url), '/');
global $wpdb;
$statement = $wpdb->prepare("SELECT `ID` FROM `wp_posts` AS posts JOIN `wp_postmeta` AS meta on meta.`post_id`=posts.`ID` WHERE posts.`guid`='%s' OR (meta.`meta_key`='_wp_attached_file' AND meta.`meta_value` LIKE '%%%s');",
$file_url,
$file_path);
$attachment = $wpdb->get_col($statement);
if (count($attachment) < 1) {
return false;
}
return $attachment[0];
}

Wordpress shortcode name as an Attribute

I was wondering if possible to setup a shortcode and have the name of the shortcode also work as an attribute. How I have mine currently setup is like so
add_shortcode('tooltip', 'tooltip');
function tooltip( $atts $content = null) {
array(
'type' => '',
);
So when someone in wordpress uses the shortcode you type in
[tooltip type="fruit"]Item Name[/tooltip]
Although I was wondering is it possible to just use the name of the shortcode as a atts so I can short it a little bit and have it look like this
[tooltip="fruit"]Item Name[/tooltip]
So pretty much cut out the type attribute and use the name of the shortcode tooltip as an attribute instead.
Nope, what you're proposing isn't possible. It may be shorter but in my opinion it would be confusing so I don't see it ever being something that's made possible short of you building the functionality yourself.
You have to use first item in $atts array, ($atts[0]) when using shortcode tag as attribute.
Working example:
<?php
add_shortcode('tooltip', 'tooltip');
function tooltip(Array $atts = array(), $content = null, $tag = null) {
$args = shortcode_atts(array( 0 => null ), $atts);
$args['type'] = trim($args[0], '"=');
unset($args[0]);
extract($args);
// Your code starts here ...
$output = array(
'$type' => $type,
'$content' => $content
);
$output = '<pre>' . print_r($output, true) . '</pre>';
return $output;
}
Please replace everything after // Your code starts here ...
Executing example:
[tooltip="fruit"]Item Name[/tooltip]
will return:
<pre>Array
(
[$type] => fruit
[$content] => Item Name
)
</pre>

Resources