WordPress – If Statement in variable

I’m trying to show 3 random categories in my posts.

I use Advanced Custom Fieds plugin to show category image. The if statement is:

Read More
 if ( get_field( 'portada', 'category_' . $cats->term_id ) ) {
echo '<a class="cover margin-ultimos" href="' . get_category_link( $cats->term_id ) . '">';
    echo '<div id="cover-home" class="gray-shadow">';
        echo '<img src="'. get_field( 'portada', 'category_'.$cats->term_id ). '" alt="Portada'. get_cat_name ( $cats->term_id ) . '" />';
    echo '</div>';

And, i’m trying to show this using wp_list_categories, so i added in functions.php file this lines:

 add_filter ( 'wp_list_categories', 'img_before_link_list_categories' );

function img_before_link_list_categories( $list ) {
  $cats = get_categories();
    foreach($cats as $cat) {

        $find = $cat->name.'</a>';
        $replace = '//Here the If Statement to show the image';
        $list = str_replace( $find, $replace, $list );

        $list = preg_replace('%<li class=".*">|</?ul>%U', '<h2>', $list);
        $list = str_replace('</li>', '</h2>', $list);
    }
 return $list;
}

How can save the if statement in $replace variable?

Related posts

Leave a Reply

1 comment

  1. $replace = '';
    if( get_field( 'portada', 'category_' . $cats->term_id ) ) 
    {
        $replace .= '<a class="cover margin-ultimos" href="' . get_category_link( $cats->term_id ) . '">';
        $replace .= '<div id="cover-home" class="gray-shadow">';
        $replace .= '<img src="'. get_field( 'portada', 'category_'.$cats->term_id ). '" alt="Portada'. get_cat_name ( $cats->term_id ) . '" />';
        $replace .= '</div>';
        $replace .= '</a>';
    }