Treeview Directory reacts with Datatable - javascript

I have a treeview directory. The directory is an actual viewing of folders with files on it and beside the treeview of directory I have a datatable.
The interface looks like this:
When I click a treeview it will show its path through alert. Like this:( I clicked the runblack.png).
My question is how can I make the treeview react with the datatable beside.
Like if I click the year the datatable will search all files with the same year.
Then if i click the category below the year it will search the category with the year.
This is my code for the directory:
<?php
function php_file_tree($directory, $return_link, $extensions = array()) {
// Generates a valid XHTML list of all directories, sub-directories, and files in $directory
// Remove trailing slash
if( substr($directory, -1) == "/" ) $directory = substr($directory, 0, strlen($directory) - 1);
$code .= php_file_tree_dir($directory, $return_link, $extensions);
return $code;
}
function php_file_tree_dir($directory, $return_link, $extensions = array(), $first_call = true) {
// Recursive function called by php_file_tree() to list directories/files
// Get and sort directories/files
if( function_exists("scandir") ) $file = scandir($directory); else $file = php4_scandir($directory);
natcasesort($file);
// Make directories first
$files = $dirs = array();
foreach($file as $this_file) {
if( is_dir("$directory/$this_file" ) ) $dirs[] = $this_file; else $files[] = $this_file;
}
$file = array_merge($dirs, $files);
// Filter unwanted extensions
if( !empty($extensions) ) {
foreach( array_keys($file) as $key ) {
if( !is_dir("$directory/$file[$key]") ) {
$ext = substr($file[$key], strrpos($file[$key], ".") + 1);
if( !in_array($ext, $extensions) ) unset($file[$key]);
}
}
}
if( count($file) > 2 ) { // Use 2 instead of 0 to account for . and .. "directories"
$php_file_tree = "<ul";
if( $first_call ) { $php_file_tree .= " class=\"dirlist\""; $first_call = false; }
$php_file_tree .= ">";
foreach( $file as $this_file ) {
if( $this_file != "." && $this_file != ".." ) {
if( is_dir("$directory/$this_file") ) {
// Directory
$flink="./$directory/$this_file";
$dlink = str_replace("[link]", "$directory/". urlencode($this_file), $return_link);
$php_file_tree .= "<li class=\"hdir\" >" . htmlspecialchars($this_file)."" ;
$php_file_tree .= php_file_tree_dir("$directory/$this_file", $return_link ,$extensions, false);
$php_file_tree .= "</li>";
} else {
// File
// Get extension (prepend 'ext-' to prevent invalid classes from extensions that begin with numbers)
$ext = "ext-" . substr($this_file, strrpos($this_file, ".") + 1);
$link = str_replace("[link]", "$directory/" . urlencode($this_file), $return_link);
$flink="./$directory/" . urlencode($this_file);
$fsize = filesize ("$flink");
$ftime=date ("F d Y H:i:s.", filemtime($flink));
$php_file_tree .= "<li class=\"hfile " . strtolower($ext) . "\">" . htmlspecialchars($this_file) . "<br></li>";
}
}
}
$php_file_tree .= "</ul>";
}
return $php_file_tree;
}
// For PHP4 compatibility
function php4_scandir($dir) {
$dh = opendir($dir);
while( false !== ($filename = readdir($dh)) ) {
$files[] = $filename;
}
sort($files);
return($files);
}
I want it like when the treeview is clicked I will pass a query to the datatable to search for the needed data.
Query example: SELECT * FROM TABLE WHERE DATE = 'from treeview' AND CATEGORY = 'from treeview' ... and so on
My datatable viewing of data from the database is just the usual javascript to php connection for select.

Related

I need to choose more values from some tasks that belong to same project

