|
<?php |
|
|
|
/* |
|
* NOTE: This is a portion of a tutorial: |
|
* |
|
* @link https://johnregan3.wordpress.com/how-to-get-wordpress-related-posts |
|
*/ |
|
function jr3_get_related_posts( $post_id = 0, $args = array(), $count = 3 ) { |
|
|
|
/* |
|
* This block of code is not functional. See the full tutorial. |
|
* |
|
* @link https://johnregan3.wordpress.com/how-to-get-wordpress-related-posts |
|
*/ |
|
|
|
/* |
|
* Remove the search for specific taxonomy terms, leaving |
|
* only the post type restriction. |
|
* |
|
* Note that we'll make this code more efficient in the next step. |
|
*/ |
|
unset( $args['tax_query'] ); |
|
|
|
$posts = jr3_related_posts_get( $args, $posts ); |
|
|
|
// Since we're not doing anymore queries, return what we have. |
|
if ( ! empty( $posts ) ) { |
|
// Make sure the new array of posts doesn't exceed the number of posts we need. |
|
$posts = array_slice( $posts, 0, $count ); |
|
|
|
return $posts; |
|
} |
|
|
|
// Make sure we don't exceed the number of $count. |
|
return array_slice( $posts, 0, $count ); |
|
} |
|
|
|
/** |
|
* Run a simple \WP_Query using the provided args. |
|
* |
|
* @since 1.0.0 |
|
* |
|
* @param array $args An array of query args. |
|
* |
|
* @return array An array of posts, else an empty array. |
|
*/ |
|
function jr3_related_get_posts_by_args( $args = array(), $posts = array() ) { |
|
if ( empty( $args ) || ! is_array( $args ) ) { |
|
return array(); |
|
} |
|
|
|
// Create the transient name. |
|
$transient_name = jr3_related_transient_name( $args ); |
|
|
|
// See if we have any posts stored already. |
|
$new_posts = get_transient( $transient_name ); |
|
|
|
// Don't check if not empty, as the saved value may be an empty array. |
|
if ( ! is_array( $new_posts ) ) { |
|
$new_posts = array(); |
|
|
|
// Don't use get_posts as the WP_Query object will be cached. |
|
$query = new WP_Query( $args ); |
|
if ( ! empty( $query->posts ) && is_array( $query->posts ) ) { |
|
$new_posts = $query->posts; |
|
} |
|
set_transient( $transient_name, $new_posts, HOUR_IN_SECONDS ); |
|
} |
|
|
|
if ( is_array( $new_posts ) && ! empty( $new_posts ) ) { |
|
$posts = $posts + $new_posts; |
|
} |
|
|
|
return $posts; |
|
} |
|
|
|
/** |
|
* Generate a transient name. |
|
* |
|
* @param array $args An array of WP_Query arguments. |
|
* |
|
* @return string A transient name. |
|
*/ |
|
function jr3_related_transient_name( $args = array() ) { |
|
return 'jr3_rel_' . md5( maybe_serialize( $args ) ); |
|
} |