Where to put my custom functions in Wordpress? - php

I am pulling my hair out. I have created some simple functions that generate random numbers, pulled from a database that I want to use on wordpress pages. (And then call them from the theme files, such as header.php or page.php.)
I have tried putting the functions inside functions.php that is in the theme (as per the documentation I have read), but I keep getting the "call to undefined function" errors! What in the world am I doing wrong?
Example, here is a function inside the functions.php
function randomPollNumber() {
///this gets a random active poll number
$sql12 = "SELECT id FROM poll WHERE removed = 0 AND active = 1 ORDER BY RAND() LIMIT 1";
$result12 = mysql_query($sql12);
$myrow12 = mysql_fetch_row($result12);
$pollquestionid = $myrow12[0];
return $pollquestionid;
}
And I am calling it, from the header.php file with this
<?php echo randomPollNumber(); ?>
And yes, I DID try using the if_function_exists, but of course it cannot FIND the function, so of course it does not exist. Please help?

Very strange - some debugging tips:
Put die('functions.php file loaded') statement at the beginning of functions.php (not inside a function). If it doesn't die, you know the file isn't being loaded.
If it dies, then check your spelling (copy and paste the function name from functions.php into your echo [...]). It's amazing how many times I'm SURE I've spelt it right, when in fact I haven't.
If it doesn't die, check that your file is definitely called functions.php, that it's definitely inside the right theme folder for the theme you are coding.
It's possible that the functions.php file has an error in it, and so is not being parsed, hence Wordpress can't find the function. Check your logs for errors. Load the functions file and nothing else, and check that the function is working. Are you using PHP Unit or something like that?

Related

Use of undefined constant ABSPATH

