WordPress delete_option(); Wildcard capability? - php

How would one go about deleting all option names in a WordPress database beginning with a specific prefix?
I would assume we need to specify a prefix, get all options that begin with that prefix, and then delete each option found.
Here is a sample of the prefix and WP functions for getting and deleting options in the database.
<?php
$prefix = 'cpt_';
$getOpt = get_option($prefix);
foreach($getOpt as $toDelete){
$deleteOpt = delete_option($prefix);
if(!$deleteOpt){
echo 'Failure.';
}
if($deleteOpt){
echo 'Success.';
}
}
?>
Resources:
http://codex.wordpress.org/Function_Reference/delete_option
http://codex.wordpress.org/Function_Reference/get_option

You could run this query:
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'cpt_%'" );
or put it in a function like so:
function delete_options_prefixed( $prefix ) {
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '{$prefix}%'" );
}
delete_options_prefixed( 'cpt_' );

You need to make a "whitelist" of all the variables your plugin sets (I assume you are looking at a plugin uninstall script), then just loop through it at the other end so you can delete them all.
Something as simple as:
// Somewhere in your plugin, maybe as a class property
$pluginDefinedOptions = array('my_name', 'my_created', 'my_modified'); // etc
// Clear up our settings
foreach($pluginDefinedOptions as $optionName) {
delete_option($optionName);
}
This is the only way to keep your plugin code tidy.

Related

PHP Custom CMS - How to handle settings

I'm currently trying to find a way to handle settings on my custom CMS (just a playground to learn PHP). I have database table that stores all settings. My temporary solution is a function that returns one dimensional array with query results.
// Get settings from db.
function getPanelOptions( $pdo ) {
$options = [];
$getOptions = $pdo->query( 'SELECT option_name, option_value FROM bp_options' );
while( $result = $getOptions->fetch() ) {
$options[ $result['option_name'] ] = $result['option_value'];
}
return $options;
}
$bpOptions = getPanelOptions( $pdo ); // Get settings to arr.
// Example use
if( $bpOptions['post_max_lenght'] === 400 ) ...
I've read a lot that global variables are not best way to do this, so I call function in file that is included on every page. I don't have problem with using hard coded variable, because I won't change it (even so I can replace all occurrences in sublime). My biggest problem is that I can't find a way to use settings to create a 'wrapper' functions like in WordPress, for example 'getHtmlLang()'. In JS it would be easy, but in PHP I need to pass setting to this function, at it gets to lengthy.
// Now i use
<html lang="<?php echo $bpOptions['panel_lang']; ?>">
// I'd like some wrapper function.
<html <?php getHtmlLang() ?>>
I'm not familiar with OOP in PHP so maybe this is way to achieve this, or should I simply use global because it's justified?

Joomla custom fields inside template

