Where to add my PHP codes for AJAX Jquery to work?

Here is a general scenario for adding PHP code snippets in WordPress theme or plugin.

  1. Scenario 1: Theme is your custom made theme.

    In this case, you can add code snippets in your own desired way (and obviously in standard way since you are the author of the theme).

  2. Scenario 2: Theme is either premium or downloaded from wordpress.org/themes

    In this case you may want to create a child theme and add the PHP code snippet in functions.php file or create new files and include them in functions.php file (point is it’s up to you as long as you maintain the coding standards). This is because if you don’t create a child theme and add PHP code snippet directly in parent theme’s functions.php file, you will lose all the added code snippets once you update the theme. If you update any Theme or Plugin, all the changes made within their core file will be deleted (since they are replaced by updated plugin or theme files).

  3. Scenario 3: Plugin is your custom built.

    In this case, you can add code anyway you like.

  4. Scenario 4: Plugin is premium or downloaded from wordpress.org/plugins

    you can not add any code snippet to this plugin file. All you do is override the functionality if the plugin allows to do so by providing appropriate hooks (action or filter). And to use these hooks (action or filter), you will still need to add the code in child theme’s functions.php file.

I hope this answer helps you to write your desired code snippet in proper way.

All the best!