Skip to content

Instantly share code, notes, and snippets.

@sbrajesh
Last active May 13, 2018 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbrajesh/e932e6d8bbfd4a515e070f520ce40ef4 to your computer and use it in GitHub Desktop.
Save sbrajesh/e932e6d8bbfd4a515e070f520ce40ef4 to your computer and use it in GitHub Desktop.
Efficient WordPress Latest Post content fetch for a user
/**
* Fetch of Latest Post content of a user by post type.
*
* @param array $atts shortcode atts.
* @param string $content n/a
*
* @return mixed|string
*/
function buddydev_user_last_post_shortcode( $atts, $content = '' ) {
$atts = shortcode_atts( array(
// by default, If BuddyPress is active, use displayed user.
'user_id' => function_exists( 'bp_displayed_user_id' ) ? bp_displayed_user_id() : 0,
'post_type' => 'post',
), $atts );
$user_id = $atts['user_id'];
if ( ! $user_id ) {
return $content;
}
global $wpdb;
$last_post_id = get_transient( "bp-user-last-post-{$atts['post_type']}-{$user_id}" );
if ( ! $last_post_id ) {
$last_post_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_status =%s AND post_author = %d ORDER BY post_modified_gmt DESC LIMIT 0, 1" , $atts['post_type'], 'publish', $atts['user_id'] ) );
if ( ! empty( $last_post_id ) ) {
set_transient( "bp-user-last-post-{$atts['post_type']}-{$user_id}", $last_post_id, DAY_IN_SECONDS );
}
}
if ( ! $last_post_id ) {
return '';
}
$post = get_post( $last_post_id );
if ( ! $post ) {
return $content;
}
return apply_filters( 'the_content', $post->post_content );
}
add_shortcode( 'bp-user-last-post', 'buddydev_user_last_post_shortcode' );
/**
* Clear transient on New Post, trash post, delete post.
*
* @param int $post_id post id.
*/
function buddydev_clear_last_post_transient( $post_id ) {
if ( ! defined( 'DOING_AUTOSAVE' ) ) {
$post = get_post( $post_id );
delete_transient( "bp-user-last-post-{$post->post_type}-{$post->post_author}" );
}
}
// on new post or delete post clear transient.
add_action( 'save_post', 'buddydev_clear_last_post_transient' );
add_action( 'wp_trash_post', 'buddydev_clear_last_post_transient' );
add_action( 'before_delete_post', 'buddydev_clear_last_post_transient' );
function buddydev_delete_user_post_association( $post_id, $data ) {
$post = get_post( $post_id );
if( $post->post_author == $data['post_author'] ) {
return ;
}
delete_transient( "bp-user-last-post-{$post->post_type}-{$post->post_author}" );
}
add_action( 'pre_post_update', 'buddydev_delete_user_post_association', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment