Where to include php files in wordpress and how to refer to them later2019 Community Moderator ElectionHow to manage ajax calls and JSON in wordpressproblem with ajax and the path to the php pageCreating custom AJAX requestsajax, right way to do it and make it works?Using AJAX and PHP to load next post objectWhere should i put my php script for ajax implementation in wordpress?How to send get request to file.php right and where to store that file.php?Wordpress forms submissions and PHP files$_SESSION inside php function executed by AJAXNeed help with AJAX login to call php in functions.php to handle redirects based on user cap (role)

Modeling an IPv4 Address

Do I have a twin with permutated remainders?

Why, historically, did Gödel think CH was false?

How to format long polynomial?

Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)

LaTeX closing $ signs makes cursor jump

Theorems that impeded progress

Are the number of citations and number of published articles the most important criteria for a tenure promotion?

Which models of the Boeing 737 are still in production?

How could an uplifted falcon's brain work?

Why does Kotter return in Welcome Back Kotter?

"You are your self first supporter", a more proper way to say it

What does it mean to describe someone as a butt steak?

Mage Armor with Defense fighting style (for Adventurers League bladeslinger)

How old can references or sources in a thesis be?

Why are 150k or 200k jobs considered good when there are 300k+ births a month?

What would happen to a modern skyscraper if it rains micro blackholes?

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

How to find program name(s) of an installed package?

Why can't I see bouncing of a switch on an oscilloscope?

How to write a macro that is braces sensitive?

Why was the small council so happy for Tyrion to become the Master of Coin?

Is it important to consider tone, melody, and musical form while writing a song?



Where to include php files in wordpress and how to refer to them later



2019 Community Moderator ElectionHow to manage ajax calls and JSON in wordpressproblem with ajax and the path to the php pageCreating custom AJAX requestsajax, right way to do it and make it works?Using AJAX and PHP to load next post objectWhere should i put my php script for ajax implementation in wordpress?How to send get request to file.php right and where to store that file.php?Wordpress forms submissions and PHP files$_SESSION inside php function executed by AJAXNeed help with AJAX login to call php in functions.php to handle redirects based on user cap (role)



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I am currently creating a customize web page and I am willing to refer to a php file inside an ajax command open(GET,"url php",true) so my question is where to put my php file so that it would be seen by this snippet and how to call it.



Thanks










share|improve this question









New contributor




ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3





    have you looked at creating a REST API endpoints? You should never ping a PHP file directly in WP as it has security and maintainability consequences

    – Tom J Nowell
    Apr 3 at 10:51

















2















I am currently creating a customize web page and I am willing to refer to a php file inside an ajax command open(GET,"url php",true) so my question is where to put my php file so that it would be seen by this snippet and how to call it.



Thanks










share|improve this question









New contributor




ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3





    have you looked at creating a REST API endpoints? You should never ping a PHP file directly in WP as it has security and maintainability consequences

    – Tom J Nowell
    Apr 3 at 10:51













2












2








2


1






I am currently creating a customize web page and I am willing to refer to a php file inside an ajax command open(GET,"url php",true) so my question is where to put my php file so that it would be seen by this snippet and how to call it.



Thanks










share|improve this question









New contributor




ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I am currently creating a customize web page and I am willing to refer to a php file inside an ajax command open(GET,"url php",true) so my question is where to put my php file so that it would be seen by this snippet and how to call it.



Thanks







php ajax






share|improve this question









New contributor




ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Apr 3 at 14:46









rudtek

3,73821439




3,73821439






New contributor




ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Apr 3 at 10:05









ahmedahmed

71




71




New contributor




ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 3





    have you looked at creating a REST API endpoints? You should never ping a PHP file directly in WP as it has security and maintainability consequences

    – Tom J Nowell
    Apr 3 at 10:51












  • 3





    have you looked at creating a REST API endpoints? You should never ping a PHP file directly in WP as it has security and maintainability consequences

    – Tom J Nowell
    Apr 3 at 10:51







3




3





have you looked at creating a REST API endpoints? You should never ping a PHP file directly in WP as it has security and maintainability consequences

– Tom J Nowell
Apr 3 at 10:51





have you looked at creating a REST API endpoints? You should never ping a PHP file directly in WP as it has security and maintainability consequences

– Tom J Nowell
Apr 3 at 10:51










3 Answers
3






active

oldest

votes


















4














You can put your code in a plugin, then create a REST API endpoint.



For example lets create a plugin, just put a PHP file with a comment in it at the top like this:



<?php
/**
* Plugin Name: Ahmeds Plugin
**/


Now you'll see "Ahmeds Plugin" in the plugins folder. You can put WP code in here that will run such as filters, actions, classes, etc. Some people put these things in their themes functions.php, but themes are for visuals/presentation, and you lose it all when you switch a theme.



