Parse error: syntax error, unexpected end of file - php

the server gave me this error but i can't understand why!
The error is
"Parse error: syntax error, unexpected end of file in /homepages/43/d514350324/htdocs/wp-content/plugins/NetClass/nw_NetClass_init_CustomBoxes.php on line 227"
Line 227 is the last line of the file.
That's the code. Help me please!
<?php
/* Define the custom box */
add_action( 'add_meta_boxes', 'aggiungiMetaBox' );
add_action( 'save_post', 'salvaMetaBox', 10, 2 );
add_action( 'wp_ajax_nc_savePortable_lezioni_action', 'nc_savePortable_lezioni' );
add_action( 'admin_footer', 'nc_savePortable_lezioni_js' );
function parseInt($str){
return (int) $str;
}
function aggiungiMetaBox(){
add_meta_box( "nw_Netclass_Box_AggiungiaCorso", "Aggiungi la lezione al corso", "aggiungiMetaBox_AggiungiLezione", "corso");
add_meta_box("nw_NetClass_Box_DatiFattura", "Dati della fattura", "aggiungiMetaBox_DatiFattura", "fattura");
add_meta_box("nw_NetClass_Box_Corsi_Associati", "Corsi associati", "aggiungiMetaBox_Corsi_Associati", "lezione");
}
function aggiungiMetaBox_Corsi_Associati($post){
?>
<p><?php echo get_post_meta($post->ID, 'corsi_associati',true); ?></p>
<?php
}
function is_in_array($array_lezioni_del_corso, $object){
if(!is_array($array_lezioni_del_corso)){
if($array_lezioni_del_corso == $object){
return true;
}else{
return false;
}
}
else{
return in_array($object, $array_lezioni_del_corso);
}
}
function aggiungiMetaBox_DatiFattura($post){
$post_id = $post->ID;
$user_info = get_userdata(get_post_meta($post_id, "intestatarioFattura" , true));
$user_meta = array(
'tipo_utente' => get_user_meta(get_post_meta($post_id, "intestatarioFattura" , true), 'tipo_utente',true),
'p_iva' => get_user_meta(get_post_meta($post_id, "intestatarioFattura" , true), 'p_iva',true),
'indirizzo_fatturazione' => get_user_meta(get_post_meta($post_id, "intestatarioFattura" , true), 'indirizzo_fatturazione',true)
);
?>
Intestatario della fattura : <?php echo $user_info->display_name; ?> <br>
Tipo di utente : <?php echo $user_meta['tipo_utente']; ?> <br>
Indirizzo di fatturazione : <?php echo $user_meta['indirizzo_fatturazione']; ?> <br>
P.IVA : <?php echo $user_meta['p_iva']; ?> <br>
Inponibile della fattura : <?php echo get_post_meta( $post_id, "inponibileFattura" , true); ?> <br>
Totale della fattura : <?php echo get_post_meta( $post_id, "totaleFattura" , true); ?> <br>
Articoli acquistati:
<ul>
<?php
foreach(get_post_meta( $post_id, "articoliFattura" , true) as $prodotto){
?>
<li><?php echo get_the_title($prodotto); ?></li>
<?php
}
?>
</ul>
<?php
}
//save the meta box
function salvaMetaBox($post_id)
{
//Salvo i dati del Box lezioni nel post corso //
global $wpdb;
$database_name = $wpdb->prefix.'Netclass_friends';
if ( (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || ( defined('DOING_AJAX') && DOING_AJAX) || isset($_REQUEST['bulk_edit']) ) { return $post_id; }
//Salvo i dati delle fatture
}
function aggiungiMetaBox_AggiungiLezione($post){
global $wpdb;
$post_id = $post->ID;
$query = "SELECT post_title,ID FROM ".$wpdb->prefix."posts WHERE post_type='lezione' AND post_status='publish'";
$array_lezioni_del_corso = get_post_meta($post_id, 'array_lezioni_del_corso');
$lezioni = $wpdb->get_results($query);
foreach ($lezioni as $lezione) { ?>
<input id="<?php echo $lezione->ID; ?>" data-title="<?php echo $lezione->post_title; ?>" class="nc_lezione_pubblicata" type="checkbox" name="checkfield[]" value="<?php echo $lezione->ID; ?>" <?php if ( is_in_array($array_lezioni_del_corso[0], $lezione->ID)) { ?> checked <?php } ?>/>
<label for="<?php echo $lezione->ID; ?>"><?php echo $lezione->post_title; ?></label> <br>
<?php } ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function($)
{
$( '.sortable' ).sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.hndle',
placeholder: {
element: function(currentItem) {
return $("<li style='background:#E7E8AD'> </li>")[0];
},
update: function(container, p) {
return;
}
},
update: function( event, ui ) {
console.log($(".sortable").sortable("toArray", {attribute: 'data-id'}));
saveSortable($(".sortable").sortable("toArray", {attribute: 'data-id'}));
}
});
$( '.sortable' ).disableSelection();
$(".nc_lezione_pubblicata").change(function() {
if( $(this).is(':checked') ){
$( '<li class="nc_lezione_del_corso" data-id="'+$(this).attr('id')+'" id="lezione_del_corso_'+$(this).attr('id')+'"><code class="hndle"> -[]- </code>'+$(this).data('title')+'</p>' ).appendTo( ".sortable" );
}else{
$("#lezione_del_corso_"+$(this).attr('id')).remove();
console.log("elimino");
}
saveSortable($(".sortable").sortable("toArray", {attribute: 'data-id'}));
});
});
</script>
<ul class="sortable ui-sortable">
<?php foreach ($array_lezioni_del_corso[0] as $lezione_del_corso) { ?>
<li class="nc_lezione_del_corso" id="lezione_del_corso_<?php echo $lezione_del_corso; ?>"
data-id="<?php echo $lezione_del_corso; ?>">
<code class='hndle'> -[]- </code>
<?php echo get_the_title($lezione_del_corso); ?>
</li>
} ?>
</ul>
<p>
<script type="text/javascript">
$(function(){
console.log($(".sortable").sortable("toArray"));
});</script>
</p>
<?php }
function nc_savePortable_lezioni(){
global $wpdb;
$post_id = $_POST['post_id'];
$array_lezioni_del_corso = $_POST['array_lezioni_del_corso'];
update_post_meta($post_id, 'array_lezioni_del_corso', $array_lezioni_del_corso);
foreach ($array_lezioni_del_corso as $lezione_del_corso) {
$corsi_associati = get_post_meta($lezione_del_corso, 'corsi_associati', true);
$corsi_associati = $corsi_associati.','.$post_id;
update_post_meta(parseInt($lezione_del_corso), 'corsi_associati', $corsi_associati);
}
echo 'al server arrriva '.$array_lezioni_del_corso;
}
function nc_savePortable_lezioni_js(){
?>
<script type="text/javascript">
function saveSortable(sortableArraystringData){
var data = {
action: 'nc_savePortable_lezioni_action',
array_lezioni_del_corso : sortableArraystringData,
post_id : <? echo get_the_ID(); ?>
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('This was passed ' + sortableArraystringData);
});
}
</script>
<?php
}

