'; 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 = '#(]*\sid=(["\'])jp-relatedposts\2[^>]*)(>)(.*?)()#is'; $has_jp = (bool) preg_match( $jp_re, $html ); if ( 'auto' === $design ) { $design = $has_jp ? 'jetpack' : 'simple'; } if ( ! $ids ) { return str_replace( self::MARKER, '', $html ); // Nothing related: leave Jetpack's box hidden as usual. } if ( 'jetpack' === $design && $has_jp ) { // Fill Jetpack's box: show it, use the Headline setting in its heading, add the items. $items = self::render_jetpack_items( $ids ); $html = preg_replace_callback( $jp_re, function ( $mm ) use ( $items ) { $open = preg_match( '#\sstyle\s*=#i', $mm[1] ) ? preg_replace( '#\sstyle\s*=\s*(["\'])(.*?)\1#i', ' style=$1$2;display:block$1', $mm[1], 1 ) : $mm[1] . ' style="display:block"'; return $open . $mm[3] . self::jetpack_headline( $mm[4] ) . $items . $mm[5]; }, $html, 1 ); // Jetpack's script would try to load the list from WordPress, which doesn't exist on the static site. $html = CFSP_Cleanup::remove_by_id( $html, 'jetpack_related-posts-js' ); $html = CFSP_Cleanup::remove_by_id( $html, 'jetpack_related-posts-js-extra' ); return str_replace( self::MARKER, '', $html ); } if ( 'jetpack' === $design ) { $block = ''; } elseif ( 'custom' === $design ) { $block = self::render_custom( $ids ); } else { $block = self::render_simple( $ids ); } if ( false !== strpos( $html, self::MARKER ) ) { return str_replace( self::MARKER, $block, $html ); } return $html; // No place to put it (theme doesn't use the_content for this post). } /** * Put the Headline setting into the heading of Jetpack's own box, keeping its markup (the * wrapper and classes) so Jetpack's styles still apply. An empty setting keeps Jetpack's text, and * a box without a heading (Jetpack's "Show a headline" off) stays without one. */ private static function jetpack_headline( $inner ) { $headline = trim( (string) CFSP_Settings::get( 'related_headline' ) ); if ( '' === $headline ) { return $inner; } return preg_replace_callback( '#(]*\bclass\s*=\s*(["\'])[^"\']*\bjp-relatedposts-headline\b[^"\']*\2[^>]*>)(.*?)()#is', function ( $m ) use ( $headline ) { $text = esc_html( $headline ); if ( preg_match( '#^\s*]*>.*\s*$#is', $m[3] ) ) { $text = '' . $text . ''; } return $m[1] . $text . $m[4]; }, $inner, 1 ); } /** * Featured image as [ url, width, height ]. * * WordPress falls back to the original file when the chosen size doesn't exist for an image, * but still reports width/height shrunk to that size (e.g. the original file at 70x44). * In that case, and for unknown sizes, use the original file with its real dimensions. */ private static function image( $id ) { if ( ! CFSP_Settings::get( 'related_show_image' ) || ! has_post_thumbnail( $id ) ) { return false; } $thumb = get_post_thumbnail_id( $id ); $size = (string) CFSP_Settings::get( 'related_image_size' ); if ( 'full' !== $size && ! in_array( $size, get_intermediate_image_sizes(), true ) ) { $size = 'full'; } $img = wp_get_attachment_image_src( $thumb, $size ); if ( $img && 'full' !== $size && empty( $img[3] ) ) { $img = wp_get_attachment_image_src( $thumb, 'full' ); } return $img; } /** Data for one related post. Neighbouring pages list the same posts, so each is built once per request. */ private static function item( $id ) { static $items = array(); if ( ! isset( $items[ $id ] ) ) { $items[ $id ] = self::build_item( $id ); } return $items[ $id ]; } private static function build_item( $id ) { $img = self::image( $id ); $cats = get_the_category( $id ); $cat = ''; foreach ( (array) $cats as $c ) { if ( ! CFSP_Settings::get( 'related_skip_default_cat' ) || (int) $c->term_id !== (int) get_option( 'default_category' ) ) { $cat = $c->name; break; } } $post = get_post( $id ); $excerpt = ''; // Only built when shown (Show a short excerpt, or {excerpt} in a custom template): stripping a long post is not free. $custom = 'custom' === CFSP_Settings::get( 'related_design' ) && false !== strpos( (string) CFSP_Settings::get( 'related_item_template' ), '{excerpt}' ); if ( CFSP_Settings::get( 'related_show_excerpt' ) || $custom ) { $excerpt = $post->post_excerpt ? $post->post_excerpt : wp_strip_all_tags( excerpt_remove_blocks( strip_shortcodes( $post->post_content ) ) ); } return array( 'id' => $id, 'url' => get_permalink( $id ), 'title' => html_entity_decode( get_the_title( $id ), ENT_QUOTES, 'UTF-8' ), 'img' => $img, 'date' => get_the_date( '', $id ), 'category' => $cat, 'excerpt' => wp_trim_words( $excerpt, 20, '…' ), ); } /** Markup Jetpack's related-posts script normally builds in the browser. */ private static function render_jetpack_items( array $ids ) { $html = ''; foreach ( array_values( $ids ) as $i => $id ) { $p = self::item( $id ); $url = esc_url( $p['url'] ); $title = esc_attr( $p['title'] ); $html .= sprintf( '
', $i, $p['img'] ? 'thumbs' : 'nothumbs', $id ); if ( $p['img'] ) { $html .= sprintf( '', $url, $title, $i, esc_url( $p['img'][0] ), (int) $p['img'][1], (int) $p['img'][2] ); } $html .= sprintf( '', $url, $title, $i, esc_html( $p['title'] ) ); if ( CFSP_Settings::get( 'related_show_excerpt' ) ) { $html .= ''; } if ( CFSP_Settings::get( 'related_show_date' ) ) { $html .= ''; } if ( CFSP_Settings::get( 'related_show_category' ) && $p['category'] ) { $html .= ''; } $html .= '
'; } return ''; } private static function render_simple( array $ids ) { $items = ''; foreach ( $ids as $id ) { $p = self::item( $id ); $url = esc_url( $p['url'] ); $meta = array(); if ( CFSP_Settings::get( 'related_show_date' ) ) { $meta[] = esc_html( $p['date'] ); } if ( CFSP_Settings::get( 'related_show_category' ) && $p['category'] ) { $meta[] = esc_html( sprintf( 'In %s', $p['category'] ) ); } $items .= ''; } // Styles: enqueue_style(). return ''; } private static function render_custom( array $ids ) { $item_tpl = (string) CFSP_Settings::get( 'related_item_template' ); $wrap_tpl = (string) CFSP_Settings::get( 'related_wrapper_template' ); $item_tpl = '' !== trim( $item_tpl ) ? $item_tpl : '
  • {title}
  • '; $wrap_tpl = '' !== trim( $wrap_tpl ) ? $wrap_tpl : '

    {headline}

    '; $items = ''; foreach ( $ids as $id ) { $p = self::item( $id ); $items .= strtr( $item_tpl, array( '{url}' => esc_url( $p['url'] ), '{title}' => esc_html( $p['title'] ), '{image}' => $p['img'] ? sprintf( '%s', esc_url( $p['img'][0] ), (int) $p['img'][1], (int) $p['img'][2], esc_attr( $p['title'] ) ) : '', '{image_url}' => $p['img'] ? esc_url( $p['img'][0] ) : '', '{date}' => esc_html( $p['date'] ), '{category}' => esc_html( $p['category'] ), '{excerpt}' => esc_html( $p['excerpt'] ), ) ); } return strtr( $wrap_tpl, array( '{headline}' => esc_html( CFSP_Settings::get( 'related_headline' ) ), '{items}' => $items, ) ); } /** For the admin preview: related posts of a post URL or ID. */ public static function preview( $input ) { $input = trim( (string) $input ); $post_id = ctype_digit( $input ) ? (int) $input : url_to_postid( $input ); if ( ! $post_id && '' !== $input ) { // Accept static-site addresses too. $path = (string) wp_parse_url( $input, PHP_URL_PATH ); $post_id = url_to_postid( home_url( $path ) ); } $post = $post_id ? get_post( $post_id ) : null; if ( ! $post ) { return new WP_Error( 'cfsp_related', 'No post found for that address or ID.' ); } $out = array(); foreach ( self::related_ids( $post->ID, (int) CFSP_Settings::get( 'related_count' ) ) as $id ) { $out[] = array( 'title' => html_entity_decode( get_the_title( $id ), ENT_QUOTES, 'UTF-8' ), 'url' => get_permalink( $id ), ); } return array( 'post' => html_entity_decode( get_the_title( $post ), ENT_QUOTES, 'UTF-8' ), 'related' => $out, ); } }