Now lets make an endpoint your javascript can make a request to. Start by telling WP you want to create an endpoint:



add_action( 'rest_api_init', function () // when WP sets up the REST API
register_rest_route( // tell it we want an endpoint
'ahmed/v1', '/test/', // at example.com/wp-json/ahmed/v1/test
[
'methods' => 'GET', // that it handles GET requests
'callback' => 'ahmed_test_endpoint' // and calls this function when hit
]
);
);


When you visit /wp-json/ahmed/v1/test it will run the function ahmed_test_endpoint, so lets create that function:



function ahmed_test_endpoint( $request ) 
return 'Hello World';



The REST API will take whatever you return, JSON encode it, and send it out. You can return a WP_Error object if something goes wrong and it will change the HTTP codes etc and output the message. If you need any of the parameters, use the $request object, e.g. if you added ?bananas=yummy to the URL, then $request['bananas'] will contain "yummy", just like $_GET.



Remember to flush/resave your permalinks when you add a new endpoint!



Now when we go to yoursite.com/wp-json/ahmed/v1/test you'll see "Hello World"



If you like, you can expand register_rest_route to add more information, such as which parameters your code expects, how to validate them, checking if the user is logged in and has permission to do what they want to do, etc.



If you do this, the REST API will even help you out, so if you tell it there's going to be an ID parameter, but none is given, it'll tell you the ID parameter is missing. Admin AJAX, or stand alone PHP files won't do this, and it makes debugging very difficult. It also greatly improves security



Why Not A Standalone PHP File?



  1. WP APIs won't be available so you'll need to bootstrap WP manually, which is painful

  2. The endpoint is available even if your plugin/theme is deactivated which can pose a security issue

  3. Other plugins can't hook into it, so no benefits from caching or optimisation plugins, so there's a possible performance penalty

  4. You'll need to roll out all the security checks yourself, building them manually, and that's not easy. WP will do them for you if you use the REST API

In the olden days, the solution was to use the Admin AJAX API, but it doesn't do a lot for you. Also, it's very unforgiving, if you don't match your AJAX actions correctly, you get a cryptic response. It also does no checking beyond logged in/out, no validation or sanitisation, and no discovery mechanisms






share|improve this answer

























  • i didnt get where to put this empty php file should i create this "ahmeds plugin" folder in plugins

    – ahmed
    Apr 3 at 11:28












  • A plugin is just a PHP file in the plugins folder with a comment at the top, in a very literal sense. A good example is the hello-dolly.php file that comes with every WP install. You could put it in a subfolder if you really want to, but it's not necessary, notice I made no mention of creating folders in my answer, there were no missing steps to fill in, create a PHP file in the plugins folder, put a comment at the top, and save, that's all the steps

    – Tom J Nowell
    Apr 3 at 11:41












  • where to put the add action script?

    – ahmed
    Apr 3 at 11:46



















2














If you want to do some AJAX in your theme and you're asking where to put the PHP file that will process such request, then... Nowhere is the real answer...



In WordPress you should deal with AJAX a little bit different than in normal PHP apps. There is already a mechanism for such requests.



So first, you should localize your JS script:



wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );


Then you should use that variable as request address:



// it's important to send "action" in that request - this way WP will know which action should be processing this request
jQuery.get(ajax_object.ajax_url, 'action': 'my_action', ..., ... );


And then you should register your callbacks that will process the request:



add_action( 'wp_ajax_my_action', 'my_action' ); // for logged in users
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for anonymous users
function my_action()
...



You can read more on that topic here:



  • https://codex.wordpress.org/AJAX_in_Plugins





share|improve this answer


















  • 2





    Nice, but a REST API endpoint would have been better, and easier to debug and work with

    – Tom J Nowell
    Apr 3 at 11:03











  • @TomJNowell it depends on what he wants to do (and it's a little bit hard to guess based on the description in question)...

    – Krzysiek Dróżdż
    Apr 3 at 11:06






  • 1





    I can't see a case where the admin ajax API can be used but the REST API can't, the REST API is superior in every conceivable way and does everything Admin AJAX does ( but better )

    – Tom J Nowell
    Apr 3 at 11:08











  • Well, there are a lot of such cases - for example every time when a JS library needs to get HTML or some other format and not a JSON - for instance there are JS search suggestions plugins that do so... They're two available mechanisms and it's very opinion-based... I wouldn't say any of these is superior. If you prefer REST - go for it.

    – Krzysiek Dróżdż
    Apr 3 at 11:20


















0














You should be able to use the functions defined in your PHP files by including it into your functions.php file. It's kinda hard to advice you better without knowing more about your structure. But functions.php seems to be a good location to require your file IMHO.






share|improve this answer








New contributor




Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Hmm, I'm not sure if he wants to include PHP files or he's asking, where should he put a PHP file that will process AJAX calls.

    – Krzysiek Dróżdż
    Apr 3 at 10:49











  • @Krzysiek Dróżdż what i need is how to add a php file that i can refer to from another code like when you program with html you put php tag and the link to a php file thats what i want in to do wordpress

    – ahmed
    Apr 3 at 11:37












  • @Ahmed, do you mean something like php include() and require()? If yes, the WordPress equivalent would be to use get_template_part()

    – jsmod
    Apr 3 at 21:41











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "110"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);






