remove_admin_bar ();
* -> disable_emojis ();
* -> delete_transients_by_prefix ('something');
* -> unzip ('file.zip');
* ...
*
* Note: This file also contains additional 'wp_plugin' class. example use: https://bit.ly/puvox_wp_plugin
*/
namespace Puvox;
if (!class_exists('\\Puvox\\library_wp')) {
#[\AllowDynamicProperties]
class library_wp extends library
{
public function __construct()
{
parent::__construct();
}
public $logs_table_maxnum=100;
public $logs_table_name ='_default_table_ERRORS_LOGS';
public function init_module($args=[])
{
parent::init_module($args);
//get blog-slug
if(is_multisite()){
global $blog_id; if(empty($blog_id)) $blog_id = get_current_blog_id();
$current_blog_details = function_exists('get_sites') ? get_site($blog_id) : get_blog_details( array( 'blog_id' => $blog_id ) );
$b_slug = basename($current_blog_details->path);
}
$this->BLOGSLUG = (!empty($b_slug)? $b_slug : basename($this->homeFOLDER) );
// others
$this->this_file_link= '';//$this->baseURL . $this->urlify( explode( basename($this->baseURL), __FILE__ )[1] );
$this->PHP_customCALL= '';//$this->this_file_link .'?custom_php_load=scripts_load&actionn=';
if ($this->is_development)
{
$this->js_debugmode("debugmode");
}
}
public function is_home_path($path){
return trailingslashit($path)==trailingslashit(str_replace( trailingslashit(network_site_url()), '', trailingslashit(home_url())) );
} //return in_array(home_url(), ["http://$site","https://$site"]) || home_url('', 'relative')==$site; }
public function home_url(){ return trailingslashit(home_url());}
public function blog_slug(){
$blogname = str_replace(basename(get_site_url()),'', basename( get_site($GLOBALS['blog_id'])->path));
return ($blogname !=='' ? $blogname : str_replace('www','',$_SERVER['HTTP_HOST']));
}
public function load_scripts_styles()
{
//load desired scripts
add_action( 'wp_enqueue_scripts', [$this, 'my_styles_hook'], 9);
add_action( 'admin_enqueue_scripts', [$this, 'my_styles_hook'], 9);
}
public function init_properties()
{
}
//when is_admin or when page is unknown (for example, custom page or "wp-login.php" or etc... )
public function is_backend(){
$includes=get_included_files();
$path = str_replace( ['\\','/'], DIRECTORY_SEPARATOR, ABSPATH);
return (is_admin() || in_array($path.'wp-login.php', $includes) || in_array($path.'wp-register.php', $includes) );
//return (!!array_intersect([$ABSPATH_MY.'wp-login.php',$ABSPATH_MY.'wp-register.php'] , get_included_files())) ;
}
public function is_gutenberg($active=true){
return ( function_exists( 'is_gutenberg_page' ) && (!$active || $this->is_gutenberg_page() ) );
}
public function is_gutenberg_page($active=true){
if (is_admin()) {
global $current_screen;
if (!isset($current_screen)) {$current_screen = get_current_screen();}
if ( method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor() || $this->is_gutenberg(true) ) {
return true;
}
}
return false;
}
//Get Blog slug, i.e. "subdir" from "http://example.com/subdir/"
public function get_blog_name(){
if(is_multisite())
{
global $blog_id;
$current_blog_details = !function_exists('get_blog_details') ? get_site($blog_id) : get_blog_details( ['blog_id' => $blog_id] );
$b_slug = basename($current_blog_details->path);
return $b_slug;
// global $current_blog;
// $blog_path = explode('/',$current_blog->path);
// if(isset($blog_path[2])) {
// return $blog_path[2];
// }
//if(!get_blog_name()) { header("Location: http://www.mydomain.com/", true, 301); exit; }
}
return false;
}
public function get_locale_sanitized(){
return ( get_locale() ? "en" : preg_replace('/_(.*)/','',get_locale()) ); //i.e. 'en'
//$x=$GLOBALS['wpdb']->get_var("SELECT lng FROM ".$this->options." WHERE `lang` = '".$lang."'"); return !empty($x);
}
public function blog_prefix()
{
$blog_prefix = '';
if ( is_multisite() && ! is_subdomain_install() && is_main_site() && 0 === strpos( get_option( 'permalink_structure' ), '/blog/' ) ) {
$blog_prefix = '/blog';
}
$this->blog_prefix = $blog_prefix;
return $blog_prefix;
}
public function path_after_blog()
{
$prf = $this->blog_prefix();
$path = $this->pathAfterHome;
return ( ($prf=="/blog") ? str_replace('/blog/', '', '/'.$path) : $path );
}
public function disable_metabox_folding()
{
add_action('admin_footer', function ()
{ ?>file_put_contents($file, ''."\r\n".
'Order allow,deny'."\r\n".
'Deny from all'."\r\n".
''
);
}
});
}
public function my_site_variables__secret($var_name=false, $value=false){
$final= $this->SITE_VARIABLES = get_site_option('site_variables_my_secret',[]);
if ($var_name) {
if(array_key_exists($var_name, $this->SITE_VARIABLES)){
$final = $this->SITE_VARIABLES[$var_name];
}
elseif($value) {
$final = $this->SITE_VARIABLES[$var_name]=$value;
update_site_option('site_variables_my_secret', $this->SITE_VARIABLES);
}
else{
$final = '';
}
return $final;
}
else{ return $this->SITE_VARIABLES; }
}
public function dashicon_styled($name, $style){
return '//" class="dashicons-before '.$name.'" style="opacity:0.91; '.$style;
}
// ====================== tinymce buttons ==================== //
// $this->my_default_buttons= array('superscript', 'subscript') + array( "|", "youtube_video","audioo", "add_spacee_button", "removeline_button", "abzac_button","videomovie", "lists", "script");
public function tinymce_funcs()
{
// Add button in TinyMCE
add_action( 'admin_init', function(){
if ( get_user_option('rich_editing') == 'true') {
add_filter( 'mce_external_plugins', function ( $plugin_array ) { return array_merge($plugin_array, ["button_handle_" . $this->slug=> $this->homeURL . '?tinymce_buttons_'.$this->slug] ); } );
add_filter( 'mce_buttons_2', function ( $button_names ) { return array_merge( $button_names, array_map( function($ar){ return $ar['button_name']; }, $this->tinymce_buttons )); } );
//this is must for REFRESHING!
add_filter( 'tiny_mce_version', function ( $ver ) { $ver += 3; return $ver;} );
}
} );
//tinymce buttons if needed
$this->tinymce_buttons_body();
foreach($this->tinymce_buttons as $each_button){
if( !empty($each_button["shortcode"]) ){
add_shortcode($each_button["shortcode"], [$this, $each_button["shortcode"]] );
}
}
}
public function compress_php_header($isWP=false)
{
ob_start('ob_gzhandler'); //similar as: ini_set('zlib.output_compression', '1');
if ($isWP){
add_action('wp', (function (){ if (!is_admin()) ob_start('ob_gzhandler'); } ) ,1);
remove_action( 'shutdown', 'wp_ob_end_flush_all', 1 );
}
}
//add_action( 'pre_get_posts', 'querymodify_2322',77);
// public function querymodify_2322($query) { $q=$query;
// if( $q->is_main_query() && !is_admin() ) {
// if($q->is_home){
// $q->init();
// $q->set('post_type',LNG);
// $q->set('category__not_in', 64);
// $q->set_query_vars('category__not_in',array(64) );
// }
// }
// return $q;
// }
public function referrer_is_external_domain()
{
return $this->get_domain(wp_get_referer()) !== $this->get_domain(home_url());
}
public function inprogress_flag_cache($flagname, $max_seconds=999999999){
$flagname_final = "inprogress_$flagname";
$start_time = $this->cache_get($flagname_final,null);
if($start_time && time()<$start_time+$max_seconds) {
return true;
}
else{
$this->cache_set($flagname_final, time(), $max_seconds);
register_shutdown_function(function() use($flagname_final){ $this->cache_set($flagname_final,null); });
return false;
}
}
public function inprogress_flag($flagname, $max_seconds=60){
$flagname_final = "inprogress_$flagname";
$start_time = $this->get_transient($flagname_final,null);
if($start_time && time()<$start_time+$max_seconds) {
return true;
}
else{
$this->set_transient($flagname_final, time(), $max_seconds);
register_shutdown_function(function() use($flagname_final){ $this->inprogress_flag_reset($flagname_final); });
return false;
}
}
public function inprogress_flag_reset($flagname_final){
$flagname_final = !$this->starts_with($flagname_final, 'inprogress_') ? "inprogress_$flagname_final" : $flagname_final;
if( !empty($this->get_transient($flagname_final) ) ) {
if( ! $this->set_transient($flagname_final,0,0) ) {
if( ! $this->set_transient($flagname_final,0,0) ) {
throw new \Exception("Cant update status: $flagname_final | ". $GLOBALS['wpdb']->last_error);
}
}
}
}
public function register_stylescript($admin_or_wp, $type, $handle=false, $url=false, $dependant=null, $version=false, $target=false)
{
add_action( $admin_or_wp.'_enqueue_scripts', function() use($type, $handle, $url, $dependant, $version, $target) {
$this->enqueue($type, $handle, $url, $dependant, $version, $target);
}, 100);
}
public function enqueue($type, $handle=false, $url=false, $dependant=null, $version=false, $target=false)
{
//lets allow shorthanded start
$localstart = 'assets';
if( substr($url,0, strlen($localstart) ) == $localstart ) {
$url = $this->moduleURL. $url;
}
if ( ! call_user_func("wp_".$type."_is", $handle, "registered" ) ){
call_user_func("wp_register_".$type, $handle, $url, $dependant, $version, $target ); //,'jquery-migrate'
}
if ( ! call_user_func("wp_".$type."_is", $handle, "enqueued" ) ){
call_user_func("wp_enqueue_".$type, $handle);
}
}
//if used earlier than INIT
public function get_permalink_before_init($post=false){
global $wp_rewrite;
if (empty($wp_rewrite)){
if(is_object($post)) {$link=$post->guid; }
elseif(is_numeric($post)){ $post_obj=get_post($post, OBJECT); $link=get_permalink($post_obj->ID); }
}
else{
if(is_object($post)) { $link=get_permalink($post->ID);}
else { $link=get_permalink($post); }
}
return $link;
}
public function get_parent_slugs_path($post){
$final_SLUGG = '';
if (!empty($post->post_parent)){
$parent_post= get_post($post->post_parent);
while(!empty($parent_post)){
$final_SLUGG = $parent_post->post_name .'/'.$final_SLUGG;
if (!empty($parent_post->post_parent) ) { $parent_post = get_post( $parent_post->post_parent); } else{ break ;}
}
}
return $final_SLUGG;
}
// https://stackoverflow.com/questions/18401236/custom-category-tree-in-wordpress
//foreach (get_terms($allTermSlugs, array('hide_empty'=>0, 'orderby'=>'id', 'parent'=>0) ) as $category) echo my_Categ_tree($category->taxonomy,$category->term_id);
public function my_categ_tree($TermName='', $termID=null, $separator='', $parent_shown=true ){
$args = 'hierarchical=1&taxonomy='.$TermName.'&hide_empty=0&orderby=id&parent=';
if ($parent_shown) {$term=get_term($termID , $TermName); $output=$separator.$term->name.'('.$term->term_id.')
'; $parent_shown=false;}
$separator .= '-';
$terms = get_terms($TermName, $args . $termID);
if(count($terms)>0){
foreach ($terms as $term) {
//$selected = ($cat->term_id=="22") ? " selected": "";
//$output .= '';
$output .= $separator.$term->name.'('.$term->term_id.')
';
$output .= my_Categ_tree($TermName, $term->term_id, $separator, $parent_shown);
}
}
return $output;
}
public function recount_categories($tax_name='category')
{
$terms_ids = get_terms( ['taxonomy' => $tax_name, 'fields' => 'ids','hide_empty' => false]);
wp_update_term_count_now( $terms_ids, $tax_name);
}
public function random_val_for_site($name){
$randoms = get_site_option('randoms_for_main_site', array());
if(empty($randoms) || empty($randoms[$name])){
$randoms[$name]= random_stringg(16);
update_site_option('randoms_for_main_site', $randoms);
}
return $randoms[$name];
}
// https://pastebin_com/sPb1qvJ0
public function delete_transients_by_prefix($myPrefix, $table_name, $column_name, $prefix=false){
global $wpdb;
$myPrefix = sanitize_key($myPrefix);
$sql = $wpdb->prepare("delete from %s where %s like '%s' or %s like '%s'", $table_name, $column_name, '%_transient_$myPrefix%', $column_name, "%_transient_timeout_$myPrefix%" );
return $wpdb->query($sql);
}
// NONCES
public function default_nonce_action($actionName=null){ return ($actionName!=null? $actionName : "_nonceAction"."_".$this->slug); }
public function default_nonce_slug($slugName=null){ return ($slugName!=null? $slugName : "_wpnonce"."_".$this->slug); }
public function check_form_submission($action=null, $slug=null)
{
$action = $this->default_nonce_action($action);
$slug = $this->default_nonce_slug($slug);
$result = isset($_POST[$slug]) && check_admin_referer($action, $slug);
return $result;
}
public function checkSubmission($action=null, $slug=null){
return $this->check_form_submission($action, $slug);
}
public function nonce($action=null, $slug=null, $echo=true)
{
$out = wp_nonce_field( $this->default_nonce_action($action), $this->default_nonce_slug($slug), true, false );
if ($echo) echo $out; else return $out;
}
public function nonceSubmit($text=null, $action=null, $slug=null, $centeredFloat=false, $echo=true)
{
$btn = $this->submit_button($text, $action, $slug, $centeredFloat);
if ($echo) echo $btn; else return $btn;
}
public function submit_button($text=null, $action=null, $slug=null, $centeredFloat=false, $echo=false)
{
$out = '';
$out .= $this->nonce( $this->default_nonce_action($action), $this->default_nonce_slug($slug), false );
if ($centeredFloat) $out .= '
';
$out .= get_submit_button( $text, $type='button-primary', $name='', $wrap=true, $other_attributes= ['id'=>'mainsubmit-button'] );
if ($centeredFloat) $out .= '
';
if ($echo) echo $out; else return $out;
}
// old
public function nonce_check($value, $action_name){
if ( !isset($value) || !wp_verify_nonce($value, $action_name) ) { die("not allowed. error_5151, Refresh the page");}
}
public function nonce_check2($name='nonce_input_name', $action_name='blabla') {
return ( wp_verify_nonce($_POST[$name], $action_name) ? true : die("not allowed, refresh page!") );
}
public function nonce_field($name='nonce_input_name', $action_name='blabla') { return '';}
// backend
private function default_nonce_action_key($actName){ return 'puvox_backend_call_'.$this->slug. "_".sanitize_key($actName); }
public function add_action_backend_call($actName, $callback){
add_action( $this->default_nonce_action_key($actName), $callback );
}
public function register_backend_call_actions(){
add_action( 'wp_ajax_'.$this->plugin_slug_u.'_all', [$this, 'ajax_backend_call'] );
add_action( 'wp_ajax_nopriv_'.$this->plugin_slug_u.'_all', [$this, 'ajax_backend_call_nopriv'] );
}
public function ajax_backend_call()
{
if(isset($_POST['action']) && $_POST['action']==$this->plugin_slug_u .'_all')
{
if( empty( $_POST["_wpnonce"] ) || !wp_verify_nonce( $_POST["_wpnonce"], "Puvox_BackendCallJS") )
{
exit( __('Incorrect nonce. Refresh page and try again.') );
}
if(isset($_POST['PRO_check_key'])){
echo $this->license_status( sanitize_text_field($_POST['PRO_check_key']), "activate");
}
elseif(isset($_POST['PRO_save_results'])){
}
else{
do_action($this->default_nonce_action_key($_POST['act']));
}
wp_die();
}
exit( __('Unknown-action') );
}
public function ajax_backend_call_nopriv(){
}
public function unzip_url($url, $where)
{
$zipLoc = $where.'/temp_'.rand(1,999999). "_". (basename($url)).'.zip';
wp_remote_get
(
$url,
[
'timeout' => 300,
'stream' => true,
'filename' => $zipLoc
]
);
$this->unzip($zipLoc, $where);
@unlink($zipLoc);
}
public function unzip($path, $where)
{
$this->file->create_directory($where);
require_once(ABSPATH . 'wp-admin/includes/file.php');
\WP_Filesystem();
\unzip_file($path, $where);
$this->sleep(300);
}
public function unzip_in_dir($dir, $rewrite=true)
{
$this->temp_unziped_folders = [];
foreach( array_filter(glob($dir.'/*.zip'), 'is_file') as $each_zip)
{
$uniqueTag = md5($each_zip);
$each_dir = substr($each_zip, 0, -4); //trim .zip
if (empty($each_dir)) return; // ! must have, to avoid empty directory threat
// remove if previous unpack was partial.
if( is_dir($each_dir) && $rewrite )
{
if( !array_key_exists($uniqueTag, $this->temp_unziped_folders) || $this->temp_unziped_folders[$uniqueTag]==false )
{
$this->file->delete_directory($each_dir);
$this->sleep(500);
//$this->create_directory($pathh);
}
}
elseif( !is_dir($each_dir) )
{
$this->temp_unziped_folders[$uniqueTag] = false;
$this->unzip($each_zip, dirname($each_zip));
$this->temp_unziped_folders[$uniqueTag] = true;
}
}
}
public function is_plugin_active($name) //i.e. woocommerce/woocommerce.php
{
return in_array($name, get_option('active_plugins') );
}
public function woocommerce_products_to_array($products)
{
$new = [];
foreach($products as $p) $new[] =$p->get_data();
return $new;
}
public function shortcode_handler_old($atts, $content=false){
$d=debug_backtrace()[0];
if(!empty($d['args']))
{
if(!empty($d['args'][2]))
{
$name = $d['args'][2];
$args = $this->shortcode_atts($name, $atts);
return call_user_func( [$this, $name], $args, $content);
}
}
}
//Advanced custom fields alternative
public function acf_getfield_detect(){
add_action('plugins_loaded', function(){
if (!function_exists('get_field')){
function get_field(){
return 'Advanced Custom Fields plugin is not installed';
}
}
}, 1);
}
// ================ flash rules ================= //
public function flush_rules_double(){ add_action('wp', [$this, 'my_flush__rewrite'] ); }
public function my_flush__rewrite($RedirectFlushToo=false){
$GLOBALS['wp_rewrite']->flush_rules();
flush_rewrite_rules();
//DUE TO WORDPRESS BUG ( https://core.trac.wordpress.org/ticket/32023 ) , i use this: (//USE ECHO ONLY! because code maybe executed before other PHP functions.. so, we shouldnt stop&redirect, but we should redirect from already executed PHP output )
if($RedirectFlushToo) {echo ' ';}
}
public function flush_rules($redirect=false){
flush_rewrite_rules();
if($redirect) {
if ($redirect=="js"){ $this->js_redirect(); } else { $this->php_redirect(); }
}
}
public function output_js_categories_ids()
{
if( ! ($out = get_transient('termids_for_js'))) {
$terms= get_terms();
foreach($terms as $term){
$cats[$term->term_id] = urldecode($term->slug);
}
$out = json_encode($cats, JSON_UNESCAPED_UNICODE);
set_transient('termids_for_js', $out , 60*60);
}
echo "";
}
// ==================== shortcodes =======================
public function shortcode_atts($shortcode, $predefined_atts, $passed_atts){
$new_arr=[];
foreach($predefined_atts as $x){
$new_arr[ $x[0] ] = $this->string_to_value($x[1]) ;
}
if (!empty($passed_atts)) {
$filtered_atts=[];
foreach($passed_atts as $key=>$value){
$filtered_atts[$key] = $this->string_to_value($value) ;
}
$new_arr = array_merge($new_arr, $filtered_atts);
}
$new_arr = $this->sanitize_shortcode_empty_defaults_pre($new_arr);
$new_atts = shortcode_atts($new_arr, [] );
return $new_atts;
}
public function sanitize_shortcode_empty_defaults_pre($atts){
$ar= ["...","___", 0];
foreach($ar as $e) { if (array_key_exists($e, $atts)) unset($atts[$e]); }
return $atts;
}
public function sanitize_shortcode_empty_defaults($attsArray){
$new_arr = [];
foreach($attsArray as $eachAttArr)
{
if ( empty($eachAttArr[0]) || in_array($eachAttArr[0], ["...","___"] ) ) continue;
$new_arr[] = $eachAttArr;
}
return $new_arr;
}
public function shortcode_alternative_message($name, $params_name=false)
{
?>
<?php echo do_shortcode('[.....]'); ?>
or
<?php if (function_exists('')) { echo (["arg1"=>"value1", ...]); } ?>
';
$out .= '['. $array['name'].''; $atts = $this->sanitize_shortcode_empty_defaults($array['atts']); foreach( $atts as $key=>$value){ $out .= " ".$value[0].'="'. htmlentities($this->truefalse_to_string($value[1])).'"';} $out .=']';
$out = ( $strip_tags ? strip_tags($out) : $out);
$out = ( $htmlentities ? htmlentities($out) : $out);
if( $ended )
$out .= "...[/".$array['name']."]";
$out .= '';
return $out;
}
public function shortcode_example($shortcode, $array, $ended=false){
$out="[$shortcode "; foreach($array as $key=>$value){ $out .= $key.'="'.$this->value_to_string($value) .'" '; } $out = trim($out). "]";
if( $ended )
$out .= "...[/$shortcode]";
return $out;
}
public function shortcodes_table($name, $array)
{
// ======= example ========
//
// $this->shortcodes_table( "breadcrumbs", [
// [ 'id', '', __('Post ID (you can ignore that parameter if you want to get for current post)', 'breadcrumbs-shortcode') ],
// [ 'delimiter', 'hello', __('Your desired delimiter', 'breadcrumbs-shortcode') ],
// ] );
?>
ID, '_wp_page_template', true); // page-templates/my_homepage_1.php
return basename($name);
}
return false;
}
// disable georgian russian slugs: https://pastebin_com/UmvhEmuz
// example to dump: add_action('save_post', function () { var_dump($_POST); exit; }, 99, 11);
public function debug_actions() { add_action( 'wp_footer', function (){ var_dump( $GLOBALS['wp_filter']); } ); }
public function called_script() { return $_SERVER["SCRIPT_FILENAME"];}
public function is_subscriber() { return $this->is_helper_('read'); }
public function is_contributor() { return $this->is_helper_('edit_posts'); }
public function is_author() { return $this->is_helper_('upload_files'); }
public function is_editor() { return $this->is_helper_('edit_others_posts'); }
public function is_administrator(){ return $this->is_helper_('install_plugins'); }
private function is_helper_($what){ return (function_exists('current_user_can') || require_once(ABSPATH.'wp-includes/pluggable.php')) && current_user_can($what); }
public function user_id(){return (function_exists('current_user_can') || require_once(ABSPATH.'wp-includes/pluggable.php')) ? get_current_user_id() : -1; }
public function init_if_editor($func, $initPriority=1){
add_action('init', function() use ($func) {
if ($this->is_editor())
call_user_func($func);
}, $initPriority);
}
public function get_user_role( $user_id = 0 ) {
$user = ( $user_id ) ? get_userdata( $user_id ) : wp_get_current_user();
return current( $user->roles );
}
// ##############
public function get_transient($transientName, $default=''){
if( ($value = get_transient($transientName))===false ) {
$value = $default;
}
return $value;
}
public function set_transient($transientName, $value, $seconds=8640000){
return set_transient($transientName, $value, $seconds);
}
public function append_transient_array($transientName, $key=null, $valueToAddInArray=null, $seconds=8640000, $autoreset_if_array_above=999){
$current_arr= $this->get_transient($transientName, []);
if( count($current_arr) > $autoreset_if_array_above )
$current_arr = $this->array_part( $current_arr, $autoreset_if_array_above, 'end');
if ($key) $current_arr[$key] = $valueToAddInArray;
else $current_arr[] = $valueToAddInArray;
return $this->set_transient($transientName,$current_arr, $seconds);
}
public function timer_remains( $uniqueActionId, $cache_seconds=9999999999, $reset=false ){
return $this->check_timer_remains($uniqueActionId, $cache_seconds, $reset );
}
public function check_timer_remains($uniqueActionId, $cache_seconds=9999999999, $reset=false ){
$remains = 0;
if ( $cache_seconds>0 )
{
$transientName = $this->slug ."_px_timer_flag_".$uniqueActionId;
$last_time = $this->get_transient($transientName,0);
if( $last_time > 0 ) {
$remains = ($last_time + $cache_seconds) - time();
if ($reset)
$this->set_transient($transientName, time(), $cache_seconds);
}
else{
$this->set_transient($transientName, time(), $cache_seconds);
}
}
return $remains;
}
public function check_timer_remains_function($uniqueActionId, $callback, $cache_seconds=9999999999){
$remains = 0;
if ( $cache_seconds>0 )
{
$transientName = $this->slug ."_px_timer_flag_".$uniqueActionId;
$last_time = $this->get_transient($transientName,0);
if( $last_time > 0 ) {
$remains = ($last_time + $cache_seconds) - time();
}
else{
call_user_func($callback);
$this->set_transient($transientName, time(), $cache_seconds);
}
}
return $remains;
}
//delete all transients:
public function delete_all_transients(){
global $wpdb;
$wpdb->query("DELETE FROM `{$wpdb->prefix}options` WHERE `option_name` LIKE ('_transient_%');");
$wpdb->query("DELETE FROM `{$wpdb->prefix}options` WHERE `option_name` LIKE ('_site_transient_%');");
}
public function option_exists($name, $site_wide=false){
global $wpdb;
$tablename = ($site_wide ? $wpdb->base_prefix : $wpdb->prefix).'options';
$sql = $wpdb->prepare("SELECT * FROM " . $tablename . " WHERE option_name ='%s' LIMIT 1", $name);
return $wpdb->query($sql);
}
public function transient_exists ($transientName, $site_wide = false) {
// get_option('_transient_timeout_' . $your_transient); gets timestamp of expiration, but is heavier than below line
return $this->option_exists('_transient_timeout_'.$transientName, $site_wide);
}
// ################################
public function post_is_in_descendant_category($cat, $postttId) {
$descendants = array_merge( array($cat,''), get_term_children((int) $cat, 'category') );
return (in_category($descendants, $postttId)) ? true : false;
}
//if post is ansector of category //is_category(4)
public function post_or_cat_is_in_ansector($upper_category_id){
$truee_fals =false; global $post;
//for categories
if (is_archive()) { $cur_cat_id = get_query_var('cat');
if ($cur_cat_id == $upper_category_id || cat_is_ancestor_of($upper_category_id, $cur_cat_id)) {return true;}
}
else {
if (in_category( $upper_category_id, $post->ID )) { return true;}
}
//$curr_post = get_post($post->ID); $truee_fals=cat_is_ancestor_of($upper_category_id, $curr_post->$post_category) ? true : $truee_fals;
}
public function get_metas_by_metakv($key, $value=null, $what=false) {
global $wpdb;
$results = $wpdb->get_results(
$wpdb->prepare( "SELECT %s FROM ".$wpdb->postmeta." WHERE meta_key=%s %s", ($what ?: "*"), $key, ($value ? " AND meta_value=$value" : "") )
);
if (!empty($results)) {
if ($what){
$array= array();
foreach($results as $index => $result) { $array[$index] = $result->{$what}; }
return $array;
}
return $results;
}
return false;
}
// metaboxes, meta-box, media-uploaders: https://pastebin_com/ePszrRWb
public function error_mail($subject, $text){
return wp_mail(get_option('admin_email'), $subject, $text );
}
public function myframe_center($content){
if(is_singular() && stripos($content,'