My question is: Is there any other method to select the values I need from all the tasks that belongs to same project and sum them? Other method that I tried in the down description?
Description:
I have an app where I can create a Project and, inside the Project, I can create Tasks. For every Task, I can add a percent and calculate a price (example picture 1).
Then I have a report page where I want to calculate all the prices from all of the Tasks of same project (example picture 2).
My problem is when I want to select all the prices from all the tasks that belongs to same projects and sum them in the table "price" of report page.
For the moment I tried a method with the code I put down, and it's not working as I need, because it take the correct value from the first task of the project but dont take corect value from the ohther tasks from the same project
picture 1
picture 2 (but here the problem is that just the first array is corrent the other are not)
code I use ( I commented in the code with "the code that doesnt work" the part that make the sum) :
<?php
defined('BASEPATH') or exit('No direct script access allowed');
$hasPermissionEdit = has_permission('tasks', '', 'edit');
$hasPermissionDelete = has_permission('tasks', '', 'delete');
$tasksPriorities = get_tasks_priorities();
$aColumns = [
db_prefix() . 'tasks.id as id',
db_prefix() . 'tasks.name as task_name',
'count(tbltasks.id) as totaltasks',
//'(SELECT GROUP_CONCAT(name SEPARATOR ",") FROM ' . db_prefix() . 'tasks) as itemlist',
];
$sIndexColumn = 'id';
$sTable = db_prefix() . 'tasks';
$where = [];
$join = [];
$sGroupBy = ' group by '.db_prefix() . 'tasks.rel_id';
// =============== Filter =================
if (isset($ts_filter_data['period-from']) && $ts_filter_data['period-from'] != '' && isset($ts_filter_data['period-to']) && $ts_filter_data['period-to'] != '') {
$ts_filter_from = to_sql_date($ts_filter_data['period-from']);
$ts_filter_from = date('Y-m-d', strtotime($ts_filter_from));
$ts_filter_to = to_sql_date($ts_filter_data['period-to']);
$ts_filter_to = date('Y-m-d', strtotime($ts_filter_to));
}
if (isset($ts_filter_data['this_month']) && $ts_filter_data['this_month'] != '') {
$ts_filter_from = date('Y-m-01');
$ts_filter_to = date('Y-m-t 23:59:59');
}
if (isset($ts_filter_data['last_month']) && $ts_filter_data['last_month'] != '') {
$ts_filter_from = date('Y-m-01', strtotime('-1 MONTH'));;
$ts_filter_to = date('Y-m-t 23:59:59', strtotime('-1 MONTH'));
}
if (isset($ts_filter_data['this_week']) && $ts_filter_data['this_week'] != '') {
$ts_filter_from = date('Y-m-d', strtotime('monday this week'));
$ts_filter_to = date('Y-m-d 23:59:59', strtotime('sunday this week'));
}
if (isset($ts_filter_data['last_week']) && $ts_filter_data['last_week'] != '') {
$ts_filter_from = date('Y-m-d', strtotime('monday last week'));
$ts_filter_to = date('Y-m-d 23:59:59', strtotime('sunday last week'));
}
if($ts_filter_from){
array_push($where, 'AND '.db_prefix().'tasks.startdate >="'.$ts_filter_from.'"');
}
if($ts_filter_to){
array_push($where, 'AND '.db_prefix().'tasks.startdate <="'.$ts_filter_to.'"');
}
// =============== Filter =================
array_push($where, 'AND '.db_prefix().'tasks.rel_type="project"');
// Script By Dev Websyms
$aColumns = hooks()->apply_filters('tasks_table_sql_columns', $aColumns);
// Fix for big queries. Some hosting have max_join_limit
if (count($custom_fields) > 4) {
#$this->ci->db->query('SET SQL_BIG_SELECTS=1');
}
$result = data_tables_init(
$aColumns,
$sIndexColumn,
$sTable,
$join,
$where,
[
'tbltasks.rel_type',
'tbltasks.rel_id',
'tbltasks.task_item_percentage',
'tbltasks.task_duration',
tasks_rel_name_select_query() . ' as rel_name',
get_sql_select_task_assignees_ids() . ' as assignees_ids',
'(SELECT staffid FROM ' . db_prefix() . 'task_assigned WHERE taskid=' . db_prefix() . 'tasks.id AND staffid=' . get_staff_user_id() . ') as is_assigned',
],
$sGroupBy
);
$output = $result['output'];
$rResult = $result['rResult'];
$loop = 1;
foreach ($rResult as $aRow) {
$row = [];
$projectTaskIds = get_assign_project_task($aRow['rel_id']);
$assignees_ids = $aRow['assignees_ids'];
$assignees_id = explode(',', $assignees_ids);
$calA = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
if($projectTaskIds && count($projectTaskIds)){
$realTime = 0;
$estimateCost = 0;
$itemName = '';
$realCost = 0;
$realCostArr = array();
$totalCalEArr = array();
foreach ($projectTaskIds as $key => $projectTaskId) {
// echo $projectTaskId['id'];
// echo "<br>";
$calB = 0;
$calC = 0;
$itemtotal = 0;
$items = get_items_by_type('task', $projectTaskId['id']);
if($items && count($items) > 0){
$itemNo = 1;
foreach ($items as $key => $item) {
$itemtotal += ($item["rate"]*$item["qty"]);
$itemName .= '<div>'.$itemNo.'.'.$item["description"].' <b>('.round($item["qty"]).')</b>'.'</div>';
$itemNo++;
}
}
// =============== the code that doesn't work ============
$calF = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
$calG = get_task_custom_billable_amount($aRow['id']);
$calE = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
if(isset($aRow['task_item_percentage'])){
$calE = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))
*($aRow['task_item_percentage']/100)))
+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
}
$totalCalEArr[] = $calE;
if($totalCalEArr && count($totalCalEArr) > 0){
$totalsCalEaMount = 0;
foreach ($totalCalEArr as $key => $totalvalue) {
$totalsCalEaMount += $totalvalue;
}
}
// =============== the code that doesnt work ============
$realTime += get_calc_task_real_logged_time($projectTaskId['id']);
$calB = get_task_custom_billable_amount($projectTaskId['id']);
if($aRow['task_item_percentage']){
$calC = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))*($aRow['task_item_percentage']/100)))+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
} else {
$calC = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
}
$estimateCost += round($itemtotal+($calA * $aRow['task_duration'] / 60));
$realCost = round($itemtotal+$calB);
// if($calC = 0){ $realCost = round($itemtotal+$calB);} else { $realCost = round($itemtotal+$calB+$calC);
// }
$realCostArr[] = $realCost;
}
if($realCostArr && count($realCostArr) > 0){
$realCostAmount = 0;
foreach ($realCostArr as $key => $reslcostvalue) {
$realCostAmount += $reslcostvalue;
}
}
}
$outputName = '';
$relName = '';
$row[] = $loop;
if ($aRow['rel_name']) {
$relName = task_rel_name($aRow['rel_name'], $aRow['rel_id'], $aRow['rel_type']);
$link = task_rel_link($aRow['rel_id'], $aRow['rel_type']);
$relName = '<span class="hide"> - </span><a class="text-muted task-table-related" data-toggle="tooltip" title="' . _l('task_related_to') . '" href="' . $link . '">' . $relName . '</a>';
}
$row[] = $relName;
$row[] = count($projectTaskIds);
$row[] = $itemName;
$row[] = $aRow['task_duration']*count($projectTaskIds);
$row[] = round($realTime/60);
$row[] = round($estimateCost);
$row[] = round($realCostAmount);
$row[] = '';
$row[] = $totalCalEArr; // display as array or
//$row[] = $totalsCalEaMount; //to display as a sum
$output['aaData'][] = $row;
$loop++;
}
And if you need more details you can find a guide how to use it: http://amco.ro/pdf/Error%20presentation.pdf

