0

I am a newbe in wordpress theme development. Can anyone tell me where I should implement the code for any ajax functionalities(say a voting system for posts)? should I write it on a separate plugin or as a custom code in functions.php please do explain your reason, thanks.

  • have you considered using REST API endpoints instead? They're much easier to secure, and when you make a mistake they'll say what it was in plain english! AJAX endpoints just return 0 or blank when something wasn't done right – Tom J Nowell Jun 26 '18 at 14:23
  • Your consideration should be, is it code, functionality you want to have independent from the specific theme in use. Imagine the case where you want to change your websites design, the theme, but you want to keep the voting system. If you tied the functionality in with your theme, you have to transfer it, which is additional work. So my suggestion would be to do it correct, and separate functionalities, and make it a plugin in the first place. – Nicolai Jun 26 '18 at 14:24
1

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

| improve this answer | |
0

Too low to comment — please see this helpful guide on updating posts with ajax. You can use this to update_post_meta() to +1 per click and then update the frontend number by +1 for visual effect. Upon refresh, it'll be the new +1'd value.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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