update plugin via code - php

is it somehow possible to update a wordpress-plugin via another plugin with php code?
i tried something like this
$request = wp_remote_post(
'http://wordpress2/wp-admin/admin-ajax.php',
array(
'body' => array(
'plugin' => 'hello-dolly/hello.php',
'slug' => 'hello-dolly',
'action' => 'update-plugin',
'_ajax_nonce' => wp_create_nonce( 'nonce-test' ),
)
));
but this only leads in a 400 status...
I thought this kind of stuff would be easy in wordpress, dumb me! :-D

Found a solution:
after all plugins are loaded add a filter which define to auto-update plugins
add_action( 'plugins_loaded', array( CLASS, 'abpr_plugins_loaded' ), 1 );
public static function abpr_plugins_loaded(){
add_filter( 'auto_update_plugin', '__return_true');
}
the define some function which will be triggered from something, in my case it is an custom api-url which calls this:
public static function update_all_defined_plugins($data){
set_site_transient( 'update_plugins', '' );
wp_maybe_auto_update(); }
keep in mind that this is some bare stuff here without any code- & results-checking

Related

CodeIgniter 3 / Basic Hook Loading Problems

Hey I'm sure I miss something obvious, but can't figure out what it is :
I can't get a simple hook working with my quasi blank installation of CI 3 ...
I've put the simplest of the code possible with a Hook called MyTest and it works fine :
application/config/hooks.php
$hook['post_controller_constructor'][] = array(
'class' => 'MyTest',
'function' => 'TestMe',
'filename' => 'MyTest.php',
'filepath' => 'hooks',
'params' => ''
);
application/hooks/MyTest.php
class MyTest{
function TestMe()
{
die("die by the hook TEST");
}
}
->this outputs "die by the hook TEST", which is what is expected.
But almost the same with a Hook called URI_Actions doesn't work at all :
application/config/hooks.php
$hook['post_controller_constructor'][] = array(
'class' => 'URI_Actions',
'function' => 'index',
'filename' => 'URI_Actions.php',
'filepath' => 'hooks',
'params' => ''
);
application/hooks/URI_Actions.php
class URI_Actions{
function index()
{
die("die by the hook URI Actions");
}
}
-> this doesn't output anything ... I'm sure I'm missing something enormous, any idea ?
Epilogue
Of course the problem was elsewhere : binary FTP transfert was the issue, once the files uploaded normally the same codes worked perfectly. Thanks to trajchevska which made me realize the code was not the problem !
Does it not display anything or it displays "die by the hook TEST" only? The thing is that you have them both defined one after the other and they're both doing dump and die. So when the Test hook displays the result, the program dies and doesn't get to the URI_Actions hook.
Try using a simple var_dump instead of die, you should get the expected result. I tested both locally and they work fine.

Get current user id in a WP plugin with redux framework

