Wordpress : Get posts but not the full WP_Post object - wordpress

Does anyone know if there is a way in Wordpress's core functions to retrieve posts but not the full WP_Post object ? For example let's say only the post title and permalink ?
The full post object is very big and the standard queries quickly become slow as your site grows.
There is a return argument in the standard WP_Query :
https://developer.wordpress.org/reference/classes/wp_query/#return-fields-parameter
But this only provides few options and you can't really retrieve what you want.
Thanks for your help

You can use the get_results() function. You can use simple SQL statements like SELECT x,y,z,... to get only the columns you need from a table of your choice.
Simple example:
function get_players() {
global $wpdb;
return $wpdb->get_results("SELECT a.id, a_name ROM player a");
}

The docs say that only 3 options are supported, and none of them allow an ad-hoc selection of fields. To do something more custom, you'd probably need to use the wpdb class

The most appropriate solution I found to avoid big requests is to use the WPGraphQL plugin.
It allows you to make GraphQL API calls on your Wordpress database, and directly specify in your request what you want in return. The server appears to be way less overloaded.
In my case it is very appropriate, but if you want to stay in a classic PHP wordpress approach, the get_results() function is working too as said in the other answers.

Related

Object storage alternatives in Wordpress

so I am developing a Quiz plugin for Wordpress.
I have defined a shortcode which is replaced by my html, and I also have enqueued javascript and styles. So far all good.
At this point, I want to visualize each question using ajax and jquery. My quiz has some sophisticated logic - some quiz question-trees can fall off depending on the answers and on the settings of the plugin.
Thus, I am trying to achieve a solution, where javascript uses ajax call to fetch one next question at a time. On the backend, I created controller-class which is responsible for handling the logic and outputing the fetched-question's html code. Thus, whenever a starts the quiz, the backend will generate some controller object.
My question is, how can i store multiple controller objects persistently? So that i can get the current use's progress.
To do that, i need some kind of persistent storage for all the running quizzes. Here, as far as I understand, i have 2 alternatives: put serialized controller objects into the database, or use some sort of WP_CACHE.
So now I have some questions:
1) Is there any other alternative for storing a set of objects in Wordpress?
2) Is the approach I am using for the quiz implementation - okay? Like maybe I am doing something unconventional?
3) Is having ajax calls communicating to the DB a good idea?
* Edit *
Thanks to #cabrerahector, who pointed out the set_transient() wordpress API.
I was able to store an object in the db with the following code:
...
$base64_serial = base64_encode(serialize($report_controller));
set_transient($report_id, $base64_serial, 60*60*12);
...
and then retreive the object with the following code:
...
$report_controller = unserialize(base64_decode( get_transient( $_GET['report_id'] )));
...
I know it's kind of hacky, but does anybody know a better way? Please don't tell me to create an array with all fields of the class...

Algolia - WordPress - how can I get the actual query into JS variable to work with it further in the hits template?

I would like to do some interesting stuff with the hits that are being displayed based on the search query that user is not only typing into search box but actually filtering using the instant search filters. I have filter based on hierarchical events_location taxonomy. Based on what user selected I would get the info in JS variable that I can then further use to do other operations in the hits div, specifically on each hit card.
So my URL when searching updates like this:
/what-to-see/?q=&idx=sdbeta_posts_events&p=0&hFR%5Btaxonomies_hierarchical.events_calendar.lvl0%5D%5B0%5D=JUL%204&hFR%5Btaxonomies_hierarchical.events_category.lvl0%5D%5B0%5D=All&hFR%5Btaxonomies_hierarchical.events_locations.lvl0%5D%5B0%5D=Paddock%20Stage
I could potentially take the URL and extract the data from it, but I am sure there is more elegant way of working with the query.
In InstantSearch.js, the state is managed by another library called the algoliasearch-helper. Through this library you can read and write the search parameters.
The cleanest to access the helper is to build a custom widget, which is a plain object with lifecycle hooks (initial rendering and the other renderings). You can read more about custom widgets there.
Once you've accessed the helper, you can read and write with the helper API.
This can be found under search.searchParameters
So:
console.log(search.searchParameters);
Will give you whole object that you can then work with.
There is however one issue with this and that is that it works only on initial load. I was unable to make this work or get any data after starting to selecting categories. So if anyone knows how to use this so it updates after each selection please comment bellow.

