Search code examples
phphtmlwordpressob-startob-get-contents

Add span inside anchor output using PHP's ob_get_contents function


What I have:

A PHP function that outputs a log in/out link based on whether the user is correspondingly logged in/out.

<a href="foo">bar</a>

What I need:

I need a span wrapped around the link text inside the anchor element.

<a href="foo"><span>bar</span></a>

My code:

add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {

        ob_start();
        wp_loginout('index.php');
        $loginoutlink = ob_get_contents();
        ob_end_clean();

        $items .= '<li>'. $loginoutlink .'</li>';

    return $items;
}

I've checked the wp_loginout() function for a potential parameter but the two that exist do not apply:

<?php wp_loginout( $redirect, $echo ); ?>

My question:

How can I wrap a span inside the anchor using a server-side approach. I don't want to have to resort to client-side approaches like JavaScript.


Solution

  • try,

    wp_logout_url ( string $redirect = '' ) function instead of wp_loginout('index.php')

    example,

        ob_start();
        wp_logout_url('index.php');
        $logoutlink= ob_get_contents();
        ob_end_clean();
    
        $items .= '<a href="'.$logoutlink.'"'><span></span></a>;
    

    use is_user_logged_in() to check weather user logged in or not.

    ob_start();
    if (is_user_logged_in()) {
        wp_logout_url('index.php');
    } else {
        site_url('index.php') 
    }