Feeling bad about an overuse of get_option - wordpress

I've been working with the settings API getting my head wrapped around it. Now that I feel I have a decent understanding of how to use it, I want to optimize how I'm doing it a bit.
My main concern is the use of get_option on every callback to create each of the settings inputs. I was planning on caching them so I didn't need to call get_option 10+ times.
My question is, before I do my caching, does wordpress have its own per-page load cache for get_option?
Thanks,
Max

No, WordPress doesn't have that kind of cache. It even calls get_option() too often.
EDIT #1: wp_load_alloption() will load every single options from database to cache, so get_option() will only load from database if none found on it's cache.
See below (the original answer) To reduce the use of get_option():
I prever to wrap them all to an object to reduce the usage of get_option. I've always do these first thing on my themes:
global $mytheme;
$mytheme = new stdClass;
$mytheme->something = get_option( 'something' );
I do for each setting that repeatedly used on my theme so get_option will only be loaded once.
Next I want the option to be call, I just use:
function something() {
global $mytheme;
$something = $mytheme->something;
return $something;
}

you can store multiple values in 1 option. Just feed update_option or add_option an array.
On the caching note take a look at these links:
http://www.catswhocode.com/blog/wordpress-transients-api-practical-examples
http://codex.wordpress.org/Transients_API

Related

Cron Wordpress Update four post every hour

I have function that update post content automatically based from custom field like this:
function update_content(){
$mycustomfield = get_post_meta( get_the_ID(), 'customfield', true);
$post = array();
$post['ID'] = get_the_ID();
$post['post_content' ] = $mycustomfield ;
$post['post_title' ] = $mycustomfield ;
// Update the post into the database
wp_update_post( $post );
We update only custom field to make content. For now, we launch this function manually on save_post hook, but the articles are so many and we need now a cron to automate this function: process 4 posts every hour until all posts are completed, then start over.
How to make this, thank you
WordPress actually has a built-in psuedo cron system called WP Cron. It doesn't function exactly like a proper server cron, but can perform a similar function in many cases. You can find documentation on it here:
https://developer.wordpress.org/plugins/cron/#:~:text=WP%2DCron%20is%20how%20WordPress,post%2C%20utilize%20WP%2DCron.&text=WP%2DCron%20works%20by%20checking,what%20needs%20to%20be%20run.
However thinking about your use case and looking at your function above, I'm wondering what the purpose of your cron is? It looks from that function like all you're doing is taking some content already in your database and putting it somewhere else. Why? Why not simply display your custom field in the correct spot? Or better yet, use the fields as intended?
Even if that is necessary - maybe I don't understand fully from the example above - I think your initial inclination to run this on save_post is much more correct. Unless there's some information external to your site that's changing, the only time these values will change is when you save the post. So what is the purpose of running it on a schedule?

WordPress constant scope using define method

I'm defining plugin path as a constant through constant define method as shown below.
define( 'MY_PLUGIN_DIR', untrailingslashit( plugin_dir_path( __FILE__ ) ) );
It is accessible within plugin all files and themes. But when I call this constant in another plugin this constant becomes undefined.
How I can get this plugin constant in another plugin? Any help will be appreciated.
Thanks,
Probably your problem is the order that wordpress is calling your plugins: the plugins that sets the constant is loaded after the one who calls it.
A better explanation of how to force your plugin be loaded first can be found here. I'm putting here a quote of the part that matters:
The order that plugins are loaded (as of WP 2.9.1 at least) is determined by the order of an array stored as "active_plugins" in the WP options table. Whenever a plugin is activated, it is added to this array, the array is sorted alphabetically by plugin name, and the array is saved to the DB.
Fortunately, there is a convenient action hook, "activated_plugins", that is called after the active plugins array is saved to the DB. This allows you to manipulate the order of the plugins stored in this array after the array is initially saved.
You'll have to the following PHP code in the plugin who defines the constant, then deactivate and reactivate it (copied from the link I providaded above).
function this_plugin_first() {
// ensure path to this file is via main wp plugin path
$wp_path_to_this_file = preg_replace('/(.*)plugins\/(.*)$/', WP_PLUGIN_DIR."/$2", __FILE__);
$this_plugin = plugin_basename(trim($wp_path_to_this_file));
$active_plugins = get_option('active_plugins');
$this_plugin_key = array_search($this_plugin, $active_plugins);
if ($this_plugin_key) { // if it's 0 it's the first plugin already, no need to continue
array_splice($active_plugins, $this_plugin_key, 1);
array_unshift($active_plugins, $this_plugin);
update_option('active_plugins', $active_plugins);
}
}
add_action("activated_plugin", "this_plugin_first");
Hope it helps!

How to change members per page in BuddyPress members directory

In BuddyPress, it shows 20 members per members directory page. I want to list 24 members per page with a pagination and sorting must work perfectly. I tried:
bp_has_members(bp_ajax_querystring('members').'per_page=24'))
It works but pagination and sorting are not working correctly.
For those like me wondering how to do this nowadays and ending here after searching with their fav engine, the proper way is to use a filter in bp-custom.php or the functions.php of your theme.
Cf. https://codex.buddypress.org/developer/using-bp_parse_args-to-filter-buddypress-template-loops/
For the member loop it would be something like :
function my_bp_members_per_page( $retval ) {
$retval['per_page'] = 24;
return $retval;
}
add_filter( 'bp_after_has_members_parse_args', 'my_bp_members_per_page' );
Bonus : this will still work if you use cache like WP Rocket.
Former method doesn't work with cache and logged in user.
You need an '&' for each additional argument.
Try:
bp_has_members(bp_ajax_querystring('members').'&per_page=24'))
To modify this file, you make a copy of it and put it into your child-theme
/your-child-theme/buddypress/members/members-loop.php

