get_plugin_directory_path function for WordPress to get plugin directory path based on plugin header information

get_plugin_directory_path.php

<?php
if( ! function_exists( 'get_plugin_directory_path') ){

	/**
	 * Get Plugin's Directory Path
	 *
	 * Search for a plugin's directory path, based on configuration in the plugin's main plugin
	 * file.  By default if passed search value is a string, will search the `Name` value.  To
	 * search multiple values, or different value to match, pass as an array with key => value.
	 *
	 *
	 * @since @@version
	 *
	 * @param string|array $search         Value to find plugin based on `Name`, or an array with key => value pairs to match.
	 *                                     Search is case-insensitive, and will only return if all search values match.
	 * @param string|bool  $const          Constant value to pass and check first, before doing search.
	 *
	 * @param bool         $trailing_slash Whether or not to include trailing slash (default is false)
	 *
	 * @return bool|string Returns directory path to plugin if match found, otherwise FALSE if no match found.
	 */
	function get_plugin_directory_path( $search, $const = false, $trailing_slash = false ){

		if( file_exists( $const ) ){
			return $const;
		}

		if ( ! function_exists( 'get_plugins' ) )
			require_once ABSPATH . 'wp-admin/includes/plugin.php';

		$plugins = get_plugins();

		foreach( (array) $plugins as $plugin_path => $readme ){

			if( is_array( $search ) ){

				// Remove spaces from array keys (keys returned by WordPress have spaces removed)
				$search = array_combine( str_replace( ' ', '', array_keys( $search ) ), array_values( $search ) );

				// Do case-insensitive comparison between passed search array
				$diff_check = array_udiff_uassoc( $search, $readme, 'strcasecmp', 'strcasecmp' );

				if( empty( $diff_check ) ){
					$path = trailingslashit( WP_PLUGIN_DIR ) . plugin_dir_path( $plugin_path );
					return $trailing_slash ? $path : untrailingslashit( $path );
				}

			} else {

				if( strtolower( $readme[ 'Name' ] ) === strtolower( $search ) ){
					$path = trailingslashit( WP_PLUGIN_DIR ) . plugin_dir_path( $plugin_path );
					return $trailing_slash ? $path : untrailingslashit( $path );
				}

			}

		}

		return FALSE;
	}

}
No comments yet.

Leave a Reply