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.

2
  • 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
    Commented Jun 26, 2018 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. Commented Jun 26, 2018 at 14:24

2 Answers 2

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

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.

1
  • Completed the work used is_singular() condition Commented Jun 30, 2018 at 15:27

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.