rtCamp notes, day 35 of undefined

WP_Query

WordPress provides us a default way to interact with the posts programatically -> We can use the default $wp_db variable to run SQL queries but it is not recommended because WP_Query gives us the caching ability as well by default.

WordPress iteself uses WP_Query to fetch posts.

How to use WP_Query?

$arguments = array( 'post_type' => 'movie' );
$result = new WP_Query( $arguments );

This is how we execute a WP_Query -> the $result will retunr a WP_Query object which contains different properties ->
Our result would be under the posts property

Different properties of WP_Query:

  • query -> It holds the query information we have sent to the WP_Query
  • query_vars -> It builds up the WP_Query variables in the object.
  • tax_query -> Creates and holds the tax_query object
  • meta_query -> Creates and holds the meta_query object
  • request -> Holds the SQL query being executed
  • posts -> Holds the result 
  • Other values like is_single, is_page, template flags
  • found_posts -> number of posts found in current request

Q: How you can fetch posts with given category or tag or custom taxonomy term?
A: We can use the tax_query for this, we can create a custom query like

'tax_query' => array(
       array(
           'relation' => 'AND',
           array(
               'taxonomy' => 'mlb_career',
               'field' => 'slug',
               'terms' => 'director',
           ),
       ),
   ),

Q: What is pre_get_posts hook? Give some use cases.
A: pre_get_posts -> This hook is created after the parse_query [ query variable object is created ] <- Before the actual query is run This would provide us a gateway to modify the final query before it is executed and change some variables to alter the final result. For example, if we want our main page to display other post_types we can use this hook and change the query variable $wp_query->set( ‘post_type’, array( ‘page’) );

Somethings about optimizing the Query

We should not add dynamic parameters in the query where we can proceed with a better optimized query
We must always look how the build up SQL query would become when assigning variables.
We should try to keep the final query less changed as it would result in the cache key being different as the query result are cached on the basis of the hash of the final SQL query and it would change if we use dynamic ids or parameters.

For example we can refer to this discussions question -> https://github.com/rtCamp/training/discussions/104

A code explanation for reference from there which results in a optimized query without disturbing the execution pattern:

Q. Write a WP Query for the sidebar "Other Posts by Post 1 author", that meets following criteria:

$exclude         = array( get_the_ID(), ...$suggested_posts ); // $suggested_posts contains post id of suggested posts in current page
$args            = array(
	'posts_per_page' => 7,
	'author'         => get_the_author_meta( 'ID' ),
	'post_type'      => 'post',
	'post_status'    => 'publish',
	'post__not_in'   => get_option( 'sticky_posts' ),
	'orderby'        => 'date',
	'order'          => 'DESC',
);

$result = new WP_Query( $args );
Fetching 7 posts as 3 + 1 + 3 where, 3 -> Number of posts we need, 1 -> The current post, 3 -> Number of suggested posts. 3 would be the result we need and 4 can be excluded results

Loop through the posts in the result
If post is in $exclude array, skip the post.
Compare the post date in php and check if it is under 1 month, break loop if its not.
If three posts are printed, break the loop.

Metadata API

WordPress provides us with the metadata api to store extra information about different fields in the database -> for example in our movie_library -> our post is movie and meta information about it would the director or actor in that -> that is stored in wp_postmeta.

This feature was possible with the functionality of metadata APIs

Functions for fetching metadata:

get_post_meta() -> for posts

get_term_meta() -> for terms

get_comment_meta() -> for comments

get_user_meta() -> for users

All of these functions internally use the function get_metadata( $meta_type )
Where meta_type is post, term, comment, user

For example: get_post_meta -> Post ID is 79 -> meta_key is actors

get_post_meta( 79, ‘actors’ ); -> This would return array with all the entries
get_post_meta( 79, ‘actors’, false ); -> This would return only the first entry

Q: How can I get all the metadata of given object/post?

A: get_post_meta( 79 ); -> This would return all the metadata available for post id 79

Shortcode API

Shortcode is a kind of shortcut, we can term it as a variable for understanding -> It is a variable with data which we want to display somewhere -> so we can directly use this variable to get our code here.

There’s another thing in shortcode that we can pass content and attributes to it.
Lets see how we can do that.

First of all to create a shortcode we can use the

add_shortcode( 'shortcode_tag', 'callback_function' );

For example we are creating a shortcode name test_hehe

add_shortcode( 'test_hehe', 'test_hehe_callback' );

function test_hehe_callback( $atts, $content ) {

}

Here the attributes will be the attributed we provide to the shortcode :

[test_hehe title="Some title"]

Here the attribute will be an array with title => Some title

The content would be what we provide inside the shortcode

[test_hehe title="Some title"]This is the content[/test_hehe]

We would get it in $content -> This is the content

Q: Why we need to return output instead of echo in shortcode callback function?
A: Because it is possible that if we echo instead of returning it would print the data at the wrong time as the shortcodes are processed before the actual data is printed.

Q: When we call add_shortcode() function, where shortcode details saved?
A: They are stored under the global variable $shortcode_tags

Leave a Reply

Your email address will not be published. Required fields are marked *