ahmed is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fwordpress.stackexchange.com%2fquestions%2f333343%2fwhere-to-include-php-files-in-wordpress-and-how-to-refer-to-them-later%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














You can put your code in a plugin, then create a REST API endpoint.



For example lets create a plugin, just put a PHP file with a comment in it at the top like this:



<?php
/**
* Plugin Name: Ahmeds Plugin
**/


Now you'll see "Ahmeds Plugin" in the plugins folder. You can put WP code in here that will run such as filters, actions, classes, etc. Some people put these things in their themes functions.php, but themes are for visuals/presentation, and you lose it all when you switch a theme.



Now lets make an endpoint your javascript can make a request to. Start by telling WP you want to create an endpoint:



add_action( 'rest_api_init', function () // when WP sets up the REST API
register_rest_route( // tell it we want an endpoint
'ahmed/v1', '/test/', // at example.com/wp-json/ahmed/v1/test
[
'methods' => 'GET', // that it handles GET requests
'callback' => 'ahmed_test_endpoint' // and calls this function when hit
]
);
);


When you visit /wp-json/ahmed/v1/test it will run the function ahmed_test_endpoint, so lets create that function:



function ahmed_test_endpoint( $request ) 
return 'Hello World';



The REST API will take whatever you return, JSON encode it, and send it out. You can return a WP_Error object if something goes wrong and it will change the HTTP codes etc and output the message. If you need any of the parameters, use the $request object, e.g. if you added ?bananas=yummy to the URL, then $request['bananas'] will contain "yummy", just like $_GET.



Remember to flush/resave your permalinks when you add a new endpoint!



Now when we go to yoursite.com/wp-json/ahmed/v1/test you'll see "Hello World"



If you like, you can expand register_rest_route to add more information, such as which parameters your code expects, how to validate them, checking if the user is logged in and has permission to do what they want to do, etc.



If you do this, the REST API will even help you out, so if you tell it there's going to be an ID parameter, but none is given, it'll tell you the ID parameter is missing. Admin AJAX, or stand alone PHP files won't do this, and it makes debugging very difficult. It also greatly improves security



Why Not A Standalone PHP File?



  1. WP APIs won't be available so you'll need to bootstrap WP manually, which is painful

  2. The endpoint is available even if your plugin/theme is deactivated which can pose a security issue

  3. Other plugins can't hook into it, so no benefits from caching or optimisation plugins, so there's a possible performance penalty

  4. You'll need to roll out all the security checks yourself, building them manually, and that's not easy. WP will do them for you if you use the REST API

In the olden days, the solution was to use the Admin AJAX API, but it doesn't do a lot for you. Also, it's very unforgiving, if you don't match your AJAX actions correctly, you get a cryptic response. It also does no checking beyond logged in/out, no validation or sanitisation, and no discovery mechanisms






share|improve this answer

























  • i didnt get where to put this empty php file should i create this "ahmeds plugin" folder in plugins

    – ahmed
    Apr 3 at 11:28












  • A plugin is just a PHP file in the plugins folder with a comment at the top, in a very literal sense. A good example is the hello-dolly.php file that comes with every WP install. You could put it in a subfolder if you really want to, but it's not necessary, notice I made no mention of creating folders in my answer, there were no missing steps to fill in, create a PHP file in the plugins folder, put a comment at the top, and save, that's all the steps

    – Tom J Nowell
    Apr 3 at 11:41












  • where to put the add action script?

    – ahmed
    Apr 3 at 11:46
















4














You can put your code in a plugin, then create a REST API endpoint.



For example lets create a plugin, just put a PHP file with a comment in it at the top like this:



<?php
/**
* Plugin Name: Ahmeds Plugin
**/


Now you'll see "Ahmeds Plugin" in the plugins folder. You can put WP code in here that will run such as filters, actions, classes, etc. Some people put these things in their themes functions.php, but themes are for visuals/presentation, and you lose it all when you switch a theme.



Now lets make an endpoint your javascript can make a request to. Start by telling WP you want to create an endpoint:



add_action( 'rest_api_init', function () // when WP sets up the REST API
register_rest_route( // tell it we want an endpoint
'ahmed/v1', '/test/', // at example.com/wp-json/ahmed/v1/test
[
'methods' => 'GET', // that it handles GET requests
'callback' => 'ahmed_test_endpoint' // and calls this function when hit
]
);
);


