| 396 | | // if any of post_type, year, monthnum, or day are set, use them to refine the query |
| 397 | | if ( get_query_var('post_type') ) |
| 398 | | $where .= $wpdb->prepare(" AND post_type = %s", get_query_var('post_type')); |
| 399 | | if ( get_query_var('year') ) |
| 400 | | $where .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var('year')); |
| 401 | | if ( get_query_var('monthnum') ) |
| 402 | | $where .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var('monthnum')); |
| 403 | | if ( get_query_var('day') ) |
| 404 | | $where .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var('day')); |
| | 396 | // if post_type is set, use it to refine query |
| | 397 | if ( $post_type = get_query_var('post_type') ) |
| | 398 | $where .= $wpdb->prepare( " AND post_type = %s", $post_type ); |
| | 399 | |
| | 400 | $possible_posts = $wpdb->get_results( "SELECT ID, post_date FROM $wpdb->posts WHERE $where AND post_status = 'publish'" ); |
| | 401 | $n = count( $possible_posts ); |
| | 402 | |
| | 403 | if( 0 == $n ) // no match |
| | 404 | return false; |
| | 405 | if( 1 == $n ) // only one match |
| | 406 | return get_permalink( $possible_posts[0]->ID ); |
| | 407 | |
| | 408 | // more than one match - try to refine based on year, month, date |
| | 409 | $y = get_query_var('year'); |
| | 410 | $m = get_query_var('monthnum'); |
| | 411 | $d = get_query_var('day'); |
| | 412 | |
| | 413 | $best_fits = array(); |
| | 414 | foreach( $possible_posts as $key => $data ) { |
| | 415 | $best_fits[$key] = 0; |
| | 416 | if( $y && mysql2date( 'Y', $data->post_date ) == $y ) { |
| | 417 | $best_fits[$key] ++; |
| | 418 | if( $m && mysql2date( 'm', $data->post_date ) == $m ) { |
| | 419 | $best_fits[$key] ++; |
| | 420 | if( $d && mysql2date( 'j', $data->post_date ) == $d ) |
| | 421 | $best_fits[$key] ++; |
| | 422 | } |
| | 423 | } |
| | 424 | } |
| | 425 | |
| | 426 | // if something came up trumps, use that, otherwise we're shooting in the dark |
| | 427 | $max = max( $best_fits ); |
| | 428 | if( $max > 0 && count( array_keys( $best_fits, $max ) ) == 1 ) |
| | 429 | return get_permalink( $possible_posts[ array_search( $max, $best_fits ) ]->ID ); |