wp_post_mime_type_where() WordPress Function

The wp_post_mime_type_where() function is used to add a WHERE clause to the query that retrieves posts by mime type. This is useful for restricting the query to only certain mime types, such as 'image/jpeg' or 'application/pdf'.

wp_post_mime_type_where( string|string[] $post_mime_types, string $table_alias = '' ) #

Convert MIME types into SQL.


Parameters

$post_mime_types

(string|string[])(Required)List of mime types or comma separated string of mime types.

$table_alias

(string)(Optional) Specify a table alias, if needed.

Default value: ''


Top ↑

Return

(string) The SQL AND clause for mime searching.


Top ↑

Source

File: wp-includes/post.php

function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
	$where     = '';
	$wildcards = array( '', '%', '%/%' );
	if ( is_string( $post_mime_types ) ) {
		$post_mime_types = array_map( 'trim', explode( ',', $post_mime_types ) );
	}

	$wheres = array();

	foreach ( (array) $post_mime_types as $mime_type ) {
		$mime_type = preg_replace( '/\s/', '', $mime_type );
		$slashpos  = strpos( $mime_type, '/' );
		if ( false !== $slashpos ) {
			$mime_group    = preg_replace( '/[^-*.a-zA-Z0-9]/', '', substr( $mime_type, 0, $slashpos ) );
			$mime_subgroup = preg_replace( '/[^-*.+a-zA-Z0-9]/', '', substr( $mime_type, $slashpos + 1 ) );
			if ( empty( $mime_subgroup ) ) {
				$mime_subgroup = '*';
			} else {
				$mime_subgroup = str_replace( '/', '', $mime_subgroup );
			}
			$mime_pattern = "$mime_group/$mime_subgroup";
		} else {
			$mime_pattern = preg_replace( '/[^-*.a-zA-Z0-9]/', '', $mime_type );
			if ( false === strpos( $mime_pattern, '*' ) ) {
				$mime_pattern .= '/*';
			}
		}

		$mime_pattern = preg_replace( '/\*+/', '%', $mime_pattern );

		if ( in_array( $mime_type, $wildcards, true ) ) {
			return '';
		}

		if ( false !== strpos( $mime_pattern, '%' ) ) {
			$wheres[] = empty( $table_alias ) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
		} else {
			$wheres[] = empty( $table_alias ) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
		}
	}

	if ( ! empty( $wheres ) ) {
		$where = ' AND (' . implode( ' OR ', $wheres ) . ') ';
	}

	return $where;
}


Top ↑

Changelog

Changelog
VersionDescription
2.5.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More