目前,我使用以下函式來給出 ACF 欄位的最低編號。該代碼正在運行,但不是最聰明和最節省資源的方式。
add_shortcode( 'LEASINGFAKTOR', 'leaserate_shortcode' );
function leaserate_shortcode () {
$args = array(
'posts_per_page'=> -1,
'post_type' => 'fahrzeuge',
'meta_key' => 'leasingfaktor',
);
$low_rate_query = new WP_Query( $args );
$rate = array();
if( $low_rate_query->have_posts() ):
while( $low_rate_query->have_posts() ) : $low_rate_query->the_post();
$rate = get_field('leasingfaktor');
if(isset($rate) && !empty($rate)){
$rates[] = $rate;
}
endwhile;
$max_rate = max($rates);
$min_rate = min($rates);
endif; wp_reset_query();
return $min_rate;
}
關于讓它更清潔、更快、更智能的任何想法?
uj5u.com熱心網友回復:
好吧,您可以使用get_posts而不是使用,WP_Query因為您只需要可以使用的帖子ID陣列get_field,并且使用get_posts您不需要執行while回圈,并且wp_reset_query
您可以做的另一個改進是使用,array_map而不是foreach 因為您不想在這里生成任何 HTML 或不做任何復雜的事情。您只是想獲得一個陣列,rates因此array_map在這種情況下會更好并且易于使用,并且代碼會很短。
所以你的最終代碼使用get_postsandarray_map將是這樣的:
/**
* Shortcode function
*/
function leaserate_shortcode() {
$query_args = array(
'posts_per_page' => -1,
'post_type' => 'fahrzeuge',
'meta_key' => 'leasingfaktor', // phpcs:ignore WordPress.DB.SlowDBQuery
'fields' => 'ids', // We just need ids for our work.
);
/**
* We will use get_posts instead of using WP_Query
* Because it's easy to use in this case and $no_found_rows
* is set to false that will give fast performance
*/
$post_ids = get_posts( $query_args );
// Set default min rate.
$min_rate = 0;
// Check if we found ids or not.
if ( ! empty( $post_ids ) ) {
/**
* We don't need to do foreach or for loop here
* We can use an array map and map the post ids array
* with the values.
* So we will have an array of rates in the result
*/
$rates = array_map(
function( $id ) {
// we use using type transform using (int)
// assuming returning value will be a number or string number.
return (int) get_field( 'leasingfaktor', $id );
},
$post_ids
);
// Filter empty values and get unique values.
$rates = array_unique( array_filter( $rates ) );
// Check if the final array is not empty.
if ( ! empty( $rates ) ) {
$min_rate = min( $rates );
}
}
return $min_rate;
}
add_shortcode( 'LEASINGFAKTOR', 'leaserate_shortcode' );
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511126.html