When you visit /wp-json/ahmed/v1/test it will run the function ahmed_test_endpoint, so lets create that function:



function ahmed_test_endpoint( $request ) 
return 'Hello World';



The REST API will take whatever you return, JSON encode it, and send it out. You can return a WP_Error object if something goes wrong and it will change the HTTP codes etc and output the message. If you need any of the parameters, use the $request object, e.g. if you added ?bananas=yummy to the URL, then $request['bananas'] will contain "yummy", just like $_GET.



Remember to flush/resave your permalinks when you add a new endpoint!



Now when we go to yoursite.com/wp-json/ahmed/v1/test you'll see "Hello World"



If you like, you can expand register_rest_route to add more information, such as which parameters your code expects, how to validate them, checking if the user is logged in and has permission to do what they want to do, etc.



If you do this, the REST API will even help you out, so if you tell it there's going to be an ID parameter, but none is given, it'll tell you the ID parameter is missing. Admin AJAX, or stand alone PHP files won't do this, and it makes debugging very difficult. It also greatly improves security



Why Not A Standalone PHP File?



  1. WP APIs won't be available so you'll need to bootstrap WP manually, which is painful

  2. The endpoint is available even if your plugin/theme is deactivated which can pose a security issue

  3. Other plugins can't hook into it, so no benefits from caching or optimisation plugins, so there's a possible performance penalty

  4. You'll need to roll out all the security checks yourself, building them manually, and that's not easy. WP will do them for you if you use the REST API

In the olden days, the solution was to use the Admin AJAX API, but it doesn't do a lot for you. Also, it's very unforgiving, if you don't match your AJAX actions correctly, you get a cryptic response. It also does no checking beyond logged in/out, no validation or sanitisation, and no discovery mechanisms






share|improve this answer

























  • i didnt get where to put this empty php file should i create this "ahmeds plugin" folder in plugins

    – ahmed
    Apr 3 at 11:28












  • A plugin is just a PHP file in the plugins folder with a comment at the top, in a very literal sense. A good example is the hello-dolly.php file that comes with every WP install. You could put it in a subfolder if you really want to, but it's not necessary, notice I made no mention of creating folders in my answer, there were no missing steps to fill in, create a PHP file in the plugins folder, put a comment at the top, and save, that's all the steps

    – Tom J Nowell
    Apr 3 at 11:41












  • where to put the add action script?

    – ahmed
    Apr 3 at 11:46














4












4








4







You can put your code in a plugin, then create a REST API endpoint.



For example lets create a plugin, just put a PHP file with a comment in it at the top like this:



<?php
/**
* Plugin Name: Ahmeds Plugin
**/


Now you'll see "Ahmeds Plugin" in the plugins folder. You can put WP code in here that will run such as filters, actions, classes, etc. Some people put these things in their themes functions.php, but themes are for visuals/presentation, and you lose it all when you switch a theme.



Now lets make an endpoint your javascript can make a request to. Start by telling WP you want to create an endpoint:



add_action( 'rest_api_init', function () // when WP sets up the REST API
register_rest_route( // tell it we want an endpoint
'ahmed/v1', '/test/', // at example.com/wp-json/ahmed/v1/test
[
'methods' => 'GET', // that it handles GET requests
'callback' => 'ahmed_test_endpoint' // and calls this function when hit
]
);
);


When you visit /wp-json/ahmed/v1/test it will run the function ahmed_test_endpoint, so lets create that function:



function ahmed_test_endpoint( $request ) 
return 'Hello World';



The REST API will take whatever you return, JSON encode it, and send it out. You can return a WP_Error object if something goes wrong and it will change the HTTP codes etc and output the message. If you need any of the parameters, use the $request object, e.g. if you added ?bananas=yummy to the URL, then $request['bananas'] will contain "yummy", just like $_GET.



Remember to flush/resave your permalinks when you add a new endpoint!



Now when we go to yoursite.com/wp-json/ahmed/v1/test you'll see "Hello World"



If you like, you can expand register_rest_route to add more information, such as which parameters your code expects, how to validate them, checking if the user is logged in and has permission to do what they want to do, etc.



If you do this, the REST API will even help you out, so if you tell it there's going to be an ID parameter, but none is given, it'll tell you the ID parameter is missing. Admin AJAX, or stand alone PHP files won't do this, and it makes debugging very difficult. It also greatly improves security



Why Not A Standalone PHP File?



  1. WP APIs won't be available so you'll need to bootstrap WP manually, which is painful

  2. The endpoint is available even if your plugin/theme is deactivated which can pose a security issue

  3. Other plugins can't hook into it, so no benefits from caching or optimisation plugins, so there's a possible performance penalty

  4. You'll need to roll out all the security checks yourself, building them manually, and that's not easy. WP will do them for you if you use the REST API

