Question

I'm working on WordPress I'm trying to write foreach to the get_the_author_meta here href and <i class="fa fa-facebook"></i> coming dynamically how should i write in a loop this is my code

echo '<ul class="at__social">';
if ( get_the_author_meta( 'google' ) ) :
    echo '<li><a target="_blank" class="author__social" href="http://plus.google.com/' . esc_url( get_the_author_meta( 'google' ) ) . '?rel=author"><i class="fa fa-google-plus"></i></a></li>';
endif;
if ( get_the_author_meta( 'pinterest' ) ) :
    echo '<li><a target="_blank" class="author__social" href="http://pinterest.com/' . esc_url( get_the_author_meta( 'pinterest' ) ) . '"><i class="fa fa-pinterest"></i></a></li>';
endif;
if ( get_the_author_meta( 'tumblr' ) ) :
    echo '<li><a target="_blank" class="author__social" href="http://' . esc_url( get_the_author_meta( 'tumblr' ) ) . '.tumblr.com/"><i class="fa fa-tumblr"></i></a></li>';
endif;*/
echo '</ul>';

So far i have tried like this

<?php
    $at_social = '<ul class="at__social">';
    if(!empty($at_social)){
        echo $at_social;
        $author_sociables  = array(
            'facebook',
            'twitter',
            'instagram',
            'google',
            'pinterest',
            'tumblr'
            );
        //$at_link = ;
        //$at_icon = ;
        foreach($author_sociables as $value){
            if ( get_the_author_meta( $value ) ) :
                echo '<li><a target="_blank" class="author__social" href=" . $at_link . ' . esc_url( get_the_author_meta( $value ) ) . '"><i class="fa fa-facebook"></i></a></li>';
            endif;
        }
        echo '</ul>';
    }
Was it helpful?

Solution

Your loop rewrite is good so far, yet you can make it better:

<?php
    $at_social_html = '<ul class="at__social">';
    /* array elements: social-media-name/meta-key => ['href-before-string', 'href-after-string', 'fa-class'] */
    $author_sociables  = array(
        'facebook' => ['', '', 'fa-fb'],
        'twitter' => ['', '', 'fa-twitter'],
        'instagram' => ['', '', 'fa-instagram'],
        'google' => ['//plus.google.com/', '', 'fa-google-plus'],
        'pinterest' => ['//pinterest.com/', '', 'fa-pinterest'],
        'tumblr' => ['//', '.tumblr.com/', 'fa-tumblr']
        );
    /* Loop */
    foreach($author_sociables as $key=>$value){
        $at_author_meta_value = get_the_author_meta( $key );
        if ( $at_author_meta_value ) :
            $at_social_html .= '<li><a target="_blank" class="author__social" href="'. $value[0] . esc_url( $at_author_meta_value ) . $value[1]'"><i class="fa '. $value[2] .'"></i></a></li>';
        endif;
    }
    $at_social_html .= '</ul>';

    echo $at_social_html;
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top