Search code examples
phpwordpressfunctiontemplate-engine

How to show function result correctly


I need to write simple script which could send emails or SMS. And I need to get function result and assign it to some variable. For example $message = message(); and get $message in script which are sending SMS.

This is sample of my code:

function message() { $argsvsq = array( 'date_query' => array(
    array(
        'year' => date( 'Y' ),
        'week' => date( 'W' ),
    ),
),
            'author__in' => array($_GET["sendtoid"]),
            'post_type' => 'ocinky',
            'meta_key' => 'wpcf-date',
            'orderby' => 'meta_value',
            'order' => 'DESC',
            'posts_per_page' => -1
             );

        $looper = new WP_Query( $argsvsq );
        // Start the Loop.
        while ( $looper->have_posts() ) : $looper->the_post(); $urok = types_render_field("urok", array("output"=>"HTML")); echo $urok; endwhile;

        }

and this is line where I need to show result

$text_sms = iconv('windows-1251', 'utf-8', message() );

Please, help to get result of function message() correctly... Many thanks!


Solution

  • iconv takes a string as a 3rd parameter. Your message() functiondoes not return anything.

    You can use outputbuffering to fix that simply:

    function message() { $argsvsq = array( 'date_query' => array(
        array(
            'year' => date( 'Y' ),
            'week' => date( 'W' ),
        ),
    ),
        'author__in' => array($_GET["sendtoid"]),
        'post_type' => 'ocinky',
        'meta_key' => 'wpcf-date',
        'orderby' => 'meta_value',
        'order' => 'DESC',
        'posts_per_page' => -1
    );
        ob_start();
        $looper = new WP_Query( $argsvsq );
        // Start the Loop.
        while ( $looper->have_posts() ) : $looper->the_post(); 
            $urok = types_render_field("urok", array("output"=>"HTML")); 
            echo $urok; 
        endwhile;
    
        return ob_get_clean();
    }
    

    It may be possable to just append to and return a string instead of using output buffering:

    function message() { $argsvsq = array( 'date_query' => array(
        array(
            'year' => date( 'Y' ),
            'week' => date( 'W' ),
        ),
    ),
        'author__in' => array($_GET["sendtoid"]),
        'post_type' => 'ocinky',
        'meta_key' => 'wpcf-date',
        'orderby' => 'meta_value',
        'order' => 'DESC',
        'posts_per_page' => -1
    );
        $return = ''
        $looper = new WP_Query( $argsvsq );
        // Start the Loop.
        while ( $looper->have_posts() ) : $looper->the_post(); 
            $urok = types_render_field("urok", array("output"=>"HTML")); 
            $return .= $urok; 
        endwhile;
    
        return $return;
    }
    

    But i dont know what all those function calls are doing (if they echo anything, you will need to use the 1st method