In the olden days, the solution was to use the Admin AJAX API, but it doesn't do a lot for you. Also, it's very unforgiving, if you don't match your AJAX actions correctly, you get a cryptic response. It also does no checking beyond logged in/out, no validation or sanitisation, and no discovery mechanisms






share|improve this answer















You can put your code in a plugin, then create a REST API endpoint.



For example lets create a plugin, just put a PHP file with a comment in it at the top like this:



<?php
/**
* Plugin Name: Ahmeds Plugin
**/


Now you'll see "Ahmeds Plugin" in the plugins folder. You can put WP code in here that will run such as filters, actions, classes, etc. Some people put these things in their themes functions.php, but themes are for visuals/presentation, and you lose it all when you switch a theme.



Now lets make an endpoint your javascript can make a request to. Start by telling WP you want to create an endpoint:



add_action( 'rest_api_init', function () // when WP sets up the REST API
register_rest_route( // tell it we want an endpoint
'ahmed/v1', '/test/', // at example.com/wp-json/ahmed/v1/test
[
'methods' => 'GET', // that it handles GET requests
'callback' => 'ahmed_test_endpoint' // and calls this function when hit
]
);
);


When you visit /wp-json/ahmed/v1/test it will run the function ahmed_test_endpoint, so lets create that function:



function ahmed_test_endpoint( $request ) 
return 'Hello World';



The REST API will take whatever you return, JSON encode it, and send it out. You can return a WP_Error object if something goes wrong and it will change the HTTP codes etc and output the message. If you need any of the parameters, use the $request object, e.g. if you added ?bananas=yummy to the URL, then $request['bananas'] will contain "yummy", just like $_GET.



Remember to flush/resave your permalinks when you add a new endpoint!



Now when we go to yoursite.com/wp-json/ahmed/v1/test you'll see "Hello World"



If you like, you can expand register_rest_route to add more information, such as which parameters your code expects, how to validate them, checking if the user is logged in and has permission to do what they want to do, etc.



If you do this, the REST API will even help you out, so if you tell it there's going to be an ID parameter, but none is given, it'll tell you the ID parameter is missing. Admin AJAX, or stand alone PHP files won't do this, and it makes debugging very difficult. It also greatly improves security



Why Not A Standalone PHP File?



  1. WP APIs won't be available so you'll need to bootstrap WP manually, which is painful

  2. The endpoint is available even if your plugin/theme is deactivated which can pose a security issue

  3. Other plugins can't hook into it, so no benefits from caching or optimisation plugins, so there's a possible performance penalty

  4. You'll need to roll out all the security checks yourself, building them manually, and that's not easy. WP will do them for you if you use the REST API

In the olden days, the solution was to use the Admin AJAX API, but it doesn't do a lot for you. Also, it's very unforgiving, if you don't match your AJAX actions correctly, you get a cryptic response. It also does no checking beyond logged in/out, no validation or sanitisation, and no discovery mechanisms







share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 3 at 11:09

























answered Apr 3 at 11:03









Tom J NowellTom J Nowell

33.2k44799




33.2k44799












  • i didnt get where to put this empty php file should i create this "ahmeds plugin" folder in plugins

    – ahmed
    Apr 3 at 11:28












  • A plugin is just a PHP file in the plugins folder with a comment at the top, in a very literal sense. A good example is the hello-dolly.php file that comes with every WP install. You could put it in a subfolder if you really want to, but it's not necessary, notice I made no mention of creating folders in my answer, there were no missing steps to fill in, create a PHP file in the plugins folder, put a comment at the top, and save, that's all the steps

    – Tom J Nowell
    Apr 3 at 11:41












  • where to put the add action script?

    – ahmed
    Apr 3 at 11:46


















  • i didnt get where to put this empty php file should i create this "ahmeds plugin" folder in plugins

    – ahmed
    Apr 3 at 11:28












  • A plugin is just a PHP file in the plugins folder with a comment at the top, in a very literal sense. A good example is the hello-dolly.php file that comes with every WP install. You could put it in a subfolder if you really want to, but it's not necessary, notice I made no mention of creating folders in my answer, there were no missing steps to fill in, create a PHP file in the plugins folder, put a comment at the top, and save, that's all the steps

    – Tom J Nowell
    Apr 3 at 11:41












  • where to put the add action script?

    – ahmed
    Apr 3 at 11:46

















i didnt get where to put this empty php file should i create this "ahmeds plugin" folder in plugins

– ahmed
Apr 3 at 11:28






i didnt get where to put this empty php file should i create this "ahmeds plugin" folder in plugins