I'am working on a sorter plugin for WordPress, which have Redux Framework installed to manage the options of every section. The plugin uses AJAX to get the ids of all the sections in the homepage of the website, then passes those values to the plugin main file to process in a function that stores the values in the current user meta. That works well, no problem here. The function looks like this:
add_action( 'wp_ajax_save_sections_ids', 'save_sections_ids_sorting_sections' );
function save_sections_ids_sorting_sections() {
//stuff here...
$user_ide = get_current_user_id(); //it works because it is inside a hook
update_user_meta($user_ide, "set-sections", $sections_ids);
die();
}
Then I have to get the stored values in user_meta to pass them to the Redux Field, so I wrote other function in the main file of the plugin. The function is this:
function get_the_db_sections_ids() {
$user_ide = 1; //This should be get_current_user_id() or something similar, but nothing works, not even globalizing $current_user and using get_currentuserinfo();
$sections_ids = get_user_meta($user_ide, "set-sections", true);
$sorter_field = array(
"section_id" => "basic",
'id' => 'homepage-sections',
'type' => 'sorter',
'title' => 'Control de secciones',
'desc' => 'Arrastra y suelta los bloques con los nombres de las secciones, tanto para ordenarlas verticalmente como para desactivarlas o activarlas.',
'compiler' => 'true',
'options' => array(
'enabled' => array(
),
'disabled' => $sections_ids
),
);
return $sorter_field;
}
As you notice in the comment in the function above, I have tried several ways, also require_once("/../../../wp-load.php"), but nothing happens. I tried do_action and add_actions, to create a hook, but those also use global variables, and for what I understand, the global variables do not work in functions with no hooks in plugins.
But I havent finished yet. The really tricky part is, I am calling an instance of Redux class inside the Redux config file (sample-config.php for the demo, I have a custom file, but it is the same).
The instance is Redux::setField($opt_name, get_the_db_sections_ids());
The problem this does not print anything if I call it from a function, or the function linked to the AJAX call.
As you can see, the second parameter of the instance is the function I wrote above that, and it works perfectly if I set $user_ide to 1, but I want the data stores in all admins user_meta, in case user 1 is erased, or whatever.
Is there a way to achieve what I want, or to store the data somewhere else and get it from there. I was thinking in creating a custom table in db, and use wpdb to retrieve the data, but I think I can't use wpdb either, because it will be the same problem.
I get the feeling I'm missing something very basic, but I can't get it. Please help.
This should help you out
global $current_user;
get_currentuserinfo();
$user_ide = $current_user->ID;
You'll have to declare a global variable $current_user, in order to use it.
Finally I found the solution to my problem. As I said, I couldn't get the current user id from the pligin if I tried outside an action hook or a filter hook, setting sessions and global variables didn't work, and functions hooked with WP normal hooks wouldn't set the Redux field. I reviewed the sample-config.php file inside the ReduxFramework/sample folder, and I found out some functions and hooks. One of them to set the entire section, but inside that section, you can set the field and it worked.
I eresed the Redux::setField instance, and did this in the sorter plugin main file:
add_filter('redux/options/' . $opt_name . '/sections', 'dynamic_section');
if ( ! function_exists( 'dynamic_section' ) ) {
function dynamic_section( $sections ) {
global $current_user;
get_currentuserinfo();
$sections[] = array(
'title' => __( 'Section via hook', 'redux-framework-demo' ),
'desc' => __( '<p class="description">This is a section created by adding a filter to the sections array. Can be used by child themes to add/remove sections from the options.</p>', 'redux-framework-demo' ),
'icon' => 'el el-paper-clip',
'fields' => array(get_the_db_sections_ids($current_user->ID))
);
return $sections;
}
} //I copied it from sample-config.php and added what's inside `"fields" =>` and the global.
Then I modified my array function like this:
function get_the_db_sections_ids($user_ide) { //Added the parameter
//Erase $user_ide = 1;
$sections_ids = get_user_meta($user_ide, "set-sections", true);
$sorter_field = array(
"section_id" => "basic",
'id' => 'homepage-sections',
'type' => 'sorter',
'title' => 'Control de secciones',
'desc' => 'Arrastra y suelta los bloques con los nombres de las secciones, tanto para ordenarlas verticalmente como para desactivarlas o activarlas.',
'compiler' => 'true',
'options' => array(
'enabled' => array(
),
'disabled' => $sections_ids
),
);
return $sorter_field;
}
And that's it, I hope this will help somebody. Redux is great but their documentation is very far from good, so, here's one little contribution for those using the framework. And thanks to the users who tried to help me.

Drupal : Create variable from custom .module to custom .tpl.php

I create a custom module and I want use the complete_url of my future website in the template who used/created by my module.
I tried several ways and searched Google but I don't find a solution.
However this issue seems very simply, that became me crazy x)
So, I must create a variable in my .module and add her when I return the array in the main_socialtag_theme function. Where/How can I do that ?
My .module:
function main_socialtag_block_info(){
$block['main_socialtag']=array(
'info' => t('Main socialtag'),
'cache' => DRUPAL_NO_CACHE,
);
return $block;
}
function main_socialtag_theme(){
return array(
'main_socialtag_block' => array(
'template' => 'theme/main_socialtag_block',
'variables' => array(),
),
);
}
function main_socialtag_block_view($delta=''){
if ($delta == 'main_socialtag'){
return array(
'subject' => '',
'content' => array(
'#theme' => 'main_socialtag_block',
)
);
}
}
Thanks for help, and sorry for my bad english writing !
If you are looking for a way to add, modify and call variables. Check variable_get and variable_set.
To add or modify a variable value:
variable_set("my_variable_name", "value");
To retrieve the value:
$myVal = variable_get("my_variable_name", "");
For hook_theme Implementation, kindly check this question.

Dynamic function name in php

