I'm using wp_localize_script(); to alter the JS in a theme I'm building, like so:
wp_enqueue_script('custom', get_bloginfo('template_directory') . '/js/script.js');
$settings = get_option('bro_options');
wp_localize_script('custom','settings',$settings);
While this is good, the way this works is it writes inline JS right before the JS file in question loads, that way you can use certain variables to modify the JS and how it functions.
Problem is, I don't really like this option and how it outputs inline JS. Does anyone know of an alternative to this? I'm pretty sure this isn't how everyone does this with their theme options so there must be another way.
Any help whatsoever would be appreciated, please no links to plugins either.
In short: I'm looking for an alternative to using wp_localize_script(); or a better way of using it.
What I did was create a file called settings.js.php and in that I included the wp-config.php file.
Like so:
<?php
header("Content-type: application/x-javascript");
$c = 0;
while($exists !== true && $notfound !== true) {
$c++;
$str = $str . '../';
if(file_exists($str.'wp-config.php')) {
$exists = true;
include($str.'wp-config.php');
$i = 0;
$amount = sizeof($bro);
echo 'var settings={';
foreach($bro as $key => $value) {
$i++;
if($i<$amount) {
echo $key . ':"' . $value . '",';
} else {
echo $key . ':"' . $value . '"';
}
}
echo '};';
}
if($c === 20) {
$notfound = true;
}
}
?>
Which would output my options in a variable like this:
var settings = {
foo: true,
bar: false
};
I would enqueue this file before my custom.js file that way I could determine if some settings were on and off.
if(settings.foo === true) {
...
}
All this so I don't have inline JS, there may be some cache issues but I'd rather have that than it output all options inline.
Related
In the view, right before the footer, I want to load three JavaScript files. So, the controller sets three variables. For example, $js_1 = "bootstrap.js", $js_2 = '' and $js_3 = "tinymce.js", which may or may not be empty. The logic is, it should echo only if the variable is not empty. I also want to use the ternary if operator.
This was the best I could try.
for ($i = 1; $i <= 3; $i++)
{
echo (!empty ('$js_' . $i)) ? get_jscript('$js_' . $i) : NULL;
}
The function get_jscript() simply returns the HTML script src.
function get_jscript($js)
{
return '<script type="text/javascript" src="' . $js . '"></script> ';
}
Please note that I intend to ask this question to primarily learn the correct PHP syntax and not just load JS in the view.
if you can create a array like this->
$javascript = array('js_1' => "bootstrap.js", 'js_2' => '', 'js_3' = "tinymce.js");
then in your view you have to just call a method
loop_javascript($javascript);
it's better to create a function in codeigniter helper and call that helper in controller's function (check how to use helpers in codeingiter) https://ellislab.com/codeigniter/user-guide/general/helpers.html->
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('loop_javascript'))
{
function loop_javascript($jscript_array)
{
foreach($jscript_array as $key =>$value){
if($value != ''){
echo '<script type="text/javascript" src="' . $value. '"></script>';
}
}
}
}
This has some great info on how to use variable variables.
for ($i = 1; $i <= 3; $i++)
{
echo (!empty (${'js_'.$i})) ? get_jscript(${'js_'.$i}) : NULL;
}
for ($i = 1; $i <= 3; $i++)
{
if(!empty($js.'_'.$i)){ echo get_jscript($js.'_'.$i); echo "</br>";}
}
function get_jscript($js)
{
return '<script type="text/javascript" src="' . $js . '"></script> ';
}
I have a lot of custom fields in my WooCommerce checkout, and I'm trying to display them all on the admin page.
The number of fields varies from user to user, therefor I need to figure out how many fields of the name "$order-billing_date_of_birth" there is.
$order-billing_date_of_birth1
$order-billing_date_of_birth2
$order-billing_date_of_birth3
...and so on
I thought maybe I could use a loop like this.
for ($x = 0; $x <= 100; $x++) {
echo '<p><strong>'.__('Date of birth').'</strong>: ' . $order->billing_date_of_birth.$x . '</p>';
}
My question is: How do I combine the two "billing_date_of_birth" and "$x" to work as "$order->billing_of_birth1".
There's probably better ways to solve this as well.
Following is what you need to do
for ($x = 0; $x <= 100; $x++) {
$prop = "billing_date_of_birth".$x ;
echo '<p><strong>'.__('Date of birth').'</strong>: ' . $order->$prop . '</p>';
}
Here is an example code to achieve the requirements.
Converting the Object to array and then finding the element.
<?php
$object = new StdClass;
$object->foo1 = 'Hey';
$object->bar1 = 'Friend';
$array_obj=(array) $object;
//var_dump( $array_obj );
$bar='bar';
$num=1;
echo ($array_obj[$bar.$num]);
?>
Try something similar, applied to a class.
for example
list-group-item1
list-group-item2
list-group-item3
With this code
jQuery(function($) {
$('.list-group-item').each(function(i) {
$(this).attr('class',"list-group-item"+i);
});
});
I have to do a php website for college.
I have to create a password and a submit button. After the I have posted the password I should get text from a html file. What is the best to achieve that?
I tried:
foreach($files as $file2) {
if($_POST['submitPassword']){
if($file2 === '.' OR $file2 === '..' OR $file2 === 'thumbs.db' OR !is_dir($folder.'/'.$file2)) {continue;}
if(file_exists($folder.'/'.$file2.'/doubleindemnity.gif') AND file_exists($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm')) {
echo '<div class="Container">';
echo "<div class='image2'><img src='$folder/$file/doubleindemnity.gif'>";
$lines4 = file($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm');
$count = count($lines4);
for($a = 0;$a < $count;$a++) {
echo substr($lines4[$a],strlen($folder),strpos($lines4[$a], '.')-strlen($folder));
}
echo "</div>";
}
echo "</div>";
}
}
?>
Help would be highly appreciated:)
Cheers:)
You can easily include the contents of an html file through include(). For example:
include($folder.'/'.$file2.'/DOUBLEINDEMNITY.htm');
It will call the entire file, and output it (since it's not a PHP file for execution)
My PHP is failing me. I'm trying to put a div around an element in a function. Here is the original code:
if ($withCurrency) {
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
return $currency . ' ' . $lowestPrice;
}
I want to put a div around the $currency.
I've tried changing this line:
return $currency . ' ' . $lowestPrice;
to this:
return "<div>" . $currency . "</div> " . $lowestPrice;
However that actually outputs the div tags as text on the page. Can someone tell me how to add the divs so they render as html?
UPDATE:
Here is the entire function:
function getTourPrice($tourId, $withCurrency = true) {
$lowestPrice = false;
$offers = getTourOffers($tourId);
// first get price from special offers
foreach ($offers as $offer) {
if ((isset($offer->options['special'])) && ((!$lowestPrice) || floatval($offer->options['price']) < $lowestPrice)) {
$lowestPrice = floatval($offer->options['price']);
}
}
// if special price isn't available then get price from normal offers
if (!$lowestPrice) {
foreach ($offers as $offer) {
if ((!$lowestPrice) || (floatval($offer->options['price']) < $lowestPrice)) {
$lowestPrice = floatval($offer->options['price']);
}
}
}
if (!$lowestPrice) return false;
if ($withCurrency) {
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
return $currency . ' ' . $lowestPrice;
} else {
return $lowestPrice;
}
}
The result of that function is called with the following code:
{var $lp = getTourPrice($post->id)}
{if $lp}<div class="item-price"><span><span><span class="from">From</span>{$lp}</span></span></div>{/if}
If I use echo instead of return like this:
echo "<div>" . $currency . "</div> " . $lowestPrice;
I lose all the html above. I.E. What was the following:
<div class="item-price"><span><span><span class="from">From</span>{$lp}</span></span></div>
Becomes this:
<div>R</div> 56200
(where R is $currency and 56200 is $lowestPrice)
Hope that's not painfully convoluted.
This will have something to do with what you are doing with the return
I imagine if you did this:
if ($withCurrency) {
$currency =
(isset($GLOBALS['aitThemeOptions']->directory->currency)) ?
$GLOBALS['aitThemeOptions']->directory->currency :
'';
echo "<div>" . $currency . "</div> ";
}
It would work.
Is your code the end of a function?
Try using the :
{$lp|escape:false}
I would simply place the div in the $currency variable, so it will be added upon return. I would change this line of code:
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? $GLOBALS['aitThemeOptions']->directory->currency : '';
to this:
$currency = (isset($GLOBALS['aitThemeOptions']->directory->currency)) ? '<div>'.$GLOBALS['aitThemeOptions']->directory->currency.'</div>' : '';
or another method:
$currency = '<div>'.$currency.'</div>';
This way you are defining the html in the variable and not in the return. This is not tested, but it is the way I tend to code. :) Hope it helps!
Also one more thing, it is a bit of controversy among programmers, but I also recommend using single quotes when defining html in php.
My name is Manuel, I am a web design student and am starting to take my first steps with web design. Recently I tried to validate
this site:
http://accesosnormalizados.com
I used the W3C validator, at first I found about 30 errors, and can correct them all except one that says: 'there is no attribute
"onload"'.
Apparently not support XHTML onload tag, and I use a Joomla extension called Vertical Menu using onload. This is a free extension and works well but I have found it has some bugs, especially when validating the website.
This is the PHP code for extension:
get( 'menutype', 'mainmenu' );
$qry = "SELECT id, name,parent, link,type,browserNav FROM #__menu WHERE menutype = '".$menutype."' AND published = 1 ORDER BY ordering";
$database->setQuery($qry);
$rows = $database->loadObjectList();
if(isset($GLOBALS['vertical_menu'])) $GLOBALS['vertical_menu']++;
else $GLOBALS['vertical_menu'] = 0;
function getMenuChildList($rows, $parentId) {
$childRows = array();
foreach ($rows as $row) {
if ($row->parent == $parentId) {
$childRows[] = $row;
}
}
return $childRows;
}
function drawVerticalMenu($rows, $showsubcats, $parentId = 0) {
$categories = $showsubcats || !$parentId ? getMenuChildList($rows, $parentId) : array();
if ($parentId) {
if (!count($categories)) {
echo '';
return;
} else echo '';
echo '';
} else echo '';
echo '';
foreach ($categories as $category) {
$link = $category->link. (preg_match("/^http:\/\/|^https:\/\//",$category->link)? "" : '&Itemid='.$category->id);
$blank = $category->browserNav? ' target="_blank" ' : ' ';
echo 'id.'" class="menu">'.$category->name.' ';
drawVerticalMenu($rows, $showsubcats, $category->id);
}
echo '';
if ($parentId && count($categories)) echo '';
}
$document = &JFactory::getDocument();
$document->addScript('https://ajax.googleapis.com/ajax/libs/dojo/1.5.0/dojo/dojo.xd.js');
$document->addScript('modules/mod_vertical_menu/script/menu.js');
$document->addStyleSheet('modules/mod_vertical_menu/style/menu.css');
$document->addCustomTag('
div#MenuContainer'.$GLOBALS['vertical_menu'].' table#VerticalMenu'.$GLOBALS['vertical_menu'].' {
width: '.$params->get('categorymenu_width', 150).'px;
opacity: '.$params->get('categorymenu_out', 0.8).';
FILTER: progid:DXImageTransform.Microsoft.Alpha(Opacity='.($params->get('categorymenu_out', 0.8)*100).');
}
');
echo '';
drawVerticalMenu($rows, $params->get('show_subcats', 1));
echo 'get('categorymenu_out', 0.8).',over : '.$params->get('categorymenu_over', 1).',duration : '.$params->get('categorymenu_fade', 300).',id : '.$GLOBALS['vertical_menu'].',width : '.$params->get('categorymenu_width', 150).'});" alt=""/>';
echo '';
?>
The problem is at the end:
echo '';
drawVerticalMenu($rows, $params->get('show_subcats', 1));
echo 'get('categorymenu_out', 0.8).',over : '.$params->get('categorymenu_over', 1).',duration : '.$params->get('categorymenu_fade', 300).',id : '.$GLOBALS['vertical_menu'].',width : '.$params->get('categorymenu_width', 150).'});" alt=""/>';
echo '';
?>
I think the extension uses the onload event to display the sub-menus when the user moves the mouse pointer over it.
What I want is to replace the onload with other event handler or some other label that is supported by XHTML and that is as similar to onload.
I would appreciate your help ...
You can remove the onload attributes and then add some simple javaScript to your page to run some functions when the page finishes loading.
It would look something like this:
<script>
window.onload=function(){
new WW.VerticalMenu({out : 1,over : 1,duration : 300,id : 0,width : 180}); // example of one of the functions being run
};
</script>
Good luck with your studies
It appears the source comes out like this right
<img src="/modules/mod_vertical_menu/images/center.gif" style="display:none" onload="new WW.VerticalMenu({out : 1,over : 1,duration : 300,id : 0,width : 180});" alt=""/>
As that looks like imho an unsavoury method of instantiating the menu I would try and loose that attribute completely by removing the offending php echo section and instead add javascript to load
as this is using dojo maybe this will help -- sorry I do not use dojo
http://mail.dojotoolkit.org/pipermail/dojo-interest/2012-May/066106.html
so php wise this would be
echo '<img src="modules/mod_vertical_menu/images/center.gif" style="display:none" alt=""/>'; echo '</div>';
echo "<script>" ."javascript or dojo script here ".</script>"
I would even suggest removing the image and using the window onload advocated below if you can