Skip to content

Instantly share code, notes, and snippets.

@adicahyaludin
Created February 19, 2019 11:05
Show Gist options
  • Save adicahyaludin/ff2179f5132abf4c41ddeeafba701918 to your computer and use it in GitHub Desktop.
Save adicahyaludin/ff2179f5132abf4c41ddeeafba701918 to your computer and use it in GitHub Desktop.
private function get_posts_ids_by( $key, $value, $default = false )
{
$posts_ids = [];
$user_id = get_current_user_id();
$query = Capsule::table(self::table())
->select(self::table().'.ID')
->where(self::table().'.post_type','soal')
->where(self::table().'.post_status','publish');
if ( false === $default ) :
if ( 'test' === $key ) :
$posts_ids_cache = get_transient( 'default_'.$user_id.'_posts_ids' );
if ( false !== $posts_ids_cache && is_array( $posts_ids_cache ) ) :
$query->whereIn( self::table().'.ID', $posts_ids_cache );
endif;
else :
switch ( $key ) {
case 'subject':
$k = 'test';
break;
case 'year-test':
$k = 'subject';
break;
case 'type':
$k = 'year-test';
break;
case 'difficulty':
$k = 'type';
break;
case 'keyword':
$k = 'difficulty';
break;
default:
$k = '';
break;
}
$posts_ids_cache = get_transient( $k.'_'.$user_id.'_posts_ids' );
if ( false !== $posts_ids_cache && is_array( $posts_ids_cache ) ) :
$query->whereIn( self::table().'.ID', $posts_ids_cache );
endif;
endif;
endif;
if ( !empty( $value ) ) :
if ( 'type' === $key ) :
$query->join(self::table('postmeta'), self::table().'.ID', '=', self::table('postmeta').'.post_id')
->where(self::table('postmeta').'.meta_key','_type')
->where(self::table('postmeta').'.meta_value',$value);
else:
$query->join(self::table('term_relationships'), self::table().'.ID', '=', self::table('term_relationships').'.object_id')
->join(self::table('term_taxonomy'), self::table('term_relationships').'.term_taxonomy_id', '=', self::table('term_taxonomy').'.term_taxonomy_id')
// ->join(self::table('terms'), self::table('term_taxonomy').'.term_id', '=', self::table('terms').'.term_id')
->where(self::table('term_taxonomy').'.taxonomy', $key)
->whereIn(self::table('term_taxonomy').'.term_id', $value);
endif;
endif;
$data = $query->get()->toArray();
if ( !empty( $data ) ) :
foreach ( $data as $k => $v ) :
$posts_ids[] = $v->ID;
endforeach;
if ( false === $default ) :
set_transient( $key.'_'.$user_id.'_posts_ids', $posts_ids, 12 * HOUR_IN_SECONDS );
endif;
endif;
return $posts_ids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment