How to debug vars inside function at functions.php file?

I have this function:

function wpse_210493_apply_advertising_position( &$posts, $return = false ) {
    $ad_posts = array();

    $content_posts = array_filter(
        $posts,
        function ( $post ) {
            $position = get_post_meta( $post->ID, 'rw_adversiting_position', true );

            if ( empty( $position ) ) {
                return true;
            }

            $ad_posts[ intval( $position ) ] = $post;

            return false;
        } );

    $content_posts = array_values( $content_posts );

    ksort( $ad_posts );

    echo "sdfksfkjshdfsdf";

    foreach ( $ad_posts as $position => $ad ) {
        array_splice( $content_posts, $position, 0, $ad );
    }

    if ( $return ) {
        return $content_posts;
    } else {
        $posts = $content_posts;
    }
}

I need to debug $ad_posts after the ksort() but output is not going to browser. I did test with the echo you see there and that text also is not going to browser as output. How do I debug the values properly?

3 Answers
3

You can simply use var_dump() to do this. That is how I check values inside functions and filters.

I have the following line of code in a file which I simply copy and paste where needed to dump the value of a variable

?><pre><?php var_dump( $variable_to_test ); ?></pre><?php

The pre tags dump a nice readable array/object/string depending on the value. Inside your function you can just do

?><pre><?php var_dump($ad_posts); ?></pre><?php 

after ksort( $ad_posts );.

Just make sure to call the function somewhere if it is not hooked to some kind of hook otherwise nothing will happen

Leave a Comment