ID !== $front_page_id ) { $excerpt = self::get_page_excerpt( $about_page->ID, 60 ); if ( $excerpt ) { $parts[] = 'About page: ' . $excerpt; } } $context = implode( ' ', $parts ); set_transient( self::TRANSIENT_KEY, $context, self::CACHE_TTL ); return $context; } /** * Looks for a published "About" page by common slugs first (fast, * indexed lookups), then falls back to a title/content search. */ private static function find_about_page() { foreach ( array( 'about', 'about-us', 'about-me', 'who-we-are' ) as $slug ) { $page = get_page_by_path( $slug ); if ( $page && 'publish' === $page->post_status ) { return $page; } } $query = new WP_Query( array( 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => 1, 's' => 'about', ) ); return $query->have_posts() ? $query->posts[0] : null; } private static function get_page_excerpt( $post_id, $word_count ) { $post = get_post( $post_id ); if ( ! $post ) { return ''; } return wp_trim_words( wp_strip_all_tags( $post->post_content ), $word_count ); } /** * If WooCommerce is active and the given attachment belongs to a * product (as its featured image or via the product edit screen), * returns that product's name, categories, and description. Returns * null if WooCommerce isn't active or no matching product is found. */ public static function get_product_context( $attachment_id ) { if ( ! function_exists( 'wc_get_product' ) ) { return null; } $product_id = self::find_product_id_for_attachment( $attachment_id ); if ( ! $product_id ) { return null; } $product = wc_get_product( $product_id ); if ( ! $product ) { return null; } $description = $product->get_short_description(); if ( '' === trim( wp_strip_all_tags( $description ) ) ) { $description = $product->get_description(); } $categories = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'names' ) ); return array( 'title' => $product->get_name(), 'excerpt' => wp_trim_words( wp_strip_all_tags( $description ), 60 ), 'categories' => is_array( $categories ) ? implode( ', ', $categories ) : '', 'edit_link' => get_edit_post_link( $product_id, 'raw' ), ); } private static function find_product_id_for_attachment( $attachment_id ) { $parent_id = wp_get_post_parent_id( $attachment_id ); if ( $parent_id && 'product' === get_post_type( $parent_id ) ) { return $parent_id; } $query = new WP_Query( array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => 1, 'fields' => 'ids', 'meta_query' => array( array( 'key' => '_thumbnail_id', 'value' => $attachment_id, ), ), ) ); return $query->have_posts() ? (int) $query->posts[0] : 0; } } add_action( 'save_post_page', array( 'AIATG_Context', 'clear_cache' ) );