Where Should i write the code for wordpress ajax voting?

Use REST API endpoint instead!

Lets register an endpoint at /wp-json/tomjn/v1/test, that calls tomjn_rest_test() when you hit it:

add_action( 'rest_api_init', function () {
        register_rest_route( 'tomjn/v1', '/test/', array(
                'methods' => 'GET',
                'callback' => 'tomjn_rest_test'
        ) );
} );

Now lets add the tomjn_rest_test function:

function tomjn_rest_test( $request ) {
        return "moomins";
}

Now when we visit tomjn.com/wp-json/tomjn/v1/test we get:

enter image description here

Now we can grab it on the frontend:

<script>
jQuery.ajax({
    url: <?php echo wp_json_encode( esc_url_raw( rest_url( 'tomjn/v1/test' ) ) ); ?>
}).done(function( data ) {
    // do something
    jQuery( '#tomsword' ).text( data );
});
</script>

That code looks for a <div id="tomsword"> and sets the contents to whatever the endpoint returned.

But Where Do I Put The Code? Theme or Plugin?

You can register you endpoints in a plugin or theme, just remember:

  • themes determine how your site looks
  • plugins determine what you site can do

Voting sounds like functionality, not decoration, and should go in a plugin.

If you put it in a theme, then that functionality is forever trapped in that theme unless a developer manually extracts it. Any voting data is unavailable as soon as the user changes the theme