You're missing a curly brace somewhere.

Related

Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?

i iclude a wordpress media selector in my wordpress plugin.
i got this error :
Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
error
i added to this code to wp-config.php file :
`
/** WordPress değişkenlerini ve yollarını kurar. */
require_once ABSPATH . 'wp-settings.php';
define( 'UPLOADS', 'wp-content/uploads' );
`
and added to myportfolio-form.php file
<?php
add_action( 'admin_footer', 'media_selector_print_scripts' );
function media_selector_print_scripts() {
$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );
?><script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>; // Set this
jQuery('#upload_image_button').on('click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
$( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );
$( '#image_attachment_id' ).val( attachment.id );
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery( 'a.add_media' ).on( 'click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script><?php
}
function portfolio_admin_myprojects_page_handler()
{
global $wpdb;
$table = new Portfolio_MyProjects_List_Table();
$table->prepare_items();
$message = '';
if ('delete' === $table->current_action()) {
$message = '<div class="updated below-h2" id="message"><p>' . sprintf(__('Items deleted: %d', 'portfolio-admin-myresume'), count($_REQUEST['ID'])) . '</p></div>';
}
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects_form');?>"><?php _e('Add new', 'portfolio-admin-myresume')?></a>
</h2>
<?php echo $message; ?>
<form id="myprojects-table" method="POST">
<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
<?php $table->display() ?>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_page_handler()
{
global $wpdb;
$table_name = $wpdb->prefix . 'portfolio_myprojects';
$message = '';
$notice = '';
$default = array(
'ID' => 0,
'projects_name' => '',
'projects_category' => '',
'projects_link' => '',
'projects_image' => '',
'order' => '',
);
if ( isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
$item = shortcode_atts($default, $_REQUEST);
$item_valid = portfolio_admin_validate_myprojects($item);
if ($item_valid === true) {
if ($item['ID'] == 0) {
$result = $wpdb->insert($table_name, $item);
$item['ID'] = $wpdb->insert_id;
if ($result) {
$message = __('Item was successfully saved', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while saving item', 'portfolio-admin-myresume');
}
} else {
$result = $wpdb->update($table_name, $item, array('ID' => $item['ID']));
if ($result) {
$message = __('Item was successfully updated', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while updating item', 'portfolio-admin-myresume');
}
}
} else {
$notice = $item_valid;
}
}
else {
$item = $default;
if (isset($_REQUEST['ID'])) {
$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $_REQUEST['ID']), ARRAY_A);
if (!$item) {
$item = $default;
$notice = __('Item not found', 'portfolio-admin-myresume');
}
}
}
add_meta_box('myprojects_form_meta_box', __('Work Details', 'portfolio-admin-myresume'), 'portfolio_admin_projects_form_meta_box_handler', 'myprojects', 'normal', 'default');
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects');?>"><?php _e('back to list', 'portfolio-admin-myresume')?></a>
</h2>
<?php if (!empty($notice)): ?>
<div id="notice" class="error"><p><?php echo $notice ?></p></div>
<?php endif;?>
<?php if (!empty($message)): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif;?>
<form id="form" method="POST">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<input type="hidden" name="ID" value="<?php echo $item['ID'] ?>"/>
<div class="metabox-holder" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<?php do_meta_boxes('myprojects', 'normal', $item); ?>
<input type="submit" value="<?php _e('Save', 'portfolio-admin-myresume')?>" id="submit" class="button-primary" name="submit">
</div>
</div>
</div>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_meta_box_handler($item)
{
// Save attachment ID
if ( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :
update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );
endif;
wp_enqueue_media();
?>
<tbody >
<div class="formdatabc">
<form >
<div class="form2bc">
<p>
<label for="projects_name"><?php _e('Project Name:', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_name" name="projects_name" type="text" value="<?php echo esc_attr($item['projects_name'])?>"
required>
</p>
</div>
<div class="form2bc">
<p>
<label for="projects_category"><?php _e('Project Category', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_category" name="skills_percent" type="text" value="<?php echo esc_attr($item['projects_category'])?>"
required>
</p>
</div>
<div class="form3bc">
</div>
<div>
<p>
<label for="projects_link"><?php _e('Project Link:', 'portfolio-admin-myresume')?></label>
<br>
<textarea id="projects_link" name="projects_link" cols="100" rows="3" maxlength="240"><?php echo esc_attr($item['projects_link'])?></textarea>
</p>
</div>
<div class='image-preview-wrapper'>
<img id='image-preview' src='' width='100' height='100' style='max-height: 100px; width: 100px;'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value=''>
</form>
</div>
</tbody>
<?php
}
`
i tried to iclude wordpress media selector to my plugin but it doesnt work.
error : Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
You need to change permissions of directories on server itself
chmod -R 777 /path/to/web-root/wp-content/uploads
(Linux example, this will change all files)
chmod 777 /path/to/web-root/wp-content
(this will change only directory itself, not all files)

Need help inserting a php variable into a URL string

Here is my php file:
<div id="map_wrap">
<div id="map"></div>
</div><!-- #map_wrap -->
<?php
$states_list = get_state_list();
$states_to_disable = get_field( 'states_to_disable' );
?>
<ul class="state-list">
<?php
foreach( $states_list as $key => $value ){
$anchor = $key;
$class = '';
foreach( $states_to_disable as $state ){
if( $state['value'] === $key ){
$class = 'disabled';
$anchor = 'no-service';
}
}
$anchor = str_replace("_","-",$anchor);
?>
<li><a class="<?= $class; ?>" href="<?php echo site_url(); ?>/<?= $anchor; ?>-quick-online-installment-loans"><?= $value; ?></a></li>
<?php
}
?>
</ul>
<?php
?>
<script src='<?php echo get_stylesheet_directory_uri(); ?>/js/raphael-min.js'></script>
<script src='<?php echo get_stylesheet_directory_uri(); ?>/js/usmap.js'></script>
<script>
$(document).ready(function() {
var clickGo = true;
$('#map').usmap({
stateStyles: {fill: '#009a4d','stroke': '#ffffff'},
stateSpecificStyles: {
<?php
foreach( $states_to_disable as $state ){
echo $state['value'] . ": {fill: '#C5C5C5'},";
}
?>
},
stateSpecificLabelBackingHoverStyles: {
<?php
foreach( $states_to_disable as $state ){
echo $state['value'] . ": {fill: '#888'},";
}
?>
},
clickState: {
<?php
foreach( $states_to_disable as $state ){
?>
'<?= $state['value']; ?>' : function(event, data) {
var state_name = data.name;
console.log('1');
clickGo = false;
state_name = state_name.replace("_","-")+'';
location.href = "<?php echo site_url(); ?>/state-terms-and-rates/no-service";
},
<?php
}
?>
},
click: function(event, data) {
var state_name = data.name;
console.log('2');
state_name = state_name.replace("_","-")+'';
if( clickGo === true ){
location.href = "<?php echo site_url(); ?>/state-terms-and-rates/"+state_name;
}
},
});
});
</script>
As you can see, in the very last section of code, any active states in the map that are clicked on, go to /state-terms-and-rates/+state_name. However, I need it to go to /+state_name-quick-online-installment-loans.
I can get it very close but the URL either shows a blank state name, the word array, a zero, or a plus sign depending on the different things I've been trying.
Can anybody give me the right direction to go in?

How to add next and previous buttons on ad (item) view on dj-classifieds (Joomla)?

I tried many codes to do the thing, but it's not working.
The Image code is in the line 21. This is a copy of the code where I have to add the next and previous buttons:
<?php
defined ('_JEXEC') or die('Restricted access');
$par = JComponentHelper::getParams( 'com_djclassifieds' );
$app = JFactory::getApplication();
$item = $this->item;
$main_img_width = $par->get('gallery_width','200')-4;
$thumbs_limit = $par->get('gallery_thumbs_in_row','3');
$thumb_width = round(($par->get('gallery_width','200')/$thumbs_limit)-14);
$djMediaTools = ($par->get('djmediatools_integration', 0) == '1' && $par->get('djmediatools_album_item', 0) > 0) ? $par->get('djmediatools_album_item', 0) : false;
$djMediaToolsMinimum = (int)$par->get('djmediatools_minimum', 1);
JHtml::_('jquery.framework');
?>
<div class="images_wrap" style="width:<?php echo $par->get('gallery_width','200');?>px"><div class="images">
<?php if ($djMediaTools > 0 && count($this->item_images) >= $djMediaToolsMinimum) {?>
<div class="djc_images">
<?php echo JHtml::_('content.prepare', '{djmedia '.(int)$djMediaTools.'}', $par, 'com_djclassifieds.item.djmediatools'); ?>
</div>
<?php } else { ?>
<div class="djc_images">
<div class="djc_mainimage">
<?php if(count($this->item_images)){ ?>
<a id="djc_mainimagelink" rel="djc_lb_0" title="<?php echo $item->name; ?>" href="<?php echo JURI::base(true).$this->item_images[0]->thumb_b; ?>">
<img id="djc_mainimage" alt="<?php echo $item->name; ?>" src="<?php echo JURI::base(true).$this->item_images[0]->thumb_b;?>" />
</a>
<?php }else{?>
<?php if($par->get('blank_img_source','0')==1){ ?>
<img id="djc_mainimage" class="djc_mainimage_no_image" style="width:<?php echo $par->get('gallery_width','200');?>px" alt="<?php echo $item->name; ?>" src="<?php echo DJClassifiedsImage::getCatImage($item->cat_id);?>" />
<?php }else{ ?>
<img id="djc_mainimage" class="djc_mainimage_no_image" style="width:<?php echo $par->get('gallery_width','200');?>px" alt="<?php echo $item->name; ?>" src="<?php echo JURI::base(true).$par->get('blank_img_path','/components/com_djclassifieds/assets/images/').'no-image-big.png';?>" />
<?php } ?>
<?php }?>
</div>
<?php
if (count($this->item_images) > 1) { ?>
<div class="djc_thumbnails djc_thumbs_gal<?php echo $thumbs_limit;?> " id="djc_thumbnails">
<?php foreach($this->item_images as $im=>$img){
if($im>0 && $im%$thumbs_limit==0){
$new_row_class = ' new_row';
}else{
$new_row_class = '';
}
?>
<div class="djc_thumbnail djc_thumb_row<?php echo $new_row_class;?>">
<a rel="<?php echo JURI::base(true).$img->thumb_b;?>" title="<?php echo $img->caption; ?>" href="<?php echo JURI::base(true).$img->thumb_b;?>">
<img alt="<?php echo $img->caption; ?>" src="<?php echo JURI::base(true).$img->thumb_s;?>" />
</a>
</div>
<?php } ?>
<div class="clear_both"></div>
</div>
<?php } ?>
<?php for($ii=0; $ii<count($this->item_images);$ii++ ){ ?>
<a id="djc_lb_<?php echo $ii; ?>" class="lightbox-djitem" rel="lightbox-djitem" title="<?php echo $this->item_images[$ii]->caption;?>" href="<?php echo JURI::base(true).$this->item_images[$ii]->thumb_b;?>" style="display: none;"></a>
<?php } ?>
</div>
<?php } ?>
</div></div>
<script type="text/javascript">
this.DJCFImageSwitcher = function (){
var mainimagelink = document.id('djc_mainimagelink');
var mainimage = document.id('djc_mainimage');
var thumbs = document.id('djc_thumbnails') ? document.id('djc_thumbnails').getElements('img') : null;
var thumblinks = document.id('djc_thumbnails') ? document.id('djc_thumbnails').getElements('a') : null;
<?php if($par->get('lightbox_type','slimbox')!='magnific'){ ?>
if(mainimagelink && mainimage) {
mainimagelink.removeEvents('click').addEvent('click', function(evt) {
var rel = mainimagelink.rel;
document.id(rel).fireEvent('click', document.id(rel));
//if(!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
return false;
//}
//return true;
});
}
<?php } ?>
if (!mainimage || !mainimagelink || !thumblinks || !thumbs) return false;
thumblinks.each(function(thumblink,index){
var fx = new Fx.Tween(mainimage, {link: 'cancel', duration: 200});
thumblink.addEvent('click',function(event){
event.preventDefault();
//new Event(element).stop();
/*
mainimage.onload = function() {
fx.start('opacity',0,1);
};
*/
var img = new Image();
img.onload = function() {
fx.start('opacity',0,1);
};
fx.start('opacity',1,0).chain(function(){
mainimagelink.href = thumblink.href;
mainimagelink.title = thumblink.title;
mainimagelink.rel = 'djc_lb_'+index;
img.src = thumblink.rel;
mainimage.src = img.src;
mainimage.alt = thumblink.title;
});
return false;
});
});
};
window.addEvent('load', function(){
var img_width = document.id('dj-classifieds').getElement('.djc_images').getSize().x;
var dj_item = document.id('dj-classifieds').getElement('.djcf_images_generaldet_box').getSize().x;
var general_det = dj_item-img_width-1;
if(general_det<150){
document.id('dj-classifieds').getElement('.general_det').addClass('general_det_s');
}
if(general_det<301){
document.id('dj-classifieds').getElement('.general_det').addClass('general_det_m');
}
document.id('dj-classifieds').getElement('.general_det').setStyle('width',general_det) ;
});
window.addEvent('domready', function(){
DJCFImageSwitcher();
});
</script>
<?php if($par->get('lightbox_type','slimbox')=='magnific'){ ?>
<script type="text/javascript">
!function($){
$(document).ready(function(){
$('#djc_mainimagelink').click(function(e) {
e.preventDefault();
var rel = $(this).attr('rel');
console.log(rel);
$('#'+rel).click();
//console.log(e);
//do other stuff when a click happens
});
$('.lightbox-djitem').magnificPopup({
//$(this).magnificPopup({
// delegate: '.dj-slide-link', // the selector for gallery item
type: 'image',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true
},
image: {
verticalFit: true,
titleSrc: 'title'
},
iframe: {
patterns: {
youtube: null,
vimeo: null,
link: {
index: '/',
src: '%id%'
}
}
}
// });
});
});
}(jQuery);
</script>
<?php } ?>

Zoom Image Woocommerce - Wordpress

Im using wordpress 3.8, woocommerce 2.0.20. And im using this Zoom Image Plugin(http://wordpress.org/plugins/zoom-image/)
Everything is looking fine, but when I have a product with color variation, it does not change the color of the image, but when you put your mouse to zoom, it appears the previous image.
Zoom Image Plugin code:
class TccZoom {
var $pluginPath;
var $pluginUrl;
public function __construct()
{
// Set Plugin Path
$this->pluginPath = dirname(__FILE__);
// Set Plugin URL
$this->pluginUrl = WP_PLUGIN_URL . '/zoom-image';
add_filter('woocommerce_product_thumbnails', array( &$this, 'apply_zoom') );
add_action('woocommerce_product_thumbnails', array( &$this, 'add_scripts') );
if(is_admin()){
add_action('admin_menu', array(&$this, 'add_zoom_image_plugin_page'));
add_action('admin_init', array(&$this, 'zoom_image_init'));
add_action( 'admin_enqueue_scripts', array(&$this, 'wp_enqueue_color_picker') );
}
}
static function install() {
add_option('zoom_image_options', array('zoom_thumbnails'=>'1'));
}
function wp_enqueue_color_picker( ) {
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script( 'wp-color-picker-script', plugins_url('/js/colorPicker.js', __FILE__ ), array( 'wp-color-picker' ), false, true );
}
public function add_zoom_image_plugin_page(){
// This page will be under "Settings"
add_options_page('Zoom Image Settings', 'Zoom Image', 'manage_options', 'zoom-image', array($this, 'create_zoom_image_page'));
}
public function create_zoom_image_page(){
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2>Zoom Image Settings</h2>
<form method="post" action="options.php">
<?php
// This prints out all hidden setting fields
settings_fields('zoom_image_group');
do_settings_sections('zoom_image_settings');
?>
<?php submit_button(); ?>
</form>
</div>
<?php
}
public function zoom_image_init(){
register_setting('zoom_image_group', 'zoom_image_options', array($this, 'check_zoom_image_options'));
add_settings_section(
'general_zoom_settings',
'Zoom image options',
array($this, 'print_section_info'),
'zoom_image_settings'
);
add_settings_field(
'zoom_thumbnails',
'Zoom over thumbnails ?',
array($this, 'create_zoom_thumbnails_field'),
'zoom_image_settings',
'general_zoom_settings'
);
/*
add_settings_field(
'zoom_level',
'Zoom level',
array($this, 'create_zoom_level_field'),
'zoom_image_settings',
'general_zoom_settings'
);
*/
add_settings_field(
'zoom_type',
'Zoom type',
array($this, 'create_zoom_inner_field'),
'zoom_image_settings',
'general_zoom_settings'
);
/*
add_settings_field(
'zoom_background_color',
'Background color',
array($this, 'create_zoom_color_field'),
'zoom_image_settings',
'general_zoom_settings'
);
*/
}
public function check_zoom_image_options($input){
if(!in_array($input['zoom_thumbnails'],array(0,1)))
{
$input['zoom_thumbnails'] = '';
}
if(!in_array($input['zoom_level'],array(0.5,1,2)))
{
$input['zoom_level'] = '';
}
if(!in_array($input['zoom_type'],array('window','inner','lens')))
{
$input['zoom_type'] = '';
}
return $input;
}
public function print_section_info(){
//print 'Enter your setting below:';
}
public function create_zoom_thumbnails_field(){
$options = get_option('zoom_image_options');
?>
<input type="checkbox" id="zoom_over_thumbnails" name="zoom_image_options[zoom_thumbnails]" value="1" <?php if($options['zoom_thumbnails']==1) { ?> checked="checked" <?php } ?> />
<?php
}
public function create_zoom_inner_field(){
$options = get_option('zoom_image_options');
?>
<select name="zoom_image_options[zoom_type]">
<option value="window" <?php if($options['zoom_type']=='window') { ?> selected="selected" <?php } ?>>Window</option>
<option value="lens" <?php if($options['zoom_type']=='lens') { ?> selected="selected" <?php } ?>>Lens</option>
<option value="inner" <?php if($options['zoom_type']=='inner') { ?> selected="selected" <?php } ?>>Inner</option>
</select>
<?php
}
public function create_zoom_level_field()
{
$options = get_option('zoom_image_options');
?>
<select name="zoom_image_options[zoom_level]">
<option value="1" <?php if($options['zoom_level']==1) { ?> selected="selected" <?php } ?>>Normal zoom</option>
<?php /*
<option value="0.5" <?php if($options['zoom_level']==0.5) { ?> selected="selected" <?php } ?>>Twice as big</option>
*/ ?>
<option value="2" <?php if($options['zoom_level']==2) { ?> selected="selected" <?php } ?>>Twice as small</option>
</select>
<?php
}
public function create_zoom_color_field()
{
$options = get_option('zoom_image_options');
?>
<input type="text" id="zoom_background" class="wp-color-picker-field" name="zoom_image_options[zoom_background_color]" value="<?php echo esc_attr($options['zoom_background_color']); ?>" />
<br />
<span>Available only for Zoom type: window</span>
<?php
}
function apply_zoom()
{
global $post;
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full', false, '' );
$options = get_option('zoom_image_options');
ob_start();
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$('.woocommerce-main-image img').attr('data-zoom-image','<?php echo $src[0]; ?>');
$('.woocommerce-main-image img').elevateZoom({
<?php if($options['zoom_level']) { ?>
zoomLevel : <?php echo strip_tags(trim($options['zoom_level'])); ?>,
<?php }else { ?>
zoomLevel : 1,
<?php } ?>
<?php
switch ($options['zoom_type'])
{
case "window":
?>
zoomType : "window",
lensShape : "square",
<?php
break;
case "lens":
?>
zoomType : "lens",
lensShape : "round",
<?php
break;
case "inner":
?>
zoomType : "inner",
cursor : "crosshair",
<?php
break;
default:
?>
zoomType : "window",
lensShape : "square",
<?php
break;
}
if(strlen(trim($options['zoom_background_color']))>1 && $options['zoom_type']=='window' ) {
?>
tint:true,
tintColour:'<?php echo esc_attr($options['zoom_background_color']); ?>',
tintOpacity:0.5
<?php
}
?>
});
<?php if($options['zoom_thumbnails']==1) { ?>
$('.thumbnails .zoom img').each(function(){
$(this).attr('data-zoom-image',$(this).parent().attr('href'));
});
$('.thumbnails .zoom img').elevateZoom({
zoomType : "window",
lensShape : "square",
lensSize : 20,
zoomWindowPosition: 16,
zoomWindowOffetx: 10,
<?php if($options['zoom_level']) { ?>
zoomLevel : <?php echo strip_tags(trim($options['zoom_level'])); ?>,
<?php }else { ?>
zoomLevel : 1,
<?php } ?>
<?php
if(strlen(trim($options['zoom_background_color']))>1) {
?>
tint:true,
tintColour:'<?php echo esc_attr($options['zoom_background_color']); ?>',
tintOpacity:0.5
<?php
}
?>
});
<?php } ?>
})
</script>
<?php
echo ob_get_clean();
}
function add_scripts() {
wp_enqueue_script( 'tcc-magnifier-js', $this->pluginUrl.'/js/jquery.elevateZoom-2.5.5.min.js', 'jquery' );
}
}
$tcczoom = new TccZoom;
register_activation_hook( __FILE__, array('TccZoom', 'install') );
We use something very similar, CloudZoom for WooCommerce, which has the same problem as well. If you are interested in switching plugins, you can solve the same problem for that plugin by adding this line of jQuery to a script in your header:
jQuery('form.variations_form').on( 'found_variation', function( event, variation ) {
addCloudZoom($productImages);
} );
Again, just to be clear, this solution won't work for the plugin you are using, but it solves the same problem for a plugin that provides identical functionality. If you can't find a solution for the plugin you're using, you might try switching and using this solution.

Magento ajax add to cart product not found error

The magento 1.8 ajax cart is showing product not found error
The java script I used is
function setLocationAjax(url,id){
var data = jQuery('#product_addtocart_form').serialize();
data += '&isAjax=1';
url = url.replace("checkout/cart","ajax/index");
jQuery('#ajax_loader'+id).show();
try {
jQuery.ajax( {
url : url,
dataType : 'json',
type : 'post',
data: data,
success : function(data) {
jQuery('#ajax_loader'+id).hide();
setAjaxData(data,false);
}
});
} catch (e) {
}
}
function setAjaxData(data,iframe){
if(data.status == 'ERROR'){
alert(data.message);
}else{
if(jQuery('.block-cart')){
jQuery('.block-cart').replaceWith(data.sidebar);
}
// if(jQuery('.header .links')){
// jQuery('.header .links').replaceWith(data.toplink);
// }
if(jQuery('.cart-top-container')){
//jQuery('.cart-top-container').empty();
jQuery('.cart-top-container').replaceWith(data.toplink);
}
var targetUrl='<?php echo Mage::getUrl('onestepcheckout') ?>';
jQuery( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Checkout": function() {
window.location.href = targetUrl;
jQuery(this).dialog( "close" );
},
"Continue Shopping": function() {
jQuery(this).dialog( "close" );
}
}
});
}
}
The product is failing to get the product information required to add to cart. Is there any way to add the product to cart other than this code?
*The form is *
<form action="<?php echo $this->getSubmitUrl($p) ?>" method="post" id="product_addtocart_form"<?php if ($p->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<div class="home-prouduct-details">
<?php $pid = $p->getId(); ?>
<?php $prod = Mage::getModel('catalog/product')->load($pid); ?>
<?php $html= $prod->getShortDescription(); ?>
<?php
$str = $html;
$matches = array();
preg_match_all('#<div[^>]*>(.*?)</div>#', $str, $matches);
// print_r($matches[1][0]);
?>
<a class="prod-name" href="<?php echo $prod->getProductUrl(); ?>"><?php echo $prod->getName(); ?></a>
<div class="prod-img">
<a href="<?php echo $prod->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($prod, 'small_image'), null, true) ?>" class="product-image">
<img src="<?php echo $this->helper('catalog/image')->init($prod, 'small_image')->resize(285,172); ?>" width="285" height="175" alt="<?php echo $this->stripTags($this->getImageLabel($prod, 'small_image'), null, true) ?>" />
</a>
</div>
<div class="home-price-button">
<?php $almost_gone_qty=$this->htmlEscape($prod->getData('almost_gone_qty')); ?>
<?php $qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($prod)->getQty(); ?>
<?php if (!$this->hasOptions() && strtotime($prod->getDealEndDate())>= Mage::getModel('core/date')->timestamp(time())):?>
<div style="clear:both;"></div>
<div class="add-to-box">
<?php if($prod->isSaleable() && $qtyStock > $almost_gone_qty){ ?>
<p class="availability out-of-stock">
<a onclick="setLocationAjax('/checkout/cart/add/product/<?php echo $prod; ?>',<?php echo $prod->getId();?>)" title="Add To Cart">
<img src="<?php echo $this->getSkinUrl('images/steamy.png'); ?>" title="Add To Cart" alt="Add To Cart" width="285" />
</a>
</p>
<?php } else if($qtyStock <= $almost_gone_qty && $qtyStock!=0){?>
<p class="availability out-of-stock">
<a onclick="setLocationAjax('/checkout/cart/add/product/?<?php echo $prod; ?>',<?php echo $prod->getId();?>)" title="Almost Gone">
<img src="<?php echo $this->getSkinUrl('images/almostgone.png'); ?>" title="Almost Gone" alt="Almost Gone" width="285" />
</a>
</p>
<?php } else{ ?>
<p class="availability out-of-stock">
<a href="<?php echo Mage::getBaseUrl(); ?>sold-out" title="Sold Out">
<img src="<?php echo $this->getSkinUrl('images/soldout.png'); ?>" width="285" /><?php //echo $this->__('Out of stock') ?>
</a>
</p>
<?php } ?>
<span id='ajax_loader<?php echo $prod->getId()?>' style='text-align: center; display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
</div>
<?php else : ?>
<p class="deal-has-ended">
<a href="<?php echo Mage::getBaseUrl(); ?>sold-out" title="Sold Out">
<img src="<?php echo $this->getSkinUrl('images/deal_ended.png'); ?>" width="285" />
</a>
</p>
<?php endif; ?>
<?php //echo $this->getChildHtml('addto') ?>
<?php //echo $this->getChildHtml('extra_buttons') ?>
</div>
<div class="home-price">
<div class="home-prices">
<?php
echo Mage::helper('core')->currency($prod->getPrice());
?>
</div>
<?php if($matches[1][1] !=""){ ?>
<div class="home-save">
<?php
$savings = $matches[1][1];
$savings = str_ireplace('Rs.', '₹', $savings);
$savings = str_ireplace('Rs', '₹', $savings);
echo $savings;
?>
<?php //print_r($matches[1][1]); ?>
<div class="home-saver">
savings
</div>
</div>
<?php } ?>
<div class="deal-endtime">
<?php
echo "<div id='cdcontainer_".$prod->getId()."' class='cdcontainer'></div>";
$dealEndDate = $prod->getDealEndDate();
$dealEndDateParts = explode(" ", $dealEndDate);
$targetDateParts = explode("-", $dealEndDateParts[0]);
$year = $targetDateParts[0];
$month = $targetDateParts[1];
$date = $targetDateParts[2];
$month_array = array(
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
);
$month = $month_array[$month-1];
$targetDate = "$month $date, $year ".$dealEndDateParts[1];
$timer_text = Mage::getStoreConfig('homedeals/basic_settings/cd_display_text');
$timer_end_text = Mage::getStoreConfig('homedeals/basic_settings/cd_end_text');
//echo $timer_end_text;
//echo date("Y-m-d H:i:s"); echo "<br/>";
//echo $dealEndDate;
if($dealEndDate <= date("Y-m-d H:i:s")){
?>
<script type="text/javascript">
var launchdate_<?php echo $prod->getId(); ?>=new cdLocalTime("cdcontainer_<?php echo $_product->getId(); ?>", "server-php", 0, "", "", "<?php echo '<span><h1 style=color:red;>Deal has ended - 00:00:00</h1></span>' ?><?php //echo $timer_text; ?>", "<?php echo $timer_end_text; ?>", "<?php echo $prod->getId(); ?>");
launchdate_<?php echo $prod->getId(); ?>.displaycountdown("hours", formatresults2);
</script>
<?php }else { ?>
<script type="text/javascript">
var launchdate_<?php echo $prod->getId(); ?>=new cdLocalTime("cdcontainer_<?php echo $prod->getId(); ?>", "server-php", 0, "<?php echo $targetDate?>", "<?php print date("F d, Y H:i:s", Mage::getModel('core/date')->timestamp(time()))?>", "<?php echo $timer_text; ?>", "<?php echo $timer_end_text; ?>", "<?php echo $prod->getId(); ?>");
launchdate_<?php echo $prod->getId(); ?>.displaycountdown("hours", formatresults2);
</script>
<?php } ?>
</div>
</div>
</div>
<div id="dialog-confirm" style="display:none;">
<?php echo $prod->getName();?> added to your cart Successfully.
</div>
</form>
There is also an URL issue I guess Thanks in advance.
my controller code is
protected function _getProduct($productInfo)
{
$product = null;
if ($productInfo instanceof Mage_Catalog_Model_Product) {
$product = $productInfo;
} elseif (is_int($productInfo) || is_string($productInfo)) {
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($productInfo);
}
$currentWebsiteId = Mage::app()->getStore()->getWebsiteId();
if (!$product
|| !$product->getId()
|| !is_array($product->getWebsiteIds())
|| !in_array($currentWebsiteId, $product->getWebsiteIds())
) {
Mage::throwException(Mage::helper('checkout')->__('The product could not be found.'));
}
return $product;
}
/**
* Get request for product add to cart procedure
*
* #param mixed $requestInfo
* #return Varien_Object
*/
protected function _getProductRequest($requestInfo)
{
if ($requestInfo instanceof Varien_Object) {
$request = $requestInfo;
} elseif (is_numeric($requestInfo)) {
$request = new Varien_Object(array('qty' => $requestInfo));
} else {
$request = new Varien_Object($requestInfo);
}
if (!$request->hasQty()) {
$request->setQty(1);
}
return $request;
}
/**
* Add product to shopping cart (quote)
*
* #param int|Mage_Catalog_Model_Product $productInfo
* #param mixed $requestInfo
* #return Mage_Checkout_Model_Cart
*/
public function addProduct($productInfo, $requestInfo=null)
{
$product = $this->_getProduct($productInfo);
$request = $this->_getProductRequest($requestInfo);
$productId = $product->getId();
if ($product->getStockItem()) {
$minimumQty = $product->getStockItem()->getMinSaleQty();
//If product was not found in cart and there is set minimal qty for it
if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty
&& !$this->getQuote()->hasProductId($productId)
){
$request->setQty($minimumQty);
}
}
if ($productId) {
try {
$result = $this->getQuote()->addProduct($product, $request);
} catch (Mage_Core_Exception $e) {
$this->getCheckoutSession()->setUseNotice(false);
$result = $e->getMessage();
}
/**
* String we can get if prepare process has error
*/
if (is_string($result)) {
$redirectUrl = ($product->hasOptionsValidationFail())
? $product->getUrlModel()->getUrl(
$product,
array('_query' => array('startcustomization' => 1))
)
: $product->getProductUrl();
$this->getCheckoutSession()->setRedirectUrl($redirectUrl);
if ($this->getCheckoutSession()->getUseNotice() === null) {
$this->getCheckoutSession()->setUseNotice(true);
}
Mage::throwException($result);
}
} else {
Mage::throwException(Mage::helper('checkout')->__('The product does not exist.'));
}
Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product));
$this->getCheckoutSession()->setLastAddedProductId($productId);
return $this;
}
/**
* Adding products to cart by ids
*
* #param array $productIds
* #return Mage_Checkout_Model_Cart
*/
public function addProductsByIds($productIds)
{
$allAvailable = true;
$allAdded = true;
if (!empty($productIds)) {
foreach ($productIds as $productId) {
$productId = (int) $productId;
if (!$productId) {
continue;
}
$product = $this->_getProduct($productId);
if ($product->getId() && $product->isVisibleInCatalog()) {
try {
$this->getQuote()->addProduct($product);
} catch (Exception $e){
$allAdded = false;
}
} else {
$allAvailable = false;
}
}
if (!$allAvailable) {
$this->getCheckoutSession()->addError(
Mage::helper('checkout')->__('Some of the requested products are unavailable.')
);
}
if (!$allAdded) {
$this->getCheckoutSession()->addError(
Mage::helper('checkout')->__('Some of the requested products are not available in the desired quantity.')
);
}
}
return $this;
}
You are doing .serialize() on a form element which doesn't have any input elememts. There is a note given http://api.jquery.com/serialize/ about which elements will be serialized using the function.
In setLocationAjax function, you are getting product id. Just pass the product id to the php script.
ie,
jQuery.ajax( {
url : url,
dataType : 'json',
type : 'post',
data: { productId: id },
success : function(data) {
jQuery('#ajax_loader'+id).hide();
setAjaxData(data,false);
}
});
In magento, you can get the product based on the productId and add to cart.

Categories