Cole
Cole

Reputation: 317

Better Optimization For Common Variables

I am trying to learn more about optimizing PHP and working with common variables. As you can see below, I will be basically duplicating the same functions to create data for 4 different positions within a template. I am trying to see what is the best way to optimize this variable storage and more efficient.

I had thought about doing some loops or storing in array's just want to make sure I do it the most efficient way so I can learn for future uses. Any help on this would be great appreciated.

$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 );

Upvotes: 0

Views: 29

Answers (2)

Cole
Cole

Reputation: 317

Thank You! Here is the final result.

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;

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

Make use of arrays and loops.

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

Upvotes: 1

Related Questions