2

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:

 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?

1 Answer 1

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>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just missing </a> in the last $replace . = ... and, thats work correclty :)
Tweaked as needed. Glad to hear it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.