Last active
January 6, 2017 04:43
-
-
Save yaulaannl/783181995a3077b184f275ea624683d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//get category id | |
$cat_id = get_cat_id(single_cat_title("",false)); | |
$featured_IDs = array(); | |
//get the three manual IDs | |
for($i = 0; $i < 3; $i++){ | |
$field_name = 'featured_post_id_'.($i+1); | |
$feat_ID = get_field($field_name,'category_'.$cat_id); | |
if($feat_ID && (intval($feat_ID) > 0) && (get_post_status($feat_ID) == 'publish')){ | |
array_push($featured_IDs,intval($feat_ID)); | |
} | |
} | |
//remove possible duplicates | |
$featured_IDs = array_values(array_unique($featured_IDs)); | |
//if didn't get three elements, add random featured posts of the same category | |
if(count($featured_IDs) < 3){ | |
$my_array = array( | |
'post_type' => 'post', | |
'post_status' => 'publish', | |
'cat' => $cat_id, | |
'meta_key' => 'is_featured', | |
'post__not_in' => $featured_IDs, | |
'meta_value' => '1', | |
'orderby' => 'rand', | |
'posts_per_page' => 3, | |
'fields' => 'ids', | |
); | |
$loop = new WP_Query($my_array); | |
$randpost_IDs = $loop->posts; | |
//combine IDs | |
$num_1 = count($featured_IDs); | |
for($i = 0; $i < min((3 - $num_1),count($randpost_IDs)); $i++){ | |
array_push($featured_IDs, $randpost_IDs[$i]); | |
} | |
} | |
//get posts | |
$featured_posts = empty($featured_IDs)? array() : array_map("get_post",$featured_IDs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment