day 27

  • Flush rewrite in plugin activation
  • WP_Query and the_wp_query

Why putting flush_rewrite in plugin activation doesn’t work?

  • We are using init hook to register the CPT
  • But the i nit hook is called at very late in the core load

Then how to do it?

  • Flush them on init hook ?
    • Not the best way, it will flush it at every load.
  • Register the CPT in activation function also, and then flush
    • Good choice as activation will be called only once!

WP_Query , how the global query works

  • We rarely have to make a custom WP_Query as the wordpress makes one for us.
  • It parses the request url, and fire the query accordingly.
  • Should we overwrite it ?
    • it is safe to use new WP_Query and the loop to temporarily overwrite the global query
    • use reset_post_data() or reset_query() function to reset it though.
  • Maybe you don’t want to create a new query, in my case I just wanted to limit the number of posts per page on the archive page
  • Is it a good idea to create a custom query for this?
  • No, We can do this using the hook pre_get_posts

Hers’s how i did it

public function limit_movies_per_page( $query ) {
		if ( is_post_type_archive( 'rt-movie' ) && $query->is_main_query() ) {
			$query->set( 'posts_per_page', $this->movies_per_page );
		}
	}

And in the constructor I hooked into the pre_get_posts

		add_action( 'pre_get_posts', [ $this, 'limit_movies_per_page' ] );

$this->movies_per_page is a member of my class that can be set to a different value by calling setter.

1. Can we create a child theme of the existing child theme?

  • No
  • Well I tried it and it didn’t work.

I might have done something wrong, please suggest if you see in mistake in code. I am using the rtdating theme as parent for this.

Comments

Leave a Reply

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