I would like to customize my template for Joomla 3.7 so that I can use the new feature of Joomla 3.7, Custom fields (com_fields), and display and format them via CSS in my template where I need to display them.
Can someone suggest me the PHP code I should use in the template to display field(s), some example please.
Thanks in advance.
For everyone getting late to the party. In case you want to use your custom form fields in a Module-Override (which really are the only way to modify j!-templates, so google 'joomla template override') you can use this handy snippet:
<?php
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jcFields = FieldsHelper::getFields('com_content.article', $item, true);
$itemCustomFields = array();
foreach($jcFields as $field) {
$itemCustomFields[$field->name] = $field->rawvalue;
}
?>
Now you cna use your customfields like so: itemCustomFields['customFieldName1']
Haven't tested in article overrides. May soon, if so, this will get updated.
certainly not the right way to do it but I had the same need and I found a work around based on https://www.giudansky.com/news/12-coding/146-joomla-custom-fields
Copie default.php from /components/com_content/views/article/tmpl/default.php to
templates/YOUR_THEME/html/com_content/article/default.php
Add following code line 25 :
$myCustomFields = array();
foreach($this->item->jcfields as $field) {
$myCustomFields[$field->name] = $field->value;
}
$GLOBALS['myCustomFields'] = $myCustomFields;
Typically you put on a global var the content of fields attached to your article.
On your template page you can know retrieved value of your field.
just print_r($GLOBALS['myCustomFields']); to view the content of your array.
That will do the trick waiting for a better answer..
This is absolutely the wrong way to do this I think but I was tearing my hair out so i came up with this quick db query to return custom field values in the template. surely this violates some kind of joomla protocol?
obviously this assumes you can get $articleid into your template already which is the Current ID of your article.
I too am waiting on a better solution but hope this helps
$db =& JFactory::getDBO();
$sql = "select * from #__fields_values where `item_id` = $articleid";
$db->setQuery($sql);
$fieldslist = $db->loadObjectList();
echo $fieldslist[0]->value;
echo $fieldslist[1]->value;
echo $fieldslist[your field ID here]->value;
I found it was easiest to follow how com_fields does it in its rendering code. In Joomla!3.7+, you'll find it in [joomla_root]/components/com_fields/layouts/fields/render.php .
Here are the main parts you need to reproduce the formatting that Joomla has:
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
<dl class="fields-container">
<?php foreach ($this->item->jcfields as $field) : ?>
<?php // If the value is empty do nothing ?>
<?php if (!isset($field->value) || $field->value == '') : ?>
<?php continue; ?>
<?php endif; ?>
<?php $class = $field->params->get('render_class'); ?>
<dd class="field-entry <?php echo $class; ?>">
<?php echo FieldsHelper::render($context, 'field.render', array('field' => $field)); ?>
</dd>
<?php endforeach; ?>
</dl>
This loops through all available tags for the component or article. The nice thing about this method is it still applies the render classes you include with the fields.
Make sure to set Automatic Display to Do not automatically display on your fields; otherwise you will see them twice on your page view.
If you want to just target specific fields to show, you can use the name of the field to target it. (The label and value pair is underneath.) See the field Joomla docs for more info.
I implemented this small function to get specific custom field values:
function getCustomFieldValue($field_name, $article_id, $default_value = '') {
// Load custom field list
$fields = FieldsHelper::getFields('com_content.article', $article_id, true);
$field_ids = array_column($fields, 'id', 'name');
$model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true));
// Return the value if the field exists, otherwise the default
return array_key_exists($field_name, $field_ids)
? $model->getFieldValue($field_ids[$field_name] , $article_id)
: $default_value;
}
Usage:
$some_field_value = getCustomFieldValue('some-field-name', $some_article_id);
Optimization: I placed the function into a helper class, implemented the variables $fields, $field_ids and $model static and checked if they are already loaded to prevent redundant loading of the same data.

Wordpress - make variables available for all theme files (without Globals)