I would like to simplify the creation of "Custom Post Types" in WordPress as it is tedious to go through the same script and change all the custom post type name instances manually over and over.
It's quite simple to achieve by creating a variable containing the CPT name and use it everywhere it is needed. This way, All I have to do is declare the variable in the beginning of the script and that should take care of the rest.
The only issue is that, to make it work, I also need to prefix the CPT name in front of every function inside the script and it seems that using a variable in a function name is not easy or even recommended in PHP.
So how could I solve this?
Here is an example below to make it clear:
$prefix = 'news';
function news_custom_type_init()
{
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
add_action('init', $prefix.'_custom_type_init');
This is almost fine and could be standardized if only I could dynamically rename the function in order not to have to write the word "news" in front of it but use the "$prefix" instead.
This could have been nice but just doesn't work:
$prefix = 'news';
$functionName= $prefix."_custom_type_init";
function $functionName()
{
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
add_action('init', $prefix.'_custom_type_init');
Having to name manually the function kinda defeat the original purpose of my attempt (especially when the script embeds dozens of functions like this one).
What would be the best way to do this?
PS: I googled and "stackoverflowed" a lot about this but didn't find any working solution that fit my needs and doesn't generate a WordPress error message.
Thank you.
Simple enough, here's a similar snipped form a project:
$function = $prefix . '_custom_type_init';
if(function_exists($function)) {
$function();
}
This is an old thread but simply use anonymous functions:
add_action('init', function() use($args) {
//...
});
Then there is no need to declare so many functions.
Edit (2017-04): Anonymous functions (properly implemented) are the way to go, see answer by David Vielhuber.
This answer is ill advised, as is any approach that involves code as a string, because this invites (among other things) concatenation.
Im not sure if it is advisable to use, or if it helps you, but php allows you to create "anonymous" functions :
function generateFunction ($prefix) {
$funcname = create_function(
'/* comma separated args here */',
'/* insert code as string here, using $prefix as you please */'
);
return $funcname;
}
$func= generateFunction ("news_custom_type_init");
$func(); // runs generated function
I am assuming add_action just calls whatever function you passed.
http://php.net/manual/en/function.create-function.php
Note: create_function will not return a function with the name you want, but the contents of the function will be under your control, and the real name of the function is not important.
I think you could use
runkit_function_add
http://php.net/manual/pl/function.runkit-function-add.php
One other available method is to use eval()
This post is old, but PHP 7 may solve this question.
Try:
$prefix = 'news';
$functionName = $prefix . "_custom_type_init";
${$functionName} = function() use ($prefix) {
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add'
)
);
register_taxonomy_for_object_type( 'category', $prefix );
};
add_action('init', '$' . $functionName);
I think it should work for WordPress.
You can use string in brackets
("function_name_{$dynamic_var}")()
I'm not sure any of the above actually answer the question about dynamically creating custom post types. This works for me though:
$languages = ("English", "Spanish", "French");
foreach($languages as $language):
$example = function () use ($language) {
$labels = array(
'name' => __( $language . ' Posts' ),
'singular_name' => __( $language . ' Post' )
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
"rewrite" => array( "slug" => $language . "_posts", "with_front" => true ),
'capability_type' => 'page',
);
register_post_type( $language . "_posts", $args );
};
add_action( 'init', $example, 0 );
endforeach;
Dynamic function named in PHP as variable functions
https://www.php.net/manual/en/functions.variable-functions.php
as example
$functionName = function () {
global $prefix;
register_post_type($prefix, array(
'labels' => array(
'name' => $prefix,
'singular_label' => $prefix,
'add_new' => 'Add',
...
));
register_taxonomy_for_object_type( 'category', $prefix );
}
you can call it by typing $functionName()
I was also looking for a way to do this, as I wanted to create a function that could make aliases for functions, just like in ruby. e.g.
function an_insanely_long_function_name($a, $b) {
// do something with $a and $b
}
// I'll go insane if I have to type that stupidly long function name every time 😵
// Aliases to the rescue :)
define_alias('shrt_nm', 'an_insanely_long_function_name');
shrt_nm('a', 'b');
I did quite a lot of research — for like 2 mins :p — and found nothing that could help me achieve that functionality.
I was about to give up and do it all manually, but then I remembered good old "eval", my long time buddy :).
Here's what you need to do:
function define_alias($alias, $function) {
if (function_exists($alias))
throw new \Exception('A function named ' . $alias . ' already exists!');
// create the function
eval("function $alias(...\$args) { $function(...\$args); }")
}
eval() is the simpliest method
https://www.php.net/manual/en/function.eval.php
$name='new_func';
$var = eval($name."();");
function new_func(){echo "It work";}

How to use tinymce plugin in other plugins in Croogo 1.3?

In
tinymce_bootstrap.php
I tried:
'gallery/photos/admin_edit_photo' => array(
array(
'elements' => 'PhotoDescription',
),
),
Gallery is my plugin
but it doesn't work. Any idea how to make it work?
I have done it the easy-way:
var $helpers = array('Tinymce.Tinymce');
in my plugins's
controller
but there must be a better solution
Assuming you have a PhotosController (either in a plugin or main app) with admin_edit_photo() action, and your Photo model has a 'description' field, add this to the bootstrap:
'Photos/admin_edit_photo' => array(
array(
'elements' => 'PhotoDescription',
),
),
See the Tinymce plugin's bootstrap for reference: https://github.com/croogo/croogo/blob/1.3/plugins/tinymce/config/tinymce_bootstrap.php

Categories