using module_invoke_all to submit a form question

here is more detailed explanation:
i am using the ubercart module with the file download feature module (the uc_file module ).
i have created a product class (which is a new content-type as far as the drupal system) and add a cck file field to it.
what i want to achive is the following behavior:
once a user saves a new node of my product class, i want the uploaded file to be added as a file download feature to the product class automatically.
i know i can hack the function uc_file_feature_form_submit($form, &$form_state), do what it does in my module code, but i rather ivoke it since i'll have easier life with future changes to the uc_file module (since i am calling it's function, i dont care if it will change in the future).
so, to invoke the uc_file_feature_form_submit function i need to build fake $form, &$form_state parameters, i know i can print_r those arrays, and build it from there, the thing is that there are a lot of data in those arrays that is not mandatory, i was wondering what are those mandatory fields that i have to build on my own.
thank you...
Short answer: Look at the submit function you are trying to invoke. The form values that it's using are the ones you need.
Long answer . . . need more info before I can give a better answer.
You can use drupal_execute() to programatically execute a form. I am not sure if it works with files though.

How to Override Drupal Views Query?

How can I replace a Views 3 query with a custom SQL query in code?
From what I understand, you can use hook_views_query_alter to modify the query. I would assume you could also use it to replace the query. Here are a couple hook_views_query_alter examples, to get you started:
Using Hook Views Query Alter
Alter a View query to add a WHERE clause with OR group operator.
This might no longer be pertinent to you, but there's what seems to be a very useful discussion on Drupal.org at Implementing custom SQL query for Views / Filters that looks like it's answering my similar question.
In particular, the initial poster has suggested attaching to hook views_views_pre_execute, which someone else mentioned can be put into a custom module like:
function mymodulename_views_pre_execute(&$view) {
if($view->name=="groups_list2") {
// ...
$view->build_info['query'] = "SELECT node.nid AS nid ".
"FROM node WHERE node.type='%s'"; // wrapped for legibility
}
}
And another poster mentioned mySQL Views and Table Wizard (direct link), though they did mention it's worth bearing in mind this article about mySQL Views performance
It's definitely worth reading the whole thread on Drupal.org, though, as I found it really useful; I hope someone else does too.
Update: Indeed, this is precisely what we're now doing — overriding views_views_pre_execute in a custom module to inject new SQL before it gets to the database. I had opened a similar (but more specific) question on Drupal.SE at Slow query with large dataset in Drupal views — better to process in SQL or PHP?, which you might find useful.
If you want to execute custom SQL (that Views cannot generate), for example computed fields, or complicated SQL joins, then what you are after is a custom module.
See drupal for a guide to get you started

How to add variable filters to Drupal 6 views via URL?

I'm currently using Drupal Views 2 to build custom views. This works fine so far, if there wasn't a feature needed: One should be able to filter the results by different fields via URL, in the form of:
http://domain/node/M/[key]:[value],[key2]:[value2],...,[keyN]:[valueN]
The key names are fixed and may not be altered.
I tried hooking hook_views_query_alter() and hook_views_pre_render() to generalize this for all views, evaluating the given filterset, but to no satisfying end, as i could not get hold of the query used to build the view (I could not alter it in the proper way, as i do not know the field names in the query).
The question is, if there is a nicer way to implement such a filterset.
thanks in advance,
flo
Looking at the comments you seem to want not only url arguments but url arguments in a custom format.
I would firstly urge you to drop your format and use the standard views argument format, this will be more standards compliant and save you a lot of headache.
If you want to use that paticular format you are going to have to write some custom code in a module.
Register a callback using hook_menu().
In that callback use arg() and decode your arguments.
Pass the arguments to views_embed_view(). as shown here

Resources