更好地优化常见变量

时间:2016-03-24 01:28:36

标签: php

我正在尝试了解有关优化PHP和使用常见变量的更多信息。正如您在下面看到的,我将基本上复制相同的函数来为模板中的4个不同位置创建数据。我试图看看优化这种变量存储的最佳方法是什么,效率更高。

我曾经考虑过做一些循环或存储在数组中,只是想确保我以最有效的方式进行循环,以便我可以学习以备将来使用。对此有任何帮助将非常感激。

$feat_1_id = get_theme_mod( 'featured-item-1' );
$feat_1_title = get_the_title( $feat_1_id );
$feat_1_type = get_post_type( $feat_1_id );
$feat_1_permalink = get_permalink( $feat_1_id );
$feat_1_img = get_the_post_thumbnail( $feat_1_id );
$feat_1_excerpt = get_the_excerpt( $feat_1_id );

$feat_2_id = get_theme_mod( 'featured-item-2' );
$feat_2_title = get_the_title( $feat_2_id );
$feat_2_type = get_post_type( $feat_2_id );
$feat_2_permalink = get_permalink( $feat_2_id );
$feat_2_img = get_the_post_thumbnail( $feat_2_id );

$feat_3_id = get_theme_mod( 'featured-item-3' );
$feat_3_title = get_the_title( $feat_3_id );
$feat_3_type = get_post_type( $feat_3_id );
$feat_3_permalink = get_permalink( $feat_3_id );
$feat_3_img = get_the_post_thumbnail( $feat_3_id );

$feat_4_id = get_theme_mod( 'featured-item-4' );
$feat_4_title = get_the_title( $feat_4_id );
$feat_4_type = get_post_type( $feat_4_id );
$feat_4_permalink = get_permalink( $feat_4_id );
$feat_4_img = get_the_post_thumbnail( $feat_4_id );

2 个答案:

答案 0 :(得分:1)

使用数组和循环。

for ($i=1; $i<=4; $i++) {
    $feat[$i]['id'] = get_theme_mod( 'featured-item-' . $i );
}

答案 1 :(得分:0)

谢谢!这是最终结果。

for ( $i = 1; $i<=4; $i++ ) :
  $feat[$i]['id'] = get_theme_mod( 'featured-item-' . $i );
  $feat[$i]['title'] = get_the_title( $feat[$i]['id'] );
  $feat[$i]['type'] = get_post_type( $feat[$i]['id'] );
  $feat[$i]['permalink'] = get_permalink( $feat[$i]['id'] );
  $feat[$i]['img'] = get_the_post_thumbnail( $feat[$i]['id'] );
  $feat[$i]['excerpt'] = get_the_excerpt( $feat[$i]['id'] );
  if ( $feat[$i]['type'] == 'post' ) :
    $category = get_the_category( $feat[$i]['id'] );
    $feat[$i]['type'] = $category[0]->cat_name;
  endif;
endfor;