'; const META = 'cfsp-post-id'; public static function init() { if ( is_admin() || ! CFSP_Settings::get( 'related_enabled' ) || ! self::is_export_request() ) { return; } add_action( 'wp_head', array( __CLASS__, 'print_meta' ), 1 ); add_filter( 'the_content', array( __CLASS__, 'add_marker' ), 999 ); add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_style' ) ); } /** Styles for the "Simple grid" design, added to exported posts the WordPress way. */ public static function enqueue_style() { // "Automatic" falls back to the grid when the theme has no Jetpack box. if ( ! in_array( CFSP_Settings::get( 'related_design' ), array( 'simple', 'auto' ), true ) || ! self::post_types() || ! is_singular( self::post_types() ) ) { return; } wp_register_style( 'cfsp-related', false, array(), CFSP_VERSION ); wp_enqueue_style( 'cfsp-related' ); wp_add_inline_style( 'cfsp-related', '.cfsp-related{margin:2.5em 0;clear:both}.cfsp-related-title{margin:0 0 1em}.cfsp-related-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:1.25em}' . '.cfsp-related-item img{display:block;width:100%;height:auto;aspect-ratio:7/4;object-fit:cover;border-radius:8px}' . '.cfsp-related-item h4{margin:.6em 0 .25em;font-size:1em;line-height:1.35}.cfsp-related-item h4 a{text-decoration:none}' . '.cfsp-related-meta,.cfsp-related-excerpt{margin:0 0 .3em;font-size:.85em;opacity:.75}' ); } /** Pages fetched by the exporter carry this header (see CFSP_Exporter::fetch()). */ public static function is_export_request() { return ! empty( $_SERVER['HTTP_X_CFSP_EXPORT'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput } /** * Content types that get related posts ("Show on"): exported ones only. Pages are left out by * default; a privacy policy or contact page shouldn't list "related" content. * * @return string[] */ public static function post_types() { return array_values( array_intersect( (array) CFSP_Settings::get( 'related_post_types' ), CFSP_URLs::post_types() ) ); } public static function print_meta() { if ( is_singular() && in_array( get_post_type(), self::post_types(), true ) ) { printf( '' . "\n", esc_attr( self::META ), (int) get_queried_object_id() ); } } public static function add_marker( $content ) { if ( is_singular() && in_the_loop() && is_main_query() && get_the_ID() === get_queried_object_id() && false === strpos( $content, self::MARKER ) ) { $content .= "\n" . self::MARKER . "\n"; } return $content; } /* ------------------------------------------------------------------ * * Matching * ------------------------------------------------------------------ */ /** * Set by the job runner: while a job runs, the ranked list for each set of terms is kept between * batches (posts in the same categories and tags share it), so a full export runs one scoring * query per category instead of one per post. * * @var string */ public static $job = ''; /** Seconds spent in apply() during this request (shown in the export timing summary). */ public static $seconds = 0.0; /** * Related post IDs, best first. Tags score 3, categories 1; ties go to the newest post. * * @return int[] */ public static function related_ids( $post_id, $limit ) { global $wpdb; static $cache = array(); static $ranked = array(); $key = $post_id . ':' . $limit; if ( isset( $cache[ $key ] ) ) { return $cache[ $key ]; } $post = get_post( $post_id ); if ( ! $post || $limit < 1 ) { return array(); } $match = CFSP_Settings::get( 'related_match' ); $taxonomies = array(); if ( 'categories' !== $match ) { $taxonomies[] = 'post_tag'; } if ( 'tags' !== $match ) { $taxonomies[] = 'category'; } $taxonomies = array_values( array_intersect( $taxonomies, get_object_taxonomies( $post->post_type ) ) ); $tt_ids = array(); foreach ( $taxonomies as $tax ) { $terms = get_the_terms( $post, $tax ); if ( ! $terms || is_wp_error( $terms ) ) { continue; } foreach ( $terms as $term ) { if ( 'category' === $tax && CFSP_Settings::get( 'related_skip_default_cat' ) && (int) $term->term_id === (int) get_option( 'default_category' ) ) { continue; } $tt_ids[] = (int) $term->term_taxonomy_id; } } if ( ! $tt_ids ) { return $cache[ $key ] = self::fill( $post, array(), $limit ); } $tt_ids = array_values( array_unique( array_map( 'intval', $tt_ids ) ) ); sort( $tt_ids ); // The ranking depends only on the post type and the set of terms, so posts that share them // share one list. Fetch one extra row so the post itself can be dropped from it. $sig = md5( $post->post_type . '|' . implode( ',', $tt_ids ) . '|' . $limit ); if ( ! isset( $ranked[ $sig ] ) && self::$job ) { $stored = get_transient( 'cfsp_rel_' . substr( md5( self::$job . $sig ), 0, 20 ) ); if ( is_array( $stored ) ) { $ranked[ $sig ] = $stored; } } if ( ! isset( $ranked[ $sig ] ) ) { // phpcs:disable WordPress.DB.DirectDatabaseQuery -- Read-only scoring query on core tables (no WP_Query equivalent), cached per request and per job. $ranked[ $sig ] = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT tr.object_id FROM {$wpdb->term_relationships} tr INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id INNER JOIN {$wpdb->posts} p ON p.ID = tr.object_id WHERE tr.term_taxonomy_id IN (" . implode( ',', array_fill( 0, count( $tt_ids ), '%d' ) ) . ") AND p.post_type = %s AND p.post_status = 'publish' AND p.post_password = '' GROUP BY tr.object_id, p.post_date ORDER BY SUM( CASE WHEN tt.taxonomy = 'post_tag' THEN 3 ELSE 1 END ) DESC, p.post_date DESC LIMIT %d", array_merge( $tt_ids, array( $post->post_type, (int) $limit + 1 ) ) ) ) ); // phpcs:enable if ( self::$job ) { set_transient( 'cfsp_rel_' . substr( md5( self::$job . $sig ), 0, 20 ), $ranked[ $sig ], DAY_IN_SECONDS ); } } $ids = array_slice( array_values( array_diff( $ranked[ $sig ], array( (int) $post->ID ) ) ), 0, $limit ); return $cache[ $key ] = self::fill( $post, $ids, $limit ); } /** * Top up a short list with the latest posts of the same post type ("When fewer are found"), * so a post in a small category with no tags still gets a full box. Matches always come first. * * @param WP_Post $post The post the list is for. * @param int[] $ids Related post IDs found by matching. * @param int $limit Posts to show. * @return int[] */ private static function fill( $post, array $ids, $limit ) { if ( 'latest' !== CFSP_Settings::get( 'related_fill' ) || count( $ids ) >= $limit ) { return $ids; } // Ask for enough of the newest posts to cover the ones already listed, then skip those. // The newest posts are the same for every page, so one list per request serves them all. static $newest = array(); $skip = array_merge( array( (int) $post->ID ), $ids ); $need = $limit + count( $skip ); if ( ! isset( $newest[ $post->post_type ] ) || ( count( $newest[ $post->post_type ]['ids'] ) < $need && ! $newest[ $post->post_type ]['all'] ) ) { $want = max( $need, 2 * $limit + 1 ); $found = array_map( 'intval', get_posts( array( 'post_type' => $post->post_type, 'post_status' => 'publish', 'has_password' => false, 'orderby' => 'date', 'order' => 'DESC', 'numberposts' => $want, 'fields' => 'ids', ) ) ); $newest[ $post->post_type ] = array( 'ids' => $found, 'all' => count( $found ) < $want, ); } $latest = array_diff( array_slice( $newest[ $post->post_type ]['ids'], 0, $need ), $skip ); return array_merge( $ids, array_slice( array_values( $latest ), 0, $limit - count( $ids ) ) ); } /** Pages whose related list may change when this post changes (for automatic pushes). */ public static function affected_urls( $post_id ) { $count = (int) CFSP_Settings::get( 'related_refresh' ); if ( ! CFSP_Settings::get( 'related_enabled' ) || $count < 1 || ! in_array( get_post_type( $post_id ), self::post_types(), true ) ) { return array(); } return array_filter( array_map( 'get_permalink', self::related_ids( $post_id, $count ) ) ); } /* ------------------------------------------------------------------ * * Rendering * ------------------------------------------------------------------ */ /** * Put related posts into an exported page (raw HTML, WordPress URLs; the exporter rewrites them). */ public static function apply( $html ) { $start = microtime( true ); $html = self::apply_inner( $html ); self::$seconds += microtime( true ) - $start; return $html; } private static function apply_inner( $html ) { if ( ! preg_match( '#\s*#', $html, $m ) ) { return $html; } $html = str_replace( $m[0], '', $html ); if ( ! CFSP_Settings::get( 'related_enabled' ) ) { return str_replace( self::MARKER, '', $html ); } $post_id = (int) $m[1]; $ids = self::related_ids( $post_id, (int) CFSP_Settings::get( 'related_count' ) ); $design = CFSP_Settings::get( 'related_design' ); $jp_re = '#(