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 Answers
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:
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
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.
-
Completed the work used is_singular() condition Commented Jun 30, 2018 at 15:27
0
or blank when something wasn't done right