– ahmed
Apr 3 at 11:28














A plugin is just a PHP file in the plugins folder with a comment at the top, in a very literal sense. A good example is the hello-dolly.php file that comes with every WP install. You could put it in a subfolder if you really want to, but it's not necessary, notice I made no mention of creating folders in my answer, there were no missing steps to fill in, create a PHP file in the plugins folder, put a comment at the top, and save, that's all the steps

– Tom J Nowell
Apr 3 at 11:41






A plugin is just a PHP file in the plugins folder with a comment at the top, in a very literal sense. A good example is the hello-dolly.php file that comes with every WP install. You could put it in a subfolder if you really want to, but it's not necessary, notice I made no mention of creating folders in my answer, there were no missing steps to fill in, create a PHP file in the plugins folder, put a comment at the top, and save, that's all the steps

– Tom J Nowell
Apr 3 at 11:41














where to put the add action script?

– ahmed
Apr 3 at 11:46






where to put the add action script?

– ahmed
Apr 3 at 11:46














2














If you want to do some AJAX in your theme and you're asking where to put the PHP file that will process such request, then... Nowhere is the real answer...



In WordPress you should deal with AJAX a little bit different than in normal PHP apps. There is already a mechanism for such requests.



So first, you should localize your JS script:



wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );


Then you should use that variable as request address:



// it's important to send "action" in that request - this way WP will know which action should be processing this request
jQuery.get(ajax_object.ajax_url, 'action': 'my_action', ..., ... );


And then you should register your callbacks that will process the request:



add_action( 'wp_ajax_my_action', 'my_action' ); // for logged in users
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for anonymous users
function my_action()
...



You can read more on that topic here:



  • https://codex.wordpress.org/AJAX_in_Plugins





share|improve this answer


















  • 2





    Nice, but a REST API endpoint would have been better, and easier to debug and work with

    – Tom J Nowell
    Apr 3 at 11:03











  • @TomJNowell it depends on what he wants to do (and it's a little bit hard to guess based on the description in question)...

    – Krzysiek Dróżdż
    Apr 3 at 11:06






  • 1





    I can't see a case where the admin ajax API can be used but the REST API can't, the REST API is superior in every conceivable way and does everything Admin AJAX does ( but better )

    – Tom J Nowell
    Apr 3 at 11:08











  • Well, there are a lot of such cases - for example every time when a JS library needs to get HTML or some other format and not a JSON - for instance there are JS search suggestions plugins that do so... They're two available mechanisms and it's very opinion-based... I wouldn't say any of these is superior. If you prefer REST - go for it.

    – Krzysiek Dróżdż
    Apr 3 at 11:20















2














If you want to do some AJAX in your theme and you're asking where to put the PHP file that will process such request, then... Nowhere is the real answer...



In WordPress you should deal with AJAX a little bit different than in normal PHP apps. There is already a mechanism for such requests.



So first, you should localize your JS script:



wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );


Then you should use that variable as request address:



// it's important to send "action" in that request - this way WP will know which action should be processing this request
jQuery.get(ajax_object.ajax_url, 'action': 'my_action', ..., ... );


And then you should register your callbacks that will process the request:



add_action( 'wp_ajax_my_action', 'my_action' ); // for logged in users
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for anonymous users
function my_action()
...



You can read more on that topic here:



  • https://codex.wordpress.org/AJAX_in_Plugins





share|improve this answer


















  • 2





    Nice, but a REST API endpoint would have been better, and easier to debug and work with

    – Tom J Nowell
    Apr 3 at 11:03











  • @TomJNowell it depends on what he wants to do (and it's a little bit hard to guess based on the description in question)...

    – Krzysiek Dróżdż
    Apr 3 at 11:06






  • 1





    I can't see a case where the admin ajax API can be used but the REST API can't, the REST API is superior in every conceivable way and does everything Admin AJAX does ( but better )

    – Tom J Nowell
    Apr 3 at 11:08











  • Well, there are a lot of such cases - for example every time when a JS library needs to get HTML or some other format and not a JSON - for instance there are JS search suggestions plugins that do so... They're two available mechanisms and it's very opinion-based... I wouldn't say any of these is superior. If you prefer REST - go for it.

    – Krzysiek Dróżdż
    Apr 3 at 11:20













2












2








2







If you want to do some AJAX in your theme and you're asking where to put the PHP file that will process such request, then... Nowhere is the real answer...



In WordPress you should deal with AJAX a little bit different than in normal PHP apps. There is already a mechanism for such requests.



So first, you should localize your JS script:



wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );


Then you should use that variable as request address:



// it's important to send "action" in that request - this way WP will know which action should be processing this request
jQuery.get(ajax_object.ajax_url, 'action': 'my_action', ..., ... );


And then you should register your callbacks that will process the request:



