day 42

  • Dashboard widgets
  • Adding widget
  • Rewrite API intro

Dashboard Widgets

By default there are some widgets on the dashboard like welcome , at a glance , activity , site health etc.

Like almost everything else in WordPress, the dashboard is also extensible. We can add our own widgets and display them in the dashboard.

Widgets are basically meta boxes that we can display info into or collect info from. Like a widget that gives info of site views etc.

How to add new widgets?

The dashboard widget API provides us with a function wp_add_dashboard_widget(), Using it we can add our own widget in the dashboard.

I have created this widget that fetches some quotes from the endpoint https://type.fit/api/quotes , then randomly generated an index and displays the quote in the dashboard widget.

Below is the code I used for this:-

public function __construct() {
		add_action('wp_dashboard_setup', array($this, 'register_dashboard_widgets'));
	}

	public function register_dashboard_widgets(){
		wp_add_dashboard_widget('daily_quote', 'Inspirational Quote', array($this, 'daily_quote_widget_callback'));
	}

public function daily_quote_widget_callback(){
        $url = 'https://type.fit/api/quotes';
        $response = wp_remote_get($url, array('headers' => array('Accept' => 'application/json')));
        $body = json_decode(wp_remote_retrieve_body($response));
		$random_index = random_int(0, count($body)-1);
		$quote = '<h1>' . esc_html($body[$random_index]->text) .'</h1>' ;
		echo $quote;
    }

Rewrite API intro

The wordpress rewrite api allows us to specifiy new rewrite rules. It has below functions:-

  • add_rewrite_rule()
  • add_rewrite_tag()
  • add_rewrite_endpoint()

Rewriting is used so we can create pretty links like /best-movies-2023 which will be then mapped with the actual resource.

This same post you can access using https://pratiklondhe.wordpress.com/?p=799 but it doesn’t look good and search engines also penalize us for this url. We can use the rewrite rules for that so the same post can be accessed at https://pratiklondhe.wordpress.com/2023/09/06/day-42/


Comments

Leave a Reply

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