Automattic\WooCommerce\Internal\EmailEditor\WCTransactionalEmails

WCTransactionalEmailPostsManager::get_email_type_from_post_id │ public │ WC 1.0

Retrieves the WooCommerce email type from the options table when post ID is provided.

Uses multi-level caching:

  1. In-memory cache for the same request
  2. WordPress object cache for cross-request caching
  3. Database query if cache is not available.

Method of the class: WCTransactionalEmailPostsManager{}

No Hooks.

Returns

string|null. The WooCommerce email type if found, null otherwise.

Usage

$WCTransactionalEmailPostsManager = new WCTransactionalEmailPostsManager();
$WCTransactionalEmailPostsManager->get_email_type_from_post_id( $post_id, $skip_cache );
$post_id(int|string) (required)
The post ID.
$skip_cache(true|false)
Whether to skip the cache.
Default: false

WCTransactionalEmailPostsManager::get_email_type_from_post_id() code WC 11.1.2

public function get_email_type_from_post_id( $post_id, $skip_cache = false ) {
	// Early return if post_id is invalid.
	if ( empty( $post_id ) ) {
		return null;
	}

	$post_id   = (int) $post_id;
	$cache_key = $this->get_cache_key_for_post_id( $post_id );

	if ( ! $skip_cache ) {
		// Check in-memory cache first (fastest).
		if ( array_key_exists( $post_id, $this->post_id_to_email_type_cache ) ) {
			return $this->post_id_to_email_type_cache[ $post_id ];
		}

		// Check WordPress object cache.
		$email_type = wp_cache_get( $cache_key, self::CACHE_GROUP );

		if ( ! empty( $email_type ) ) {
			$this->post_id_to_email_type_cache[ $post_id ] = $email_type;
			return $email_type;
		}
	}

	// Cache miss - perform database query.
	global $wpdb;

	$option_name = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND option_value = %s LIMIT 1",
			self::WC_OPTION_NAME,
			$post_id
		)
	);

	if ( empty( $option_name ) ) {
		// Unpublished posts (auto-draft/draft) have no option mapping yet; fall back to post meta.
		// The result is intentionally NOT stored in the shared caches:
		// `get_email_template_post_id()` reverse-searches the in-memory cache
		// and must only ever see mapped posts, and the object cache has no
		// invalidation for scratchpad deletion. Repeated calls are cheap via
		// the post meta cache.
		$email_type = get_post_meta( $post_id, self::EMAIL_TYPE_META_KEY, true );
		if ( empty( $email_type ) || ! is_string( $email_type ) ) {
			// Cache the full miss in memory so repeated lookups within the
			// request don't rerun the options LIKE scan.
			$this->post_id_to_email_type_cache[ $post_id ] = null;
			return null;
		}

		return $email_type;
	}

	$email_type = $this->get_email_type_from_option_name( $option_name );

	// Store in both caches.
	$this->post_id_to_email_type_cache[ $post_id ] = $email_type;
	wp_cache_set( $cache_key, $email_type, self::CACHE_GROUP, self::CACHE_EXPIRATION );

	return $email_type;
}