I am trying to build a query that will help me rank SearchWP search results by total_sales (in a WooCommerce shop).
SearchWP has a simple filter that helps injecting additional sql into the search algorithm and adding weight as desired.
The following example lets recent posts rank higher:
$sql .= " + ( IF( UNIX_TIMESTAMP( {$wpdb->prefix}posts.post_date ) > UNIX_TIMESTAMP( {$time_ago} ), {$additional_weight}, 0 ) )";
So I tried to do the same thing by using the total_sales column from the postmeta table to increase the weight of search results, but it doesn't work.
$sql .= " + {$wpdb->prefix}postmeta.total_sales";
Obviously I wonder what the solution is.
But I also want to know a way how to build and test such a $wpdb query successfully myself. A link to a good tutorial would be appreciated.
I found the solution by following this SearchWP documentation. It is another filter provided by the SearchWP plugin: https://searchwp.com/docs/kb/using-custom-field-prioritize-search-results/
Simply drop both filters into functions.php and change the line
$my_meta_key = 'my_search_priority';
to
$my_meta_key = 'total_sales';
It works like a charm
Related
I am trying to diedump the query on my index screen using this line of code:
dd(DB::table('members')->where('name', '=', 'Tycho')->toSql());
Now the problem is that when I am displaying the query on my screen I get this:
"select * from `members` where `name` = ?"
My final goal of these lines of code is that I can save offline queries and execute them when the application is online. Unless someone has a solution for this, I'll have to save the queries in a database.
You are seeing the ? placeholders as Laravel uses Prepared Statements.
See Ijas Ameenudeen's answer on another SO question which details how to add a toRawSql() macro on the Eloquent builder which will replace the placeholders with the bindings that you supplied to the original query.
This is because you are using the toSql method, you can use the getBindings method to get the values / bindings.
oneliner:
$query = DB::table('members')->where('name', '=', 'Tycho')->toSql();
// will give the raw query with bindings.
$sqlWithBindings = str_replace_array('?', $query->getBindings(), $query->toSql());
You can try this:
DB::enableQueryLog();
DB::table('members')->where('name', '=', 'Tycho')->get();
echo "<pre>";
print_r(DB::getQueryLog());
I'm working with vcharts in Joomla and trying tom implement charts based on who is logged in. Sadly vcharts only allows me to use SQL for queries and not PHP so How will I get the session ID then.
Based on the SO question Variables added to vchart joomla sql query not picked up (that exposes a relevant portion of the vcharts manual which joomla users must ordinarily pay to see...) it seems the placeholder that you can use in your SQL is:
{loggedinuserid}
So, you might write something like
SELECT * FROM #__users WHERE id = {loggedinuserid}
Of course this is just a guess because I've never used vcharts, nor have I seen the actual docs.
If it doesn't like the #__ prefix placeholder, then I guess you'll need to manually replace it like this:
SELECT * FROM lmnop_users WHERE id = {loggedinuserid}
All this said, I have had some experience with the Plotalot extension and it's pretty good with great documentation.
I find this approach: with joomla api
<?php
$link = mysqli_connect("localhost", "joomla_usr", "geheim", "joomla_db");
define('_JEXEC', 1);
define('JPATH_BASE', dirname(__FILE__));
define('DS', DIRECTORY_SEPARATOR);
require_once(JPATH_BASE . DS . 'includes' . DS . 'defines.php');
require_once(JPATH_BASE . DS . 'includes' . DS . 'framework.php');
require('libraries/joomla/factory.php');
$mainframe = JFactory::getApplication('site');
$mainframe->initialise();
$session = JFactory::getSession();
$query_user = "SELECT name, username, email FROM joomla_users WHERE id=(SELECT userid FROM joomla_session WHERE session_id='" . $session->getId() . "')";
$result_user = mysqli_query($link, $query_user);
$row_user = mysqli_fetch_array($result_user);
?>
Maybe you can use the query direct to access the mysql database from your Platform. Or embed PHP in any way.
I have a list of Products with a field called 'Title' and I have been trying to get a list of initial letters with not much luck. The closes I have is the following that dosn't work as 'Distinct' fails to work.
atoz = Product.objects.all().only('title').extra(select={'letter': "UPPER(SUBSTR(title,1,1))"}).distinct('letter')
I must be going wrong somewhere,
I hope someone can help.
You can get it in python after the queryset got in, which is trivial:
products = Project.objects.values_list('title', flat=True).distinct()
atoz = set([i[0] for i in products])
If you are using mysql, I found another answer useful, albeit using sql(django execute sql directly):
SELECT DISTINCT LEFT(title, 1) FROM product;
The best answer I could come up with, which isn't 100% ideal as it requires post processing is this.
atoz = sorted(set(Product.objects.all().extra(select={'letter': "UPPER(SUBSTR(title,1,1))"}).values_list('letter', flat=True)))
I have two tables; dashboard_map_items and device_data_current. in dashboard_map_items I have two field, id and command and in device_data_current I have three field id, commands, current_value. Based on the id and commands in my dashboard_map_items I need get the current_data from device_data_current.
Now I dont know where to start. Before I was able to hard-code the id and command and fetch the current_data from device_data_current but this is not working for me anymore, because the id and commands will be changed in the future.
$currentValues = DeviceDataCurrent::where('map_id', 1)
->where('system_id', $system_id)
->where('command', 1)->where('id', 64)
->orderby('datetime', 'DESC')->take(1)->get();
this is what i was doing to get the data. if it would help i am using laravel 4.2 framework but i dont know it has anything to do with laravel. it is pure php.
Any help would be appreciated.
I found the solution
$currentValues = DashboardMapItem::where('system_id', $system_id)
->select()->join('device_data_current', function($join){
$join->on('device_data_current.id', '=', 'dashboard_map_items.device_id');
$join->on('device_data_current.command', '=', 'dashboard_map_items.command');
})
->get();
dd($currentValues->toArray());
I am a newbie with WordPress and am trying to modify the standard SQL call for for custom field data posts to limit by category. Here is what I am basing my attempts on, but i just can't figure out how to filter for category 15.
$querystr = "SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = 'priority'
AND wposts.post_type = 'post'
AND wposts.post_status = 'publish'
AND wposts.
ORDER BY wpostmeta.meta_value ASC";
Use query_posts right before the loop like this :
query_posts('meta_key=priority&order=ASC&orderby=meta_value&cat=15&post_type=post&post_status=publish');
meta_key=priority -> Show posts associated with a certain (priority) custom field.
order=ASC -> self explanatory
orderby=meta_value -> Sort retrieved posts by the meta_value field
cat=15 -> Display posts that have this category (and any children of that category), using category id 15
Aditionaly you could use cat=15,4 to show posts in categoryes 15 and 4 , or category_name=staff,test to show posts in staff and test categories .
More info about using query_posts , usualy you can retrive just about any kind of posts building the query using query_posts . Use plain SQL when you can't use query_posts for whatever reasons .
Read the section Query based on Custom Field and Category in the WordPress Codex article Displaying Posts Using a Custom Select Query. Try googling it next time!
Edit: As poelinca pointed out, consider using query_posts() if you have no highly customized or complex queries to pull off.