add_action( 'wp_ajax_my_action', 'my_action' ); // for logged in users
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for anonymous users
function my_action()
...



You can read more on that topic here:



  • https://codex.wordpress.org/AJAX_in_Plugins





share|improve this answer













If you want to do some AJAX in your theme and you're asking where to put the PHP file that will process such request, then... Nowhere is the real answer...



In WordPress you should deal with AJAX a little bit different than in normal PHP apps. There is already a mechanism for such requests.



So first, you should localize your JS script:



wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );


Then you should use that variable as request address:



// it's important to send "action" in that request - this way WP will know which action should be processing this request
jQuery.get(ajax_object.ajax_url, 'action': 'my_action', ..., ... );


And then you should register your callbacks that will process the request:



add_action( 'wp_ajax_my_action', 'my_action' ); // for logged in users
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for anonymous users
function my_action()
...



You can read more on that topic here:



  • https://codex.wordpress.org/AJAX_in_Plugins






share|improve this answer












share|improve this answer



share|improve this answer










answered Apr 3 at 10:57









Krzysiek DróżdżKrzysiek Dróżdż

18.5k73249




18.5k73249







  • 2





    Nice, but a REST API endpoint would have been better, and easier to debug and work with

    – Tom J Nowell
    Apr 3 at 11:03











  • @TomJNowell it depends on what he wants to do (and it's a little bit hard to guess based on the description in question)...

    – Krzysiek Dróżdż
    Apr 3 at 11:06






  • 1





    I can't see a case where the admin ajax API can be used but the REST API can't, the REST API is superior in every conceivable way and does everything Admin AJAX does ( but better )

    – Tom J Nowell
    Apr 3 at 11:08











  • Well, there are a lot of such cases - for example every time when a JS library needs to get HTML or some other format and not a JSON - for instance there are JS search suggestions plugins that do so... They're two available mechanisms and it's very opinion-based... I wouldn't say any of these is superior. If you prefer REST - go for it.

    – Krzysiek Dróżdż
    Apr 3 at 11:20












  • 2





    Nice, but a REST API endpoint would have been better, and easier to debug and work with

    – Tom J Nowell
    Apr 3 at 11:03











  • @TomJNowell it depends on what he wants to do (and it's a little bit hard to guess based on the description in question)...

    – Krzysiek Dróżdż
    Apr 3 at 11:06






  • 1





    I can't see a case where the admin ajax API can be used but the REST API can't, the REST API is superior in every conceivable way and does everything Admin AJAX does ( but better )

    – Tom J Nowell
    Apr 3 at 11:08











  • Well, there are a lot of such cases - for example every time when a JS library needs to get HTML or some other format and not a JSON - for instance there are JS search suggestions plugins that do so... They're two available mechanisms and it's very opinion-based... I wouldn't say any of these is superior. If you prefer REST - go for it.

    – Krzysiek Dróżdż
    Apr 3 at 11:20







2




2





Nice, but a REST API endpoint would have been better, and easier to debug and work with

– Tom J Nowell
Apr 3 at 11:03





Nice, but a REST API endpoint would have been better, and easier to debug and work with

– Tom J Nowell
Apr 3 at 11:03













@TomJNowell it depends on what he wants to do (and it's a little bit hard to guess based on the description in question)...

– Krzysiek Dróżdż
Apr 3 at 11:06





@TomJNowell it depends on what he wants to do (and it's a little bit hard to guess based on the description in question)...

– Krzysiek Dróżdż
Apr 3 at 11:06




1




1





I can't see a case where the admin ajax API can be used but the REST API can't, the REST API is superior in every conceivable way and does everything Admin AJAX does ( but better )

– Tom J Nowell
Apr 3 at 11:08





I can't see a case where the admin ajax API can be used but the REST API can't, the REST API is superior in every conceivable way and does everything Admin AJAX does ( but better )

– Tom J Nowell
Apr 3 at 11:08













Well, there are a lot of such cases - for example every time when a JS library needs to get HTML or some other format and not a JSON - for instance there are JS search suggestions plugins that do so... They're two available mechanisms and it's very opinion-based... I wouldn't say any of these is superior. If you prefer REST - go for it.

– Krzysiek Dróżdż
Apr 3 at 11:20





Well, there are a lot of such cases - for example every time when a JS library needs to get HTML or some other format and not a JSON - for instance there are JS search suggestions plugins that do so... They're two available mechanisms and it's very opinion-based... I wouldn't say any of these is superior. If you prefer REST - go for it.

– Krzysiek Dróżdż
Apr 3 at 11:20











0














You should be able to use the functions defined in your PHP files by including it into your functions.php file. It's kinda hard to advice you better without knowing more about your structure. But functions.php seems to be a good location to require your file IMHO.






share|improve this answer








New contributor




Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Hmm, I'm not sure if he wants to include PHP files or he's asking, where should he put a PHP file that will process AJAX calls.

    – Krzysiek Dróżdż
    Apr 3 at 10:49











  • @Krzysiek Dróżdż what i need is how to add a php file that i can refer to from another code like when you program with html you put php tag and the link to a php file thats what i want in to do wordpress

    – ahmed
    Apr 3 at 11:37












  • @Ahmed, do you mean something like php include() and require()? If yes, the WordPress equivalent would be to use get_template_part()

    – jsmod
    Apr 3 at 21:41















0














You should be able to use the functions defined in your PHP files by including it into your functions.php file. It's kinda hard to advice you better without knowing more about your structure. But functions.php seems to be a good location to require your file IMHO.






share|improve this answer








New contributor




Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Hmm, I'm not sure if he wants to include PHP files or he's asking, where should he put a PHP file that will process AJAX calls.

    – Krzysiek Dróżdż
    Apr 3 at 10:49











  • @Krzysiek Dróżdż what i need is how to add a php file that i can refer to from another code like when you program with html you put php tag and the link to a php file thats what i want in to do wordpress

    – ahmed
    Apr 3 at 11:37












  • @Ahmed, do you mean something like php include() and require()? If yes, the WordPress equivalent would be to use get_template_part()

    – jsmod
    Apr 3 at 21:41













0












0








0







You should be able to use the functions defined in your PHP files by including it into your functions.php file. It's kinda hard to advice you better without knowing more about your structure. But functions.php seems to be a good location to require your file IMHO.






share|improve this answer








New contributor




Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










You should be able to use the functions defined in your PHP files by including it into your functions.php file. It's kinda hard to advice you better without knowing more about your structure. But functions.php seems to be a good location to require your file IMHO.







share|improve this answer








New contributor




Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this answer



share|improve this answer






New contributor




Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









answered Apr 3 at 10:28









HitoHito

1011




1011




New contributor




Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Hito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1





    Hmm, I'm not sure if he wants to include PHP files or he's asking, where should he put a PHP file that will process AJAX calls.

    – Krzysiek Dróżdż
    Apr 3 at 10:49











  • @Krzysiek Dróżdż what i need is how to add a php file that i can refer to from another code like when you program with html you put php tag and the link to a php file thats what i want in to do wordpress

    – ahmed
    Apr 3 at 11:37












  • @Ahmed, do you mean something like php include() and require()? If yes, the WordPress equivalent would be to use get_template_part()

    – jsmod
    Apr 3 at 21:41












  • 1





    Hmm, I'm not sure if he wants to include PHP files or he's asking, where should he put a PHP file that will process AJAX calls.

    – Krzysiek Dróżdż
    Apr 3 at 10:49











  • @Krzysiek Dróżdż what i need is how to add a php file that i can refer to from another code like when you program with html you put php tag and the link to a php file thats what i want in to do wordpress

    – ahmed
    Apr 3 at 11:37












  • @Ahmed, do you mean something like php include() and require()? If yes, the WordPress equivalent would be to use get_template_part()

    – jsmod
    Apr 3 at 21:41







1




1





Hmm, I'm not sure if he wants to include PHP files or he's asking, where should he put a PHP file that will process AJAX calls.

– Krzysiek Dróżdż
Apr 3 at 10:49





Hmm, I'm not sure if he wants to include PHP files or he's asking, where should he put a PHP file that will process AJAX calls.

– Krzysiek Dróżdż
Apr 3 at 10:49













@Krzysiek Dróżdż what i need is how to add a php file that i can refer to from another code like when you program with html you put php tag and the link to a php file thats what i want in to do wordpress

– ahmed
Apr 3 at 11:37






@Krzysiek Dróżdż what i need is how to add a php file that i can refer to from another code like when you program with html you put php tag and the link to a php file thats what i want in to do wordpress

– ahmed
Apr 3 at 11:37














@Ahmed, do you mean something like php include() and require()? If yes, the WordPress equivalent would be to use get_template_part()

– jsmod
Apr 3 at 21:41





@Ahmed, do you mean something like php include() and require()? If yes, the WordPress equivalent would be to use get_template_part()

– jsmod
Apr 3 at 21:41










ahmed is a new contributor. Be nice, and check out our Code of Conduct.









draft saved

draft discarded


















ahmed is a new contributor. Be nice, and check out our Code of Conduct.












ahmed is a new contributor. Be nice, and check out our Code of Conduct.











ahmed is a new contributor. Be nice, and check out our Code of Conduct.














Thanks for contributing an answer to WordPress Development Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fwordpress.stackexchange.com%2fquestions%2f333343%2fwhere-to-include-php-files-in-wordpress-and-how-to-refer-to-them-later%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020