how to fetch the content within <table> tag from an website

I used this code to fetch all the content of the website page.
$url = file_get_contents('https://berojgarjobs.com/forms/AirForceAFCAT.php'); echo $url;
This code shows all the content of the website but i want only those content
which is within <table></table> tag.
you can use javascript ,php,curl any to fetch the particular content within the tag from any website
suggest the answer if you can?
You can use PHP DOMDocument's loadHTML:
$doc = new DOMDocument();
$doc->loadHTML($url);
Then obtain the TABLE node from that object.
You may use preg_match_all function:
$url = file_get_contents('https://berojgarjobs.com/forms/AirForceAFCAT.php');
$pattern = "/<table(.*)<\/table>/i";
preg_match_all($pattern, $url, $match);
$table = $match[0][0];
echo $table;
There is other way:
$url = file_get_contents('https://www.sarkariexam.com/canara-bank-recruitment-2012/994');
$tables = [];
$pos = 0;
do {
$start = strpos($url, '<table', $pos);
$end = strpos($url, '</table', $pos);
if ($end !== false && $start !== false) {
$tables[] = substr($url, $start, $end - $start + 8);
$pos = $end;
}
} while ($end !== false && $start !== false);

trying to create a php foreach loop which generates a javascript file

So I have this script which im trying to create a filelist.js file from in php here's the code:
//CREATE fileslist.js
$thumbssize = "1";
$moviesize= "1";
$thumbarray = array_slice(scandir($tpath), 2);
echo print_r($thumbarray) . "<br/>";
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$script="
fileList = {};
fileList[\"thumbs\"] = {};
fileList[\"movies\"] = {};
fileList[\"title\"]=\"{$foldername}\";";
foreach($thumbarray as $item) {
print "fileList[\"thumbs\"][1]=["$item['0']","$item['2']","$item['3']","$item['4']","$item['5']","$item['6']"];";
}
$script2 = "
fileList[\"thumbs\"][\"size\"]={$thumbssize};
fileList[\"thumbs\"][\"size\"]={$moviesize};";
//$script = preg_replace('/\s\s+/', ' ', $script);
$scriptName= $_SERVER['DOCUMENT_ROOT'] . "/{$foldername}/assets/js/filelist.js";
file_put_contents($scriptName, trim($script . $script2) . "\n", FILE_APPEND);
echo "Generating filelist.js</br>";
}
This here is the example output of the array:
Array ( [0] => 863_example_r003.mp4 [1] => 863_example_r004.mp4 [2] => 863_example_r005.mp4 [3] => 863_example_r006.mp4 [4] => 863_example_r007.mp4 ) 1
This is the filelist.js output as it stands right now:
fileList = {};
fileList["thumbs"] = {};
fileList["movies"] = {};
fileList["title"]="test7";
fileList["thumbs"]["size"]=1;
fileList["thumbs"]["size"]=1;
So up until this point its doing what i want except I cannot figure out how to make a foreach loop to generate this type of output :
fileList = {};
fileList["thumbs"] = {};
fileList["movies"] = {};
fileList["title"]="863-example";
fileList["thumbs"][1]=["863_example_r048.mp4","863_example_r049.mp4","863_example_r050.mp4","863_example_r051.mp4","863_example_r052.mp4","863_example_r053.mp4"];
fileList["thumbs"][2]=["863_example_r054.mp4","863_example_r055.mp4","863_example_r056.mp4","863_example_r057.mp4","863_example_r058.mp4","863_example_r059.mp4"];
fileList["thumbs"][3]=["863_example_r060.mp4","863_example_r061.mp4","863_example_r062.mp4","863_example_r003.mp4","863_example_r063.mp4","863_example_r064.mp4"];
fileList["thumbs"][4]=["863_example_r065.mp4","863_example_r004.mp4","863_example_r067.mp4","863_example_r068.mp4","863_example_r069.mp4","863_example_r070.mp4"];
fileList["thumbs"][5]=["863_example_r005.mp4","863_example_r071.mp4","863_example_r072.mp4","863_example_r073.mp4","863_example_r074.mp4","863_example_r006.mp4"];
fileList["thumbs"][6]=["863_example_r075.mp4","863_example_r076.mp4","863_example_r077.mp4","863_example_r078.mp4","863_example_r007.mp4","863_example_r079.mp4"];
fileList["thumbs"][7]=["863_example_r080.mp4","863_example_r081.mp4","863_example_r082.mp4","863_example_r008.mp4","863_example_r083.mp4","863_example_r084.mp4"];
fileList["thumbs"][8]=["863_example_r085.mp4","863_example_r086.mp4","863_example_r009.mp4","863_example_r087.mp4","863_example_r088.mp4","863_example_r089.mp4"];
The [1], [2], [3] refers to a page number and there needs to be 6 items per page as the example above
Thank you for your feedback. Just a minute ago I refined the code and tested it in my localhost. Here is the changed code that gives the result:
$script1 = "";
$i = 0;
$j = 0;
$inrow = 6; // files in row
foreach($thumbarray as $item => $itemv) {
// beginning of the row
if($j % $inrow == 0){
$script1 .= "\nfileList[\"thumbs\"][".($i+1)."]=[";
}
$script1 .= "\"" . $itemv . "\","; // add filename "863_example_r048.mp4",
// end of the row
if(($j + $inrow + 1) % $inrow == 0){
// Delete comma at end of row
if(substr($script1,-1) == ","){
$script1 = substr($script1, 0, strlen($script1) - 1);
}
$script1 .= "];";
}
if($j % $inrow == 0){
$i++;
}
$j++;
}
Here is the tested result:
fileList["thumbs"][1]=[".AndroidStudio1.3",".ICEauthority",".PlayOnLinux",".Skype",".Xauthority",".adobe"];
fileList["thumbs"][2]=[".android",".audacity-data",".bash_history",".bashrc",".bibletime",".cache"];
fileList["thumbs"][3]=[".claws-mail",".config",".dbus",".directory",".dmrc",".dosbox"];
fileList["thumbs"][4]=[".emacs",".esd_auth",".fltk",".fontconfig",".fonts",".fonts.conf"];
fileList["thumbs"][5]=[".frozen-bubble",".gimp-2.8",".gnome",".gnome2",".gnome2_private",".gnupg"];
fileList["thumbs"][6]=[".gstreamer-0.10",".gtkrc-2.0",".gvfs",".icewm",".inputrc",".ivy2"];
fileList["thumbs"][7]=[".java",".jsword",".kde",".kde4",".kismet",".local"];
fileList["thumbs"][8]=[".macromedia",".mozilla",".mplayer",".mtpaint",".opera",".pki"];
fileList["thumbs"][9]=[".profile",".putty",".pyhistory",".qt",".remmina",".sbt"];
fileList["thumbs"][10]=[".skel",".ssh",".streamtuner",".sword",".themes",".thumbnails"];
fileList["thumbs"][11]=[".thunderbird",".vnc",".wine",".xboardrc",".xdg_menu_cache",".xim.template"];
fileList["thumbs"][12]=[".xinitrc.template",".xiphos",".xscreensaver",".xsession-errors",".xsession-errors-192.168.1.101:1",".xsession-errors-192.168.1.103:1"];
fileList["thumbs"][13]=[".xsession-errors-:0",".xsession-errors-:1",".y2log",".y2usersettings","20150901_134031.jpg","281436_wpmu-dev-dashboard-3.5.3.zip"];
fileList["thumbs"][14]=["Android","AndroidStudioProjects","Bible Analyzer User Modules","Calibre Library","Desktop","Documents"];
fileList["thumbs"][15]=["Downloads","Java","Kismet-20141124-23-54-29-1.alert","Kismet-20141124-23-54-29-1.gpsxml","Kismet-20141124-23-54-29-1.nettxt","Kismet-20141124-23-54-29-1.netxml"];
fileList["thumbs"][16]=["Kismet-20141124-23-54-29-1.pcapdump","Movies","Music","Phpgtk","Pictures","PlayOnLinux's virtual drives"];
fileList["thumbs"][17]=["Public","Templates","Videos","VirtualBox VMs","WPMUDEV_PLUGINS.zip","battery"];
fileList["thumbs"][18]=["bibleanalyzer","bibledesktop-2.0-beta","bin","ca.key","deklaracia.jpg","deklaracia2.jpg"];
fileList["thumbs"][19]=["dfc","http:⁄⁄www.biblestudytools.com⁄niv⁄.desktop","konq","projects","public_html","scala"];
fileList["thumbs"][20]=["somefile","somefile.txt","viber","wget-log","wp-cron.php?import_key=d&import_id=20&action=processing","Запис0003.amr"];
you need to change below part
$index = 1;
foreach($thumbarray as $item) {
$script .= "fileList[\"thumbs\"][$index]= ".json_encode($item).";" ;
$index++;
}
You need two indexes. $i is incremented every time $i is deleted in $inrow times properly with the remainder of 0. If you want 6 rows of files then $i should be increased 6 times less then $j which is increased every time. This way $i would change when $j is 6,12,18,24 and etc. You will need to play a little bit with the code ...
$script1 = "";
$i = 0;
$j = 0
$inrow = 6; // files in row
foreach($thumbarray as $item => $itemv) {
// beginning of the row
if($j % $inrow == 0){
$script1 .= "fileList[\"thumbs\"][".($i+1)."]=[";
}
$script1 .= "\"" . $itemv . "\","; // add filename "863_example_r048.mp4",
// end of the row
if($j % $inrow == 0){
// Delete comma at end of row
if(substr($script1,-1) == ","){
$script1 = substr($script1, 0, strlen($script1) - 1);
}
$script1 .= "]";
$i++;
}
$j++;
}

Uncaught SyntaxError: Unexpected token < - Wordpress

I am using the Penny auction theme and I am getting the following error message:
Uncaught SyntaxError: Unexpected token < penny_scripts.js:126
When I expand the error it shows:
(anonymous function) penny_scripts.js:126
$.ajax.success smart-updater.js:146
j jquery.js?ver=1.11.0:2
k.fireWith jquery.js?ver=1.11.0:2
x jquery.js?ver=1.11.0:4
b jquery.js?ver=1.11.0:4
Line 126 of penny_scripts.js is
var myObj = eval("(" + data + ")");
for (var i = 0; i < myObj.length; i++) <---This line
{
pid = myObj[i].pid;
rnd = myObj[i].rnd;
remaining_time = myObj[i].remaining_time;
current_bid = myObj[i].current_bid;
If I do alert(data); then I get the following message
Line 1092 of functions.php is:
$info = array(); global $wpdb;
$my_arr = $_POST['my_values'];
$OKOK = $_POST['OKOK'];
foreach($my_arr as $id_plus_rand)
{
$exp = explode("_",$id_plus_rand);
$pid = $exp[0];
$rnd = $exp[1];
//----------------------
$newpid = array();
$highest_bidder_id = PennyTheme_get_highest_bid_owner_obj($pid);
if($highest_bidder_id == false) $highest_bidder = "0";
else {
$s = "select user_login from ".$wpdb->users." where ID='{$highest_bidder_id->uid}'";
$r = $wpdb->get_results($s); $r = $r[0];
$highest_bidder = $r->user_login;
}
$newpid['highest_bidder'] = $highest_bidder;
$newpid['highest_bidder_id'] = $highest_bidder_id->id;
$newpid['pid'] = $pid;
$newpid['rnd'] = $rnd;
$newpid['remaining_time'] = get_post_meta($pid, 'ending', true) - current_time('timestamp',0);
$newpid['current_bid'] = PennyTheme_get_show_price(get_post_meta($pid, 'current_bid', true));
if($OKOK == "1"):
//$closed = get_post_meta($pid, 'closed', true);
//$post = get_post($pid);
$bids = "select * from ".$wpdb->prefix."penny_bids where pid='$pid' order by id DESC limit 13";
$res = $wpdb->get_results($bids);
$all_bids = '';
if(count($res) > 0)
{
$all_bids .= '<table width="100%">';
$all_bids .= '<thead><tr>';
$all_bids .= '<th>'.__('Username','PennyTheme').'</th>';
$all_bids .= '<th>'.__('Bid Amount','PennyTheme').'</th>';
// echo '<th>'.__('Date Made','PennyTheme').'</th>';
$all_bids .= '</tr></thead><tbody>';
//-------------
foreach($res as $row)
{
$user = get_userdata($row->uid);
$s = "select user_login from ".$wpdb->users." where ID='{$row->uid}'";
$r = $wpdb->get_results($s);
$all_bids .= '<tr>';
$all_bids .= '<th>'.$r[0]->user_login.'</th>';
$all_bids .= '<th>'.PennyTheme_get_show_price($row->bid).'</th>';
// echo '<th>'.date("d-M-Y H:i:s", $row->date_made).'</th>';
$all_bids .= '</tr>';
}
$all_bids .= '</tbody></table>';
}
else $all_bids .= __("No bids placed yet.", 'PennyTheme');
$newpid['bidders'] = $all_bids;
endif;
array_push($info,$newpid);
}
header('Content-type: application/json'); <---Line 1092
Line 146 of smart-update.js is:
if(es.rCallback && rCallback && es.rCallback.search(rCallback) != -1) {
window[rCallback](data);
} else {
es.callback(data); <---This line
}
Line 1395 of plugin.php:
function remove_menu_page( $menu_slug ) {
global $menu;
foreach ( $menu as $i => $item ) { <-- This line
if ( $menu_slug == $item[2] ) {
unset( $menu[$i] );
return $item;
}
}
return false;
}
I only get this error message when I am not logged into the site or logged in with an account that the user level is below Contributor.
I am unsure why that is happening or how to fix this. Any help is appreciated.
The above problem was caused by a plugin that I had enabled on my site. When I updated it, the error stopped. The error doesn't happen with version 2.19.5 or above. Changelog for 2.19.5
Remove Testimonials menu for authors removal code <--This was the change that fixed the error for me.
Require Aihrus Framework 1.1.4
Revise premium introduction
Update premium links

How to properly declare a php function as a variable in another function

I'm looking to display a piece of javascript after the 6th paragraph of every post on my wordpress blog. So far, I can only get the function to work when I'm using a fixed variable:
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = 'fixed variable such as <div>box</div>';
if (is_single()) {
return prefix_insert_after_paragraph( $ad_code, 6, $content );
}
return $content;
}
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
The javascript I'm trying to add:
function ad_unit() ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php
I've tried to declare $placeholder = ad_unit(); but it keep displaying the unit at the top of the content instead of after the 6th paragraph. Somehow the prefix_insert_after paragraph function doesn't work after I add the javascript function. Any ideas?
Try it with ob_start() and ob_get_clean()
function ad_unit()
{
ob_start();
?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write ('<div id="' + akId[0] + '"></div>');
</script>
<?php
return ob_get_clean();
}
So what happens is that with ob_start() you enable output buffering. You output the HTML but buffer it, then with ob_get_clean() you get the buffered output from the output buffer.
This will be cleaner without a function (and definitely work, I don't remember what plain HTML does when put in a PHP function):
// Somewhere above the rest of your application
ob_start(); ?>
/// YOUR HTML/javascript
<?php
$advertisement = ob_get_clean();
You need opening and closing brackets for the php function
<?php
function ad_unit() { ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php }

Categories