Plugin info custom replacement code

📅 Published on

📝 Last updated

Documentation

»

Code Samples

»

Plugin info custom replacement code

Adds a custom replacement code that allows developers to showcase stats from their WordPress.org plugin listing.

<?php

add_action( 'groundhogg/replacements/init', function ( \Groundhogg\Replacements $replacements ){

	// usage would look like
	// `{plugin_info.slug="groundhogg" field="downloaded"}`
	$replacements->add( 'plugin_info', function ( $args ){

		$args = shortcode_parse_atts( $args );
		$args = wp_parse_args( $args, [
			'slug' => '',
			'field' => 'active_installs'
		] );

		if ( empty( $args['slug'] ) ) {
			return 'specific a slug';
		}

		if ( ! function_exists( 'plugins_api' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
		}

		$root_field = explode( '.', $args['field'] )[0];

		$result = plugins_api( 'plugin_information', [
			'slug' => $args['slug'],
			'fields' => [
				$root_field => true // make sure the root field is in the request
			]
		] );

		if ( is_wp_error( $result ) ){
			return 'Failed to fetch plugin info.';
		}

		// this allows us to use field like "ratings.0.whatever"
		$return = get_by_dotn( $result, $args['field'] );

		if ( in_array( $args['field'], [ 'active_installs', 'downloaded', 'num_ratings' ] )){
			$return = number_format( $return );
		}

		return $return;

	}, 'Fetch plugin info from WordPress.org', 'Plugin info', 'site', 'slug="groundhogg" field="active_installs"' );

} );

if ( ! function_exists( 'get_by_dotn' ) ){

	/**
	 * Get a value from an object or array using dot notation instead of direct key access
	 *
	 * @param $data array|object
	 * @param $path string
	 * @param $default mixed
	 *
	 * @return mixed|null
	 */
	function get_by_dotn($data, $path, $default = null) {
		if ($data === null || $path === '') {
			return $default;
		}

		$keys = explode('.', $path);

		foreach ($keys as $key) {
			// convert purely numeric keys to int for array index access
			if (ctype_digit($key)) {
				$key = (int) $key;
			}

			if (is_array($data) && array_key_exists($key, $data)) {
				$data = $data[$key];
			} elseif (is_object($data) && (isset($data->$key) || property_exists($data, $key))) {
				$data = $data->$key;
			} else {
				return $default;
			}
		}

		return $data;
	}

}

Was this helpful?

Let us know if this document answered your question. That’s the only way we can improve.