I'm trying to resolve the following -
$result = $wpdb->get_results( "SELECT * FROM table name WHERE ID = 1" );
foreach ( $result as $print ) {
print '<div class = "facebook">facebook link</div>';
}
This should display the facebook link and link towards the correct page but unfortunately doesn't work as it removes the link.
I hope i'm not doing this completely wrong as I used a foreach loop as I will be adding other social media.
You have two choices:
Use get_results() as you did:
$results = $wpdb->get_results( "SELECT * FROM $wpdb->table_name WHERE id = 1");
foreach ( $results as $result )
{ echo $result->column_name }
OR
Use get_rows():
$mylink = $wpdb->get_row( "SELECT * FROM $wpdb->table_name WHERE link_id = 10", ARRAY_A );
echo $mylink['column_name'];
You can see more here: https://codex.wordpress.org/Class_Reference/wpdb
The link is just not visible because your a tag doesn't contain any text.
Change this:
<div class = "facebook">facebook link</div>
to this:
<div class = "facebook">facebook link</div>
(move the text inside of the a tag).
Have you used global $wpdb ?
Use it like this:
global $wpdb;
$result = $wpdb->get_results( 'SELECT * FROM $wpdb->table name WHERE ID = 1');
Check this official doc for more info.
Related
Hi I am using learndash Wordpress plugin. I want to get the data related to a user tht how many courses he is enrolled in and how many has he completed. Is there a way to check this? does learndash provide any solution for this or should I query data myself?
Any help is appreciated. Thanks in advance.
Please ask for any more details if you want.
You can use the following to get all course ID's the current user is currently enrolled to:
learndash_user_get_enrolled_courses(get_current_user_id())
I found that all is stored inside the table learndash_user_activity and you can query that table to get user stats.
For example I get the list of the in-progress users for a given course with the following query:
public static function get_inprogress_users_for_course( $course_id )
{
global $wpdb;
if( empty( $course_id ) ) return [];
$results = $wpdb->get_results( "SELECT `user_id` FROM `" . $wpdb->prefix . "learndash_user_activity` "
."WHERE `course_id` = '" . intval( $course_id ) . "' "
."AND `activity_type` = 'lesson' "
."GROUP BY `user_id`" );
return $results;
}
In the same way, you can get all the IDs of the users ever enrolled to a course changing activity_type from 'lesson' to 'course' in the query, and if you want to only get enrolled course by a user, you can add the user_id to the query, like this:
public static function get_courses_for_user( $user_id )
{
global $wpdb;
if( empty( $course_id ) ) return [];
$results = $wpdb->get_results( "SELECT * FROM `" . $wpdb->prefix . "learndash_user_activity` "
."WHERE `user_id` = '" . intval( $user_id ) . "' "
."AND `activity_type` = 'course' "
."GROUP BY `course_id`" );
return $results;
}
I know this is not exactly what you were searching for, but it could still be useful.
You can return anything using wp_query. Try this:
function wpso49370180_get_course_name($courseid) {
global $wpdb;
$user_id = the_author_meta( 'ID' ); //alt method below
$query_course = "SELECT post_title
FROM wp_posts
WHERE post_type = 'sfwd-courses'
AND post_status NOT IN ( 'trash','auto-draft','inherit' )
AND post_author='$user_id' LIMIT 10";
return $wpdb->get_var($query_course);
}
You will need to either know the user_id or get it from the post (sfwd-quiz, sfwd-course, sfwd-lesson) -see below.
The data you want can be all (*) You will have to do a meta_query if you want deeper data that is not in the post_type tables.
/**
* Gets the author of the specified post. Can also be used inside the loop
* to get the ID of the author of the current post, by not passing a post ID.
* Outside the loop you must pass a post ID.
*
* #param int $post_id ID of post
* #return int ID of post author
*/
function wpso49370180_get_author( $post_id = 0 ){
$post = get_post( $post_id );
return $post->post_author;
}
I'm trying to use the Wordpress built-in functions to search and retrieve one row of data and place it in a string, but I get "object of class stdclass could not be converted to string.." error.
Code I'm using is:
<?php
$zip = $_GET['z'];
//primary key is $zip
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM wp_main_placename_zip WHERE _Zip_Code = $zip");
$array = json_decode(json_encode($results), True);
echo $array[0];
echo $array[1];
echo $array[2];
//echo $results[1];
//echo $results[2];
?>
Thanks in advance!
The object to which you are printing is an object, in this case $array[0]; Return an object.. example
Error : http://codepad.org/iGbZcN6W
$code = '[{"id":2,"name":"Bob"},{"id":3,"name":"Maria"}]';
$parse = json_decode($code);
//"object of class stdclass could not be converted to string..
echo $parse[0];
//prints Bob
echo $parse[0]->name
If you want to print the entire object you can use print_r or var_dump
//prints object
echo var_dump($parse[0]);
check if http://codepad.org/EwIUbnIU
Revised code
$zip = $_GET['z'];
//primary key is $zip
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM wp_main_placename_zip WHERE _Zip_Code = $zip");
$array = json_decode(json_encode($results));
//_zip_code field
echo $array[0]->_Zip_Code;
// or all fields
var_dump($array[1]);
I hope I've helped :)
Revised code
$zip = $_GET['z'];
global $wpdb;
//Use get_row(); for single row
$results = $wpdb->get_row("SELECT * FROM wp_main_placename_zip WHERE _Zip_Code = $zip");
$objasarray = json_decode(json_encode($results));
$zipcode = $objasarray['_Zip_Code'];
I think this may help you :)
replace your query with
$results = $wpdb->get_results("SELECT * FROM wp_main_placename_zip WHERE _Zip_Code = '".$zip."'",ARRAY_N);
Got it sorted out. This works posting un case someone runs across the same issue:
$zip = $_GET['z'];
//primary key is $zip
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM wp_roof_main_placename_zip WHERE _Zip_Code = '".$zip."'",ARRAY_A);
$array = json_decode(json_encode($results));
echo $array[0]->_Zip_Code;
$zipcode = $array[0]->_Zip_Code;
echo $zipcode;
Thanks all, for your help!
-Brian
how i can get the users nice name in a function?
currently i got it with an avatar, but dont know hot to get the users nice name:
$table = $wpdb->prefix . "thumbsup_info";
$result = $wpdb->get_results("SELECT userid FROM $table WHERE postid = '$postid' LIMIT 10", ARRAY_A);
$total_user = $wpdb->num_rows;
for($i=0; $i <$total_user ; $i++)
{
$userid.= get_avatar($result[$i]['userid'],100);
}
return $userid;
Get the user object with the following line of code:
$user = get_user_by( 'id', $result[$i]['userid'] );
Then you can just access the property you need. To get the nicename for example you would use $user->data->user_nicename
I am trying to query the wordpress post_meta table by meta_value.
I would like to output all post_id's where the meta_value is = to _parent_product. Here is my code:
$posts = $wpdb->get_results("SELECT *, FROM $table WHERE meta_key='_parent_product' ");
foreach ( $posts as $post ){
$id = $post->post_id;
echo $id;
}
The above outputs nothing and im not quite sure why? Can anyone see anything wrong?
As stated in the comment,
There is a comma (,) behind SELECT *,. Therefor the given SQL is invalid and will fail to retrieve any results.
I'm sorting my posts alphabetically by Title, like so:
<?php
{
$posts = get_posts($query_string .
'&orderby=title&order=asc&posts_per_page=-1');
}
get_template_part( 'loop', 'category' );
?>
I'd like to exclude articles such as "the", "a", and "an" from the sort.
What would be the best way to accomplish this?
Thanks!
I don't know any simple way to do that but you can do this,
For achieving this you need to add a custom meta field to the post. Name it mytitle (say).
For the new posts you add, it is simple, you have to add your modified title(removing a, an, the from the title) in the mytitle custom field in the add posts page.
For old posts it is a bit tricky, you have to write a php code to retrieve the titles of the post remove 'a','an','the' from them using php preg_replace and add it to the postmeta table of your wordpress database using something like this:
<?php //inside loop
$query=INSERT INTO xyz_postmeta (post_id, meta_key, meta_value) VALUES ($postid, 'mytitle' $title);
$wpdb->query('$query'); ?>
where $postid is the post id inside the loop and $title is your modified title.
Now you have updated all the previous posts with custom mytitle field.
Now to display, you have to use a custom loop (not the loop included in the theme).
Here is how you can make a basic custom loop to display posts sorted in order of mytitle.
$querystr = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = 'mytitle'
AND wposts.post_type = 'post'
AND wposts.post_status = 'publish'
ORDER BY wpostmeta.meta_value ASC
";
Now you can execute the query by any means you want. Wordpres provides various methods to do so. Here's a link
For example you can do something like this
$pageposts = $wpdb->get_results($querystr, OBJECT);
foreach ( $pageposts as $pagepost )
{
echo $pagepost->post_title;
//do other stuff to display content, meta etc..
}
You can actually achieve this by manipulating the ORDERBY clause using the posts_orderby_request filter, and using TRIM to ignore articles "the", "a", and "an". Here's an example:
<?php
add_filter( 'posts_orderby_request', 'myproject_title_sort', 10, 2 );
/**
* Ignore opening articles when sorting by Title.
*
* #param string $orderby Order by parameter.
* #param WP_Query $query WP Query object.
*
* #return string
*/
function myproject_title_sort( $orderby, $query ) {
global $wpdb;
// Be sure to add a condition that matches your criteria (post type, archive, etc).
// In this example, we bail early if it's an Admin query, or not a main query.
if ( is_admin() || ! $query->is_main_query() ) {
return $orderby;
}
// This is another check to see if we're on a particular post type archive.
if ( ! $query->is_post_type_archive( 'my-post-type' ) ) {
return $orderby;
}
$title_col = $wpdb->posts . '.post_title';
// Check if we are sorting by post_title.
// You may need to use a separate `pre_get_posts` filter to sort by "title" if not already doing so.
if ( false === strpos( $orderby, $title_col ) ) {
return $orderby;
}
$ignore = "TRIM( LEADING 'the ' FROM LOWER( TRIM( LEADING 'a ' FROM LOWER( TRIM( LEADING 'an ' FROM LOWER( $title_col ) ) ) ) ) )";
$orderby = str_replace( $title_col, $ignore, $orderby );
return $orderby;
}