I am using WP for the first time. I'm just trying to create a very basic script to echo the user's id and am having all sorts of issues.
The code is this and is currently located in wp-content/plugins (i'm not really sure where these things should be):
<?php
require_once ABSPATH . '/wp-includes/pluggable.php';
$user = wp_get_current_user();
echo $user->get_site_id();
I'd had it without the require initially but I was getting a function not defined error for wp_get_current_user. Now I'm getting Warning: Use of undefined constant ABSPATH - assumed 'ABSPATH'...
Is there some sort of predefined set of files that I need to include or some specific directory I need to be putting my scripts so that these variables and functions are in scope? My understanding was that these things are supposed to be global.
Did you try code like that:
add_action('init', 'some_function_name');
function some_function_name() {
$user = wp_get_current_user();
echo $user->get_site_id();
}
The WordPress comes with hooks (actions and filters) to let other developers modify either core parts of the WordPress or code from other plugins / themes.
The code I describe in my answer, it is running your code when the whole WordPress , all the Plugins and the theme are loaded, thus you should have by default the wp_get_current_user() function and you should not need to include manually the pluggable.php.
This seems like is going to solve your problem.
Read more on hooks here: https://developer.wordpress.org/plugins/hooks/.
Side note. Keep in mind that in order to run your custom code you should register a proper WordPress plugin and activate it. If you have made a php file in the plugins folder, and you loaded using PHP functions like require/include the plugin probably will not operate as you expect although the source code it could be perfect. To get more details on how to write your own plugin, you could read here: https://developer.wordpress.org/plugins/

wordpress php add value to database

I'm very new to the idea of adding values to a database, so would like some advise on whether this is possible and how I would do it.
I have a code that counts the lines of code written in a project, the code has to be in the folder that it is counting the lines of code from however I want to display this number on my site elsewhere. My site is a wordpress one, so i thought of sending this number to the database and calling on it in a template file elsewhere.
Is there a way to send this number to my database and have it keep up to date in real-time so that I can call it from other places in my site?
My LOC script can be seen running here:
http://www.skizzar.com/wp-content/loc.php
and the number is displayed using the command:
$folder -> count_lines()
update
I've added the following code to my loc.php
$num_of_lines = $folder -> count_lines();
add_option('line_count', $num_of_lines);
And called it in my theme files using
echo get_option('line_count', '0');
So far this just returns 0 as the value and causes a fatal error on loc.php "call to undefined function..."
Second update
Got the code to work by adding
require_once('wp-config.php');
To the top of my code, the issue now is that it doesn't update in real time - is there a way to do this?
Assuming you are saving the value to the database with wordpress as well, use add_option and get_option. Something like this:
add_option('line_count', $num_of_lines);
And in your template, display it with:
echo get_option('line_count', '0');

500 Internal server error with new php files on server (Wordpress/Woocommerce)

I am getting a strange 500 Internal Server Error with a new script I am trying to implement in the actual site. Here's a screen:
![500 Internal][1]
I can route to this files manually without problems and they are working too. But not in the script itself. The Paths are also correct.
Heres the link to the Site:
[>>> Link <<<][2] (just enter R10369 in the input field or a random number)
Everything else is working correctly except these 3 files:
reseller.php,
checkresellerid.php,
resellermail.php
I googled a bit and everywhere is the .htaccess mentioned. but I never modified it or overwrited it. What could be the Problem? Thanks for any Help and sorry for my bad Englisch.
(Let me know if you want to see the php files)
EDIT: I managed to include my new php files into wordpress but i still got the 500 Error
I checked out the website.
I think Wordpress doesn't let you call .php inside of it's system.
I mean you cannot call PHP files for ajax.
You need to use wordpress ajax. Here is a snippet how to use ajax:
Function.php in your theme file.
function myajax()
{
//do stuff
die();
}
add_action( 'wp_ajax_nopriv_product_s', 'myajax' );
add_action( 'wp_ajax_product_s', 'myajax' );
And in your javascript file using jQuery:
The url may change, maybe it's enough to have wp-admin/admin.ajax.php or something like this, i don't really remember right now.
$.post('/wp-admin/admin-ajax.php',{action:'myajax',yourdata:"mydata"}).done(function(data)
{
//do stuffs
});
Update:
So basically if you want to have ajax request inside wordpresss, you need to define these things and use it like this. the "action" parameter is the function name which you want to call. And you need to put the PHP code into your current theme's function.php.

Open file from a php document, and close it from another?

I am trying to do the following:
Open a file, say "myfile.json" from a php- let's call it "utils.php"; Use it in other php pages; close it from another php.
I have tried to include "utils.php" in the other files and write in the utils file, but it does not seem to work. I suppose this happens because utils.php is never actually executed, only included, but if I should execute it, how can I do it without having to refresh any page, preferably right when the user gets on the main page? This should not be seen by the user, what he sees should remain the main page.
Thanks in advance, I am quite new to php, and am trying to learn.
When you include a file, you are running all code inside it. The functions and classes will not be evaluated but will be defined for future use. If you open your file as this example:
util.php
<?php
$file_hand = fopen('/tmp/file.txt','r');
You will have a handle if the operation is completed. However, the variable $file_hand is global. If you need to use a function to close it, you will need the following code to do it:
other.php
function close_file(){
global $file_hand;
fclose($file_hand)
}
or you can pass the handle as parameter like:
function close_file($file_hand){
fclose($file_hand)
}
Doesn't matter how you will close the file. You have to make sure the variable you are using is the same created in utils.php. If you close like this:
function close_file(){
fclose($file_hand)
}
The variable you've created in until.php file is different of this one.

Shortcodes breaking Wordpress Site

I am creating new shortcodes for Wordpress on my local version of a Wordpress website.
In functions.php, I am adding for example:
function shortTest() {
return 'Test for shortcodes ';
}
add_shortcode('shortTestHTML', 'shortTest');
Adding the function only is OK, but when I add the add_shortcode() portion, I get a major issue.
It breaks something somehow and I get 500 errors, meaning I can't even load my website locally anymore.
Any thoughts???
Thanks so much!
EDIT:
From PHP Error Log:
[21-Jun-2011 19:02:37] PHP Fatal error: Call to undefined function add_shortcode() in /Users/jonas/Sites/jll/wp-includes/functions.php on line 4505
1) Make sure that you have included shortcodes.php file somewhere (for example, in wp-load.php or whatever other more appropriate place may be).
require_once( ABSPATH . '/wp-includes/shortcodes.php' );
2) Make sure that this file does exist on your installation (which I think you have otherwise we would see a different error).
3) Where do you call this function from (I see it is called from functions.php, but which place)? Possible problem here -- functions.php is loaded prior to shortcodes.php, and if you do use that add_shortcode function before shortcodes.php is loaded you most likely will see this error. Double check your code in that place -- maybe move the call to add_shortcode to another place.
mentioned functions.php is not in wp-include/ directory.
it is in: wp-content/themes/<your-theme-name>/functions.php
adding this in functions.php you say? Well I don't know about that, the way I did it was create a folder inside the wp-content/plugins folder, e.g. shortcodetest.
Inside this folder create a shortcodetest.php file.
in that file you basically write your code:
<?php
/*
Plugin Name: ShortCodeTest
Plugin URI: http://www.example.net
Description: Print a test message
Version: 0.1
Author: anonymous
Author URI: http://www.example.net
*/
add_shortcode('shortcodetest', 'shortcodetest_function');
function shortcodetest_function() {
return "test of shortcode";
}
?>
Then you login as admin, you will see a plugin ShortCodeTest, activate it. Then you can use the shortcode in your posts.
Note that the comments are important... they show up in the plugin description.
I got a way to execute them but it's a little triky :)
You need to change a little bit your template by putting your shortcode (for example: [inline ....]) between <shortcode></shortcode> then
Here is the function to place at the end of your function.php.
function parse_execute_and_echo_shortcode($_path) {
$str = file_get_contents($_path);
while (strrpos($str, "<shortcode>")) {
$beginShortcode = strrpos($str, "<shortcode>");
$endShortcode = strrpos($str, "</shortcode>");
$shortcode = substr($str, $beginShortcode + 11, $endShortcode - ($beginShortcode+11));
$shortcode = do_shortcode($shortcode);
$str = substr_replace($str, $shortcode, $beginShortcode, $endShortcode + 12);
}
echo $str;
}
Then you can call function parse_execute_and_echo_shortcode and giving it the path to your file containing the shortcodes.
Hope that can help someone
Check your error.log file (it should be in your apache log folder).
It probably has to do with add_shortcode not existing as a function.
Put your shortcode in the file /wp-includes/shortcodes.php this way you make sure it will be loaded when all the blows and whistles are up and running.

Categories