This is the current code which is displaying the images on the frontend gallery.
What i need is a link or button to delete a single image when pressed.
It should show a confirmation javascript alert before deleting and then delete
Don't need ajax just plain javascript page refreshes is no issue.
I have looked out over the internet but can't really find a good solution.
function Closify_Translate_Images_to_Photoswipe_HTML($galleries, $effect,
$random_id, $itemPerPage = 10, $disable_caption = "off", $imgWidth = '',
$titleEnabled = 'off', $isMultiPage)
{
// Update caption flag
$caption = ($disable_caption!="on")?true:false;
$itemWidth = '';
// Update title flag
$title = ($titleEnabled!="on")?true:false;
// Update item's width
if($imgWidth != '') $itemWidth = ';width:'.$imgWidth.'px;';
// Update option range
$options = '';
for($i=10;$i<35;$i=$i+5)
{
if($i==$itemPerPage){
$options = $options . '<option selected>'.$i.'</option>';
}else{
$options = $options . '<option>'.$i.'</option>';
}
}
$numPages = '';
if($isMultiPage){
$itemWidth = $itemWidth.'opacity:0;';
$numPages = '<form class="closify-jpages-form">
<label>items per page: </label>
<select id="closify-select-'.$random_id.'">
'.$options.'
</select>
</form>';
}
$holder = '<div class="closify-holder closify-holder-'.$random_id.'">
</div>';
$htmlStart = '<div id="itemContainer-'.$random_id.'" class="closify-gallery"
itemscope itemtype="http://schema.org/ImageGallery">';
$htmlEnd = '</div>';
$htmlBody = '';
$titleText = "";
$captionText = "";
$titleCopyright = "";
foreach($galleries as $gallery)
{
if($caption && $gallery['img_desc']!='')
$captionText = '<br>Description <small>'.$gallery['img_desc'].'</small>';
else
$captionText = "";
if($title)
$titleText = 'Title <small>'.$gallery['img_title'].'</small>';
$htmlBody = $htmlBody.'<figure class="closify-figure-gallery-item" style="'.$itemWidth.'" itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="'.$gallery['full'][0].'" itemprop="contentUrl" data-size="'.$gallery['full'][1].'x'.$gallery['full'][2].'">
<img class="closify-animated '.$effect.'" src="'.$gallery['thumb'][0].'" itemprop="thumbnail" alt="'.$gallery['img_alt'].'" />
</a>
<figcaption itemprop="caption description">'.$titleText.$captionText.'</figcaption>
</figure>';
}
return $numPages.$holder.$htmlStart.$htmlBody.$htmlEnd;
}
From the server side there will be only one PHP file that should process the images that have been uploaded from the client side, and this single processing file is represented by the "processupload.php" file. This file is responsible of generating proper photos/thumbnails, where the resized photos are sent back to the client side using AJAX to be shown to the user seamlessly.
Referance link :
http://preview.codecanyon.net/item/closify-powerful-flexible-image-uploader/full_screen_preview/8292742
############ Put your custom code here ##############
This means that you can harness this space to add your own logic.
Other specific places to look:
1.
/****************************************************/
/****************************************************/
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
/****************************************************/
/****************************************************/
2.
// Handling position save command
if(isset($_POST["top"]) || isset($_POST["left"]))
{
// When somebody saves a picture you can read "top" and "left" and save them, so it become stored
// play with "left / top" image position
echo "Success";
}
// Handling image delete command
// POST
// command: delete
// id: The ID name of the specific image container that has been deleted
if(isset($_POST["command"]) && isset($_POST["id"]))
{
// When somebody delete a picture, the corresponding action should be put here
echo "Deleted";
}
Related
I'm trying to show random images/video in product category pages. Every category page will display their own set of images.
I did it in the typical rookie way by adding in every product category page with their own respective set of images. Is there a way that I can use hooks to do it at functions.php for ease of maintenance?
var total_images = 7;
var image1 = document.getElementById('banner1');
var image2 = document.getElementById('banner2');
var image3 = document.getElementById('banner3');
var random_numbers = [];
var random_number;
var random_img = [];
random_img[0] = '<img src="banner1.jpeg">';
random_img[1] = '<img src="banner2.jpeg">';
random_img[2] = '<img src="banner3.jpeg">';
random_img[3] = '<img src="banner4.jpeg">';
random_img[4] = '<img src="banner5.jpeg">';
random_img[5] = '<img src="banner6.jpeg">';
random_img[6] = '<img src="banner7.jpeg">';
while(random_numbers.length < 3){
random_number = Math.floor((Math.random() * total_images));
if(random_numbers.indexOf(random_number) < 0){
random_numbers.push(random_number);
}
}
image1.innerHTML = random_img[random_numbers[0]];
image2.innerHTML = random_img[random_numbers[1]];
image3.innerHTML = random_img[random_numbers[2]];
The easy way - Install ACF plugin and create your fields - https://prnt.sc/1yek9zy .
For image field select image url. Duplucate Banner 1 as many banners you want and setup Location rules to taxonomy product category - https://prnt.sc/1yekgys
Then go to a product category and add your images and urls - https://prnt.sc/1yeklpf
If you have ACF pro go with repeater field instead. Its more dynamic and you can add as many banners you want per product category.
Use this visual hook guide to change where you want the banners to be showed - https://www.businessbloomer.com/woocommerce-visual-hook-guide-archiveshopcat-page/
function woo_category_banners() {
$term = get_queried_object();
$banners = get_field('banners', $term->taxonomy . '_' . $term->term_id);
if($banners):
echo '<div class="banners">';
foreach($banners as $k => $banner):
$banner_data = $banners[$k];
echo '<div class="banner"><img src="'.$banner_data['banner_image'].'"></div>';
endforeach;
echo '</div>';
endif;
}
add_action('woocommerce_before_shop_loop','woo_category_banners',40);
I have developed something similar in the past, but not in javascript, it was all php code.
I had added a new banner field in the categories with ACF (only one, you would have many), and then on the category page I would show that banner or, recursively, the father's banner, until I found one.
You would have multiple image fields, and you would extract one at random, maybe it can be useful to you.
In any case, the hook to use is: woocommerce_before_main_content action.
add_action('woocommerce_before_main_content','bannertop');
function bannertop() {recursebanner('banner_top','bannertop');}
function recursebanner($type,$class) {
if ( is_tax( 'product_cat' ) ) {
$term = get_queried_object();
$banner = get_field('banner_top', $term);
if ($banner) {
echo '<div class="'.$class.'">';
echo $banner;
echo '</div>';
} else {
// no banner defined, parse ancestors
$cat_ancestors = get_ancestors( $term->term_id, 'product_cat' );
foreach ($cat_ancestors as $cat_ancestor) {
$termancestor = get_term($cat_ancestor);
$banner = get_field($type, $termancestor);
if ($banner) {
echo '<div class="'.$class.'">';
echo $banner;
echo '</div>';
break;
}
}
}
}
}
If you want to use javascript instead, you have to add it in your js file in the child theme, and call the script for example like this:
$ (function () {
// your code
});
I have about 60 landing pages that use different phone numbers on them. I am using a combination of WordPress and Advanced Custom Fields to place the phone numbers on their respective pages.
I am being asked to show a <div> based on the landing page URL that will not only show the phone number assigned to that page, but, keep showing the <div> (and phone number) regardless of what page the user navigates to on the website.
I have found little to no support on how to make the <div> remain visible throughout the entire session until the user closes the window.
I am thinking that this will somehow revolve around a cookie and Dynamic Number Insertion but I have no real progress to speak of. Should this be done using PHP or JS? Does a plugin exist that would allow for this on WordPress? I'm open to all suggestions.
Please try this code. Like #John C mentioned, WP Engine doesn't recommend Cookie nor PHP Session for the sake of performance and security. This is pure JavaScript code, and I think this will solve your problem.
Code in your Post/Page template file:
<div id="phone-number"></div>
<?php if( get_field('phone_number') ): ?>
<script type="text/javascript">
let phone_number = "<?php the_field('phone_number'); ?>";
</script>
<?php endif; ?>
Code in your theme JavaScript file:
<script type="text/javascript">
// in the case of the div data is persistent on the same site
// let storage = localStorage;
// in the case of the div data is persistent in the same tab, but not in new tab
let storage = sessionStorage;
let key = "phone_number"; // storage key
var global_phone_number = storage.getItem(key);
// check if storage data is set before
if (null === global_phone_number) {
// if not set the data on page into storage
global_phone_number = phone_number ? phone_number : '';
storage.setItem(key, global_phone_number);
}
document.getElementById('phone-number').innerHTML = global_phone_number;
</script>
You should use PHP and capture the session.
(untested code warning)
add_action('wp_footer', 'dynamic_phone_div');
function dynamic_phone_div() {
session_start;
if(isset($_SESSION['phone_div']) ? $phone_div = $_SESSION['phone_div'] :
$phone_div = '';
if($phone_div != '') {
echo '<div class="that_div_thing">';
echo $phone_div;
echo '</div>';
} else {
$_SESSION['phone_div'] = 123456789;
echo '<div class="that_div_thing">';
echo '123456789';
echo '</div>';
}
}
This is only raw logic. I am not sure where your div is (header/footer/page) - depending on where it is you should either use a hook (header/footer) or code it into a template (page/post).
The session will be destroyed after the user closes the tab/window.
I would probably do this with client side session storage. Providing all pages open in the same tab, the value will remain for the session, then be removed.
PHP code (in your functions.php file?) would be something like this:
function phone_script() {
$params = array(
'phone_number' => null, // Insert logic for current number. Can stay null if this is running on a non-landing page
'is_landing_page' => false // Change to true/false based on is current page a landing one or not
);
$params = json_encode( $params );
echo <<< EOT
<script>
let settings = $params;
document.addEventListener("DOMContentLoaded", function() {
if( settings.is_landing_page ) {
window.sessionStorage.setItem( 'phone-number', settings.phone_number );
} else {
settings.phone_number = window.sessionStorage.getItem( 'phone-number' );
}
if( settings.phone_number ) {
let div = document.createElement('div');
div.classList.add('phone-div');
// or add inline style
// div.style.cssText = 'position:fixed'; //etc
// Some logic here to actually add the number and any other content to the div
div.innerHTML = `The Phone number is: ${settings.phone_number}`;
document.body.appendChild(div);
}
});
</script>
EOT;
}
add_action( 'wp_footer', 'phone_script');
Note that the EOT; line MUST have no leading or trailing spaces.
The above is untested.
I have a website where user can upload images, name and description. I am saving it in mysql and fetching that information to show on my website. That's what my below code does, let the user enter those information (image and text) and show it on the website when they click submit button.
My question is how can I make the div (that shows images, name and desc) to editable when user clicks the edit button (so change that same div to textarea or something that is editable) and for images should have an cross mark near the image when clicked on edit button, so user can delete it and upload button to upload more images.
What I have done: I try to use javascript to get the value of div and use that to change it to textarea, but it says the value is undefined for the grid div.
So, how can I make my div editable as explained above, as what I have try so far is not complete, so is there any better way to make the div editable same way I explained above so user can edit text and upload or delete images?
My code:
<?php
require "database.php"; // connecting to database
session_start();
global $username;
$username = $_SESSION['userUsername'].$_SESSION['userId']; //fetching the username
$image = "userPos/$username"; //fetching image posted by specific user
function listFolderFiles($dir, $username){
<!-- The div my_class is getting the images from local storage
that was initially uploaded by user in the website
(and we stored it in the local storage) to display them on the website -->
echo '<div class="my_class">';
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1)
return;
foreach($ffs as $ff){
$s = "'<li>'.$ff";
$saving = "$dir/$ff";
$string = "$saving";
global $string_arr;
$string_arr = (explode("/",$string));
$sav;
$sav = '<li>'.$ff;
global $sa;
$sa = "$ff";
echo '<div class="imagess">';
if(is_file($saving)) {
echo '
<div class="images">
<img src="'.$saving.' " width="100" height="100" alt="Random image" class="img-responsive" />
</div>
' ;
}
echo `</div>`;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff, $username);
}
echo `</div>`;
require "database.php";
<!--Here we are fetching the name and description
that was entered by user on the website
and displaying them on the website now-->
$username = $_SESSION['userUsername'].$_SESSION['userId'];
$sql = "SELECT * FROM `_desc` WHERE `username` = '$username' AND `id` = '$string_arr[2]';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
echo '</br>';
while($row = mysqli_fetch_assoc($result) ) {
//name and desc
echo '<div class="grid">' . '<h2>' . $row["_name"] . '</h2>' . '</div>';
echo '<div class="grid2">' . '<p>' . $row["_desc"] . '</p>' . '</div>';
}
<!--Here I am trying when user click on edit button it should
change that div to editable textarea so user can edit
and save it or delete the whole div-->
echo '<button onClick="editName()" class="btn btn-info">
Edit</button>';
echo '<a href="deleteUserInfo.php?edit= '.
$row["id"].'"class="btn btn-danger ">Delete</a>';
}
echo '</div>';
}
listFolderFiles($image, $username);
?>
<script>
function editName() {
console.log("calling");
var divName = $("grid").html();
console.log(divName); //value is undefined here
var editableName = $("<textarea />");
editableName.val(divName);
$("grid").replaceWith(editableName);
editableName.focus();
editableName.blur(saveName);
}
function saveName() {
var htmlName = $(editableName).html();
var viewableText = $("<div>");
viewableText.html(htmlName);
$(editableName).replaceWith(viewableText);
$(viewableText).click(editName);
}
</script>
</body>
</html>
It is quite simple, you should use contenteditable attribute available and set that value to true. This will make the div element editable.
Like this,
<div class="grid" contenteditable="true">I am editable!</div>
In your case, you should use a function to select the element and set the attribute to true. And for the div element on clicking the type='file' input tag, you can write function that will delete the file that is previously uploaded and upload the new file. I would recommend you to research before posting a question in the community as you might get negative impacts on such questions. Hope it helps! Happy coding!!
When the user clicks the edit button, set the contenteditable attribute to true on the target element and set the focus to that element.
function editName() {
$("grid").attr("contenteditable", true);
$("grid").focus();
$("grid").blur(saveName);
}
I've read multiple examples on infinite scrolling, but I find it hard to implement it to my code. Here's the code, where data get shown from MySQL database :
<div class="container" align="center" style="margin-top:100px;margin-bottom:100px"><div class="row">
<?php
$result = mysql_query("SELECT * FROM batai WHERE svarbumas=1 ORDER BY id DESC");
while ($row = mysql_fetch_array($result))
{
extract($row);
$link=$row["linkas"];
echo "<div class='col-md-4'>";
$sites_html = file_get_contents($link);
$html = new DOMDocument();
#$html->loadHTML($sites_html);
$meta_og_img = null;
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
//If the property attribute of the meta tag is og:image
if($meta->getAttribute('property')=='og:image'){
//Assign the value from content attribute to $meta_og_img
$meta_og_img = $meta->getAttribute('content');
}
}
list($width, $height) = getimagesize($meta_og_img);
$skaicius = abs($width - $height);
if($width > $height) {
echo "<img src=\"$meta_og_img\" style='height:234px;margin-left:-33%' onclick='window.open(\"$link\", \"_blank\");'>";
}
else if($width < $height) {
if($skaicius < 100){
echo "<img src=\"$meta_og_img\" style='width:234px'
onclick='window.open(\"$link\", \"_blank\");'>";
}
else {
echo "<img src=\"$meta_og_img\" style='width:234px;margin-top:-33%'
onclick='window.open(\"$link\", \"_blank\");'>";
}
}
echo "</div>";
}
?>
Stored in the database is a link to, for example, a internet shop page. What the code does is it takes a image for facebook preview from the link stored in the db, which is tagged og:image and then positions it to center. The problem is that page tries to load every image and that takes a ton of time to load the page, thats why I want to somehow make it into a load on scroll page. Btw, Im using Bootstrap's grid system here. I hope you can help me. P.S. If you don't get what I mean because of my bad english, ask me and I'll try to answer it more clearly
I am new to php and ajax. I have this script that is working for me, it does almost what I want it to do. But I am looking to add this piece of code in to have the image show up once a product is fully selected and it has the id.
$dynamic_image .= '
<img style="height:auto; width:auto; max-width:7em; max-height:10em; padding :12px; margin: 9px; border: 3px solid #e3e3e3;" src="design_images/' . $did . '.png" alt="' . $name . '" />';
I also wanted the 'id' to be hidden, or at least not a selection option.
and to have the price and an add to cart button show up once the product is fully selected.
I know this is a lot to ask, but any help would be amazing because I am fully stuck right now. Thank You!
Here is the select_list.php file
<?php
// Multiple select lists - http://coursesweb.net/ajax/
if(!isset($_SESSION)) session_start();
// Here add your own data for connecting to MySQL database
$server = 'localhost';
$user = 'root';
$pass = '';
$dbase = 'mystore';
// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'col_description' if you don`t want to display their data too
$table = 'products';
$ar_cols = array('category', 'subcategory', 'size', 'color', 'id', 'price');
$preid = 'slo_'; // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0]; // the variable used for the column that wil be selected
$re_html = ''; // will store the returned html code
$pre_html = '';
// if there is data sent via POST, with index 'col' and 'wval'
if(isset($_POST['col']) && isset($_POST['wval'])) {
// set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
$col = trim(strip_tags($_POST['col']));
$wval = "'".trim(strip_tags($_POST['wval']))."'";}
$key = array_search($col, $ar_cols); // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1]; // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol; // store in SESSION the column and its value for WHERE
// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : '';
$conn = new mysqli($server, $user, $pass, $dbase); // connect to the MySQL database
if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); } // check connection
// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
$ar_where[] = '`'.$ar_cols[$i-1].'`='.$_SESSION['ar_cols'][$ar_cols[$i-1]];}
// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : '';
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where;
$result = $conn->query($sql); // perform the query and store the result
// if the $result contains at least one row
if ($result->num_rows > 0) {
// sets the "onchange" event, which is added in <select> tag
$onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';
// sets the select tag list (and the first <option>), if it's not the last column
if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>';
while($row = $result->fetch_assoc()) {
// if its the last column, reurns its data, else, adds data in OPTION tags
if($col==$ar_cols[$last_key]) $re_html .= '<br/>$'. $row[$col];
elseif($col==$ar_cols[$last_key]) $pre_html .= '<br/>$'. $row[$col];
else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>'; }
if($col!=$ar_cols[$last_key]) $re_html .= '</select> '; // ends the Select list} else { $re_html = '0 results';}
$conn->close();
// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
// adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
// with ID in each SPAN, according to the columns added in $ar_cols
for($i=1; $i<count($ar_cols); $i++) {
if($ar_cols[$i]===null) continue;
if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
else $re_html .= '<span id="'. $preid.$ar_cols[$i]. '"> </span>'; }
// adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
$re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
}else echo $re_html;
?>
Here is the ajax_select.js file for refeference
// Multiple select lists - http://coursesweb.net/ajax/
// function used to remove the next lists already displayed when it chooses other options
function removeLists(colid) {
var z = 0;
// removes data in elements with the id stored in the "ar_cols" variable
// starting with the element with the id value passed in colid
for(var i=1; i<ar_cols.length; i++) {
if(ar_cols[i]==null) continue;
if(ar_cols[i]==colid) z = 1;
if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = '';
}
}
// sends data to a php file, via POST, and displays the received answer
function ajaxReq(col, wval) {
removeLists(col); // removes the already next selects displayed
// if the value of wval is not '- - -' and '' (the first option)
if(wval!='- - -' && wval!='') {
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // XMLHttpRequest instance
var php_file = 'select_list.php'; // path and name of the php file
// create pairs index=value with data that must be sent to server
var data_send = 'col='+col+'&wval='+wval;
request.open("POST", php_file, true); // set the request
document.getElementById(preid+col).innerHTML = 'Loadding...'; // display a loading notification
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send); // calls the send() method with data_send
// Check request status
// If the response is received completely, will be added into the tag with id value of "col"
request.onreadystatechange = function() {
if (request.readyState==4) {
document.getElementById(preid+col).innerHTML = request.responseText;
}
}
}
}
Any Ideas?
I'm assuming that function ajaxReq is showing the list of products? and on select of an option you want the image to load?
This would depend on where your image url data will show when you get the list from the ajax.
I would add an id to the select element and use jquery to insert the image on click of an option. Let's say you add the image url to the value.
<select id="selectId">
<option value="/img/product.png">Product List</option>
</select>
<div id="productImg">
</div>
<script>
$(function(){
$("#selectId option").click(function(){
$("#productImg").html('<img src="'+$(this).val()+'"/>Product img');
});
});
</script>
Fiddle with it here: https://jsfiddle.net/kqyfw2s2/