I'm developing a Wordpress theme and I'm trying to store some of my variables in a function to re-use it among my theme files, without writing the same variables hundreds of time and without make them global. I've read that's a bad practice.
For now I'm using add_action but without results. Having in my functions.php
add_action( 'run_pms_variables', 'pms_variables_function' );
function pms_variables_function ($uid ) {
$the_group_uid = isset($_COOKIE["v_group_id"]) && !empty($_COOKIE["v_group_id"]) ? trim(strip_tags($_COOKIE["v_group_id"])) : "";
$session_detail = vpb_get_the_user_detail($uid);
$session_username = strlen($session_detail[0]) > 40 ? ucfirst(substr($session_detail[0],0,40)) : ucfirst($session_detail[0]);
$session_uid = $session_detail[1];
$session_email = $session_detail[2];
$session_photo = $session_detail[3];
$session_country = $session_detail[4];
//$session_usernames = explode(' ', $session_detail[0]);
$session_firstname = get_user_meta($uid,'first_name', true );
$session_lastname = get_user_meta($uid,'last_name', true );
}
and using eventually in my files like:
do_action('run_pms_variables', $uid );
I mean, can you address me to the right method? Thanks.
Write a class, declare a global object of that class, save all your variables as attribute/property of that class.
Now from anywhere just get the global object.
You have all variables stored inside that.
Uuuuhmm you are mixing apples with peaches. The WordPress Hooks, Actions and Filters are ment to modify the WordPress core the way you want, it is not build to store any data somewhere in your template.
One way to do it would be to simply store the values in the database of your WordPress installation. To do that you need to get familiar with the "Nonce" function, which is security mechanism for storing stuff in the database of WP.
There are hundrets and thousands of tutorials out there which show how to do it.
If you want only to store some numeric values or short strings, you could use the HTML data-* object to store some data, when php spits it back.
add_action( 'run_pms_variables', 'pms_variables_function' );
function pms_variables_function ($uid ) {
class GlobalVariables{
function __construct ($uid){
$this->the_group_uid = isset($_COOKIE["v_group_id"]) && !empty($_COOKIE["v_group_id"]) ? trim(strip_tags($_COOKIE["v_group_id"])) : "";
$this->session_detail = vpb_get_the_user_detail($uid);
$this->session_username = strlen($session_detail[0]) > 40 ? ucfirst(substr($session_detail[0],0,40)) : ucfirst($session_detail[0]);
$this->session_uid = $session_detail[1];
$this->session_email = $session_detail[2];
$this->session_photo = $session_detail[3];
$this->session_country = $session_detail[4];
//$session_usernames = explode(' ', $session_detail[0]);
$this->session_firstname = get_user_meta($uid,'first_name', true );
$this->session_lastname = get_user_meta($uid,'last_name', true );
}
}
return GlobalVariables($uid);
}
//and to access:
$global_variables = do_action('run_pms_variables', $uid );
echo $global_variables->the_group_uid;
As a side note, be definition global variables are variables that can be accessed anywhere, other options include setting variables in the $_SESSION super global (as most of you're variables look session specific) inside the pms_variables_function instead of setting class attributes.

Wordpress PHP - How to update plugin setting value in main file

This is from inside my Wordpress plugin, inside the main file:
function my_plugin_install() {
$my_site_url = get_site_url();
$my_options['my_site_url'] = $my_site_url;
// Save
}
register_activation_hook(__FILE__, 'my_plugin_install');
Currently, the install is successful but the 'my_site_url' option is not saved. I'm assuming because the way I'm using the $my_options array at this point doesn't mean anything. It should save this data to the wp_options table.
I can't seem to get this to save, or even find a way to test this as using "echo" gives Wordpress an error during install. Is there a best method for running a script and updating the database during install?
Thanks in advance.
You need to use the WordPress function update_option to save your option value:
function my_plugin_install() {
$my_site_url = get_site_url();
update_option('my_site_url', $my_site_url);
}
register_activation_hook(__FILE__, 'my_plugin_install');
And then later, when you need that value, you can use get_option:
$my_site_url = get_option('my_site_url');
*UPDATE
Since it appears you want to manage multiple of your own options, then I suggest using a simple "utility" function, like so:
function update_my_option($key, $value) {
// Load all of the option values from wp_options
$all_options = get_option('my_options');
// Update just the one option you passed in
$all_options[$key] = $value;
// Save to wp_options
update_option('my_options');
}
And, an appropriate getter function:
function get_my_option($key, $default = NULL) {
// Load all of your options from wp_options
$all_options = get_option('my_options');
// Return just the one option you are asking for
return (isset($all_options[$key])) ? $all_options[$key] : $default;
}
Then, rather than calling update_option directly, you'll call this function, as illustrated below:
function my_plugin_install() {
$my_site_url = get_site_url();
update_my_option('my_site_url', $my_site_url);
}
And, to get one of your options:
$my_site_url = get_my_option('my_site_url');

WP Custom plugin: Create table and insert data once.

This is my complete Wordpress plugin file:
<?php
function wp_create_table_install()
{
global $wpdb;
$table_name = $wpdb->prefix.'createtable';
$sql = 'CREATE TABLE '.$table_name.'(
id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(75)
);';
require_once(ABSPATH.'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
function wp_create_table_insert_data()
{
global $wpdb;
$table_name = $wpdb->prefix.'createtable';
$id = 1;
$name = 'WP Create Table!';
$wpdb->insert($table_name, array('id' => $id, 'name' => $name));
}
register_activation_hook(__FILE__, 'wp_create_table_install');
register_activation_hook(__FILE__, 'wp_create_table_insert_data');
?>
When I activate the plugin, it always tries to create a table and insert data. How could I do it once, just in the first plugin activation?
Thank you.
A quicker way would be to add [IF NOT EXISTS] in your CREATE statement so that you don't get an error if your table already exists.
Before running CREATE TABLE, you could query information_schema.tables to check to see whether or not the table already exists.
Unfortunately, there's no way to run something on "install" - surprisingly, WordPress doesn't provide any hooks for install as opposed to activation!
The way people cope with this is to set and test an option - if the option is not set, then create the tables, and if it is set do nothing or do a DB upgrade. Options are read in and cached so there is no performance penalty to doing this.
$opt = get_option(MYPLUGIN_OPTIONS);
$opt['dbversion'] = 100;
...
update_option(MYPLUGIN_OPTIONS, $opt);

Categories