What's "function_exists" in Wordpress

Im very new to WordPress. I was going through Smooth Slider WP Plugin and saw
if ( function_exists( 'get_smooth_slider_category' ) ) { get_smooth_slider_category('Uncategorized'); }
This pretty much gives what I wanted, but not quite. This pulls all the content in the category and what Im after is just the image URL.
My question is whats "function_exists" in wordpress? and I checked get_smooth_slider_category in functions.php file but couldnt find any. Can someone please explain how function_exists works?
function_exists is a PHP function, not limited to WordPress.
From the manual "Checks the list of defined functions, both built-in (internal) and user-defined, for function_name."
It returns true or false on whether or not the function exists. So you can either create a new function before it that does something slightly different, or prevent an error if it doesn't exist (normally because the required file hasn't been included).
This is a PHP function that checks if the passed in name matches any defined functions (either internal, or user defined).
It is a way to check if a function is "available" before calling it.

Wordpress session management

I'm putting up a site using Wordpress and I'd like to piggyback on its sessions. But I'm not finding any plugins, or even documentation. Any suggestions or references before I start hacking it?
Note: I'm asking about if and how WP uses standard PHP sessions itself, not how to add PHP sessions e.g. using session_start(). Apparently any state WP maintains is accomplished by other means. So if I want to use PHP sessions I need to add and maintain it myself entirely, using techniques like those in the thread.
Thanks all!
It's a very bad idea to modify WP Core files for the ability to use sessions. The best way I've found is to call the session_start() from init action hook.
function kana_init_session() {
session_start();
}
add_action('init', 'kana_init_session', 1);
You can place it in functions.php file of your theme.
Detailed article can be found here: http://www.kanasolution.com/2011/01/session-variable-in-wordpress/
WordPress doesn't appear to call session_start() because it wants to be stateless
and if register_globals is defined, it automatically destroys your $_SESSION
Consider using WordPress Transient API
Values stored using the Transient API are visible to all users, not just the current user, depending on the unique identifier used to retrieve the transient, you could assign each user a unique identifier essentially causing a transient to behave very much like a session.
Further considerations:
Depending on a users setup with object cache, etc., transients may
not always be stored in the DB (e.g. memcached), using transients for
sessions could mean that the data can get bulky and fill memory
quickly (in the use of memcached).
Also, it seems that WP does not do auto garbage collection for
transients:
https://wordpress.stackexchange.com/questions/6602/are-transients-garbage-collected
For what I need to do, the best answer involves:
To allow the cookie for wordpress to persist across subdomains, install the Root Cookie plugin.
sub1.domain.com has wordpress; sub2.domain.com is another site. From the other site (sub2), I read the cookies to identify who the user is and if the user is logged in.
My cookies are as follows:
[wordpress_909bb230b32f5f0473202684d863b2e0] => mshaffer|1255298821|d0249fced9c323835c5bf7e84ad3ffea
[wordpress_logged_in_909bb230b32f5f0473202684d863b2e0] => mshaffer|1255298821|56e9c19541ecb596a1fa0995da935700
Using PHP, I can loop over the cookies, parse the key=>value pairs. These cookies let me know that [mshaffer] has a cookie stored on wordpress, and also is authenticated as logged_in. The expiry of the cookie is 1255298821.
In sub2, I can query the database of wordpress and grab the user info:
SELECT * FROM `wp_users` WHERE user_login = 'mshaffer' ... grab user_id, user_email from this query
SELECT * FROM `wp_usermeta` WHERE user_id = '$user_id' ... grab lots of other data from wp
With this info, I can add to my sub2 session variable / cookie and do what I want with the data. I can identify if I am logged in, and my username ... which let's me grab lots of different data. I can now use WordPress authentication in my sub2.domain.com and redirect accordingly.
monte
{x:
Wordpress doesn't seem to use any sessions.
The best way to go about it is to use the action hooks it provides.
Have you checked the solution here this may work for here and its on easy way
http://thedigilife.com/wordpress-how-to-set-session-custom-variable-while-login/
Hooking a function with session_start() on wp_loaded seems to work in this case.
Put this code in wp-config.php at first line:
if (!session_id()) {
session_start();
}
Put this code in theme's header.php at first line:
session_start();
Then it will maintain all session variables.
If you wanna use your own session values, Wordpress does support it.
You need to add following lines at the top of wp-config.php
if (!session_id()) {
session_start();
}
Then add following line at the top of header.php
session_start();

Resources