0
function test_dashboard_content() {
    $args = array( 'posts_per_page' => -1, 'post_type' => array( 'post', 'page' ), 'post_status' => 'publish', 'date_query' => array( 'after' => '1 year ago' ) );
    $posts = get_posts( $args );
    $allowed = '';
    $testlist = '';
    foreach ( $posts as $post ) {
        $testlist .= '{date: "' . esc_js( get_the_date( 'Y-n-j', $post ) ) . '", value: "' . esc_js( '1' ) . '"},';
    }
    echo '
    <script>
    jQuery(document).ready(function($) {
        var massive = [
            ' . wp_kses( $testlist, $allowed ) . '
        ];
    });
    </script>';
}

Functionally, everything is as I want it, but security wise, is there anything I should be doing different than the use of esc_js and wp_kses here?

2

1 Answer 1

0

The wp_kses() call looks to me unneccessary as you're already escaping the values within the foreach loop. esc_js() should be just fine as the strings are mostly hard-coded and the only part that is changing is the date value, so escape that. If value is always 1, then escaping it doesn't add any real value.

If you want to make the code a bit more readable, I would suggest first mapping the posts into a PHP array and then turning it into script friendly format with json_encode() and wp_add_inline_script(). This way there is a smaller risk of having typos in the code and data variable.

function test_dashboard_content(): void {
    $testlist = json_encode( wpse_425118_get_posts_data() );
    
    wp_add_inline_script(
        'my-script-handle',
        "var massive = {$testlist};",
        'before'
    );
}

function wpse_425118_get_posts_data(): array {
    $posts = get_posts( array( 
        'posts_per_page' => -1,
        'post_type' => array( 'post', 'page' ),
        'post_status' => 'publish',
        'date_query' => array( 'after' => '1 year ago' )
    ) );

    return array_map(
        function( WP_Post $post ) {
            return array(
                'date' => esc_attr( get_the_date( 'Y-n-j', $post ) ),
                'value' => 1,
            );
        },
        $posts
    );
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.