Pregunta sobre Developing with WordPress de Wordpress:

Convierta la aplicaci贸n PHP / Javascript a un plugin de WordPress

Un usuario pregunt贸 馃憞

Estoy tratando de convertir la aplicaci贸n de calendario PHP / Javascript al widget de WordPress. Casi funciona, pero cuando intento pasar al mes siguiente o al anterior, aparece el siguiente error:

TypeError: $ is undefined[Learn More] calendar.js:28:2
getPrevmonth http://server/testfolder/directory/wp-content/plugins/calendar/calendar.js:28:2
onclick http://server/testfolder/directory/:1:1

Este error se centra en el siguiente c贸digo:

	$.ajax({
        type: "GET", // use $_GET method to submit data
        url: 'processcalendar.php', // where to submit the data
        data: {
            newmonth : newmonth, // PHP: $_GET['newmonth']
            newyear  : newyear, // PHP: $_GET['newyear']
        },
        success:function(data) {
            $( '#calendardiv' ).html( data ); // add HTML results to empty div
            $( '#currentmonth' ).val( newmonth );
            $( '#currentyear' ).val( newyear );
        },
        error: function(errorThrown){
            $( '#calendardiv' ).html( '<p>Error retrieving data. Please try again.</p>' );
        }
    });

Mi problema, creo, es que tengo que incluir las bibliotecas ajax en el c贸digo, pero prob茅 algunas cosas diferentes, pero no puedo hacer que funcione. Agradecemos cualquier consejo. Como nota, el desarrollo para WordPress es nuevo para m铆 y nunca he usado AJAX o JQuery. Aqu铆 est谩 el c贸digo:

events.php

<?php
	/*
		Plugin Name: Intranet Calendar Plugin Test
		Description: Event Plugin
		Version: 1.0.0
		Author: Mike Dunham
		License: GPLv2 or later
		Text Domain: The Eagles Nest Web Design
	*/			
			
	class Calendar_Widget extends WP_Widget {
		
		public function __construct() {
			$widget_options = array( 
		    	'classname' => 'calendar_widget',
		      	'description' => 'This is an Event Widget',
		    	);
			parent::__construct( 'calendar_widget', 'Calendar Widget', $widget_options );
		}

		
		public function widget( $args, $instance ) {
		  	$title = apply_filters( 'widget_title', 'Calendar Test' );
		  	echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title']; 
		  	
			wp_enqueue_style( 'calendar', plugins_url() . '/calendar/calendar.css',false,'1.1','all');
			wp_enqueue_script('calendar', plugins_url() . '/calendar/calendar.js', array('jquery'), null, true);
			
			if (isset($_GET["newmonth"])) {
				$month = $_GET["newmonth"];
				$month = $month + 1;
				$day = 1;
				$year = $_GET["newyear"];
				$newdate = mktime(0,0,0,$month,$day,$year);
				$displaymonth = date("F", $newdate);
				$displayyear = date("Y", $newdate);
				$linkmonth = date("m", $newdate);
				$linkyear = date("Y", $newdate);
				$current = date("j");
				$totaldays = date("t", $newdate);
			} else {
				$displaymonth = date("F");
				$displayyear = date("Y");
				$linkmonth = date("m");
				$day = 1;
				$linkyear = date("Y");
				$current = date("j");
				$totaldays = date("t");
			}
		?>
			<div id="calendardiv">
				<table id="calendar" border="1">
					<tr>
						<th id="prevmonth" valign="center"><button id="prev" class="button" onclick="getPrevmonth()"> < </button></th>
						<th id="mainhead" colspan="5"><?php echo $displaymonth . " " . $displayyear; ?></th>
						<th id="nextmonth" valign="center"><button id="next" class="button" onclick="getNextmonth()"> > </button></th>
					</tr>
					<tr>
						<th id="header">Sun</th>
						<th id="header">Mon</th>
						<th id="header">Tue</th>
						<th id="header">Wed</th>
						<th id="header">Thu</th>
						<th id="header">Fri</th>
						<th id="header">Sat</th>
					</tr>
					<tr>
						<?php
						$first = date("w", mktime(0,0,0,$linkmonth,$day,$linkyear));
						$ctr = 1;
						$ctrcells = 0;
						for ($i=0; $i<$first; $i++) {
							echo "<td class='nil'></td>";
						}
						for ($i=$first; $i<=6; $i++) {
							if ($ctr == $current) {
								 echo "<td class='today'><a href='#'>$ctr</a></td>";
							}else{
								echo "<td class='day'><a href='#'>$ctr</a></td>";
							}
							$ctr++;
						}
						echo "</tr><tr>";
						while ($ctr <= $totaldays) {
							if ($ctr == $current) {
								 echo "<td class='today'><a href='#'>$ctr</a></td>";
							}else{
								echo "<td class='day'><a href='#'>$ctr</a></td>";
							}
							$ctrcells++;
							if ($ctrcells == 7) {
								echo "</tr><tr>";
								$ctrcells = 0;
							}
							$ctr++;
						}
						if ($ctrcells <> 0) {
							for ($i=$ctrcells; $i<7; $i++) {
								echo "<td class='nil'></td>";
							}
						}
						
						?>
						
					</tr>
				</table>
				<input type="hidden" name="currentmonth" id="currentmonth" />
				<input type="hidden" name="currentyear" id="currentyear" />
			</div>
			
		
			<?php

			echo $args['after_widget'];
		}
		
		public function form( $instance ) {
		  	$title = ! empty( $instance['title'] ) ? $instance['title'] : ''; 
		  	?>
		  	<p>
		    	<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>
		    	<input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
		  	</p>
		  	<?php 
		}
				
		public function updatecalendar( $new_instance, $old_instance ) {
		  	$instance = $old_instance;
		  	$instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] );
		  	return $instance;
		}
		
		
		
	}
	
	
	function register_calendar_widget() { 
		register_widget( 'Calendar_Widget' );
	}
	add_action('widgets_init', 'register_calendar_widget');

	
/************************************************************************************************************************************************************
 * This portion registers the activation, deactivation and uninstall hook
/***********************************************************************************************************************************************************/
	register_activation_hook( __FILE__, 'activate_calendar_plugin' );
	//register_deactivation_hook( __FILE__, 'deactivate_staff_directory_plugin' );
	register_uninstall_hook(__FILE__, 'uninstall_calendar_plugin');
	
/************************************************************************************************************************************************************
 * This portion creates the database tables when the plugin is activated
/***********************************************************************************************************************************************************/
	function activate_calendar_plugin() {
		
	}
	
/************************************************************************************************************************************************************
 * This portion deletes the database tables when the plugin is uninstalled
/***********************************************************************************************************************************************************/
	function uninstall_calendar_plugin() {
		
		
	}

/************************************************************************************************************************************************************
 * This portion Adds Menu Items for the plugin
/***********************************************************************************************************************************************************/
	function calendar_admin_menu_option() {
		add_menu_page('Calendar Test', 'Calendar Test', 'manage_options', 'calendar_admin_menu', 'calendar_scripts_page', '', 200);
	}
	add_action('admin_menu', 'calendar_admin_menu_option');
	
/************************************************************************************************************************************************************
 * Main page for the events calendar plugin.
/***********************************************************************************************************************************************************/
	function calendar_scripts_page() {
		global $wpdb;
		
		echo "<h2>Calendar Test Plugin</h2>";
			
			
	}

calendar.js

function getPrevmonth() {
			
	var currentmonth = document.getElementById('currentmonth').value;
	var currentyear = document.getElementById('currentyear').value;
	
	if (currentmonth) {
		if (currentmonth == 0) {
			var newmonth = 11;
			var newyear = currentyear-1;
		} else {
			var newmonth = Number(currentmonth) - 1;
			var newyear = currentyear;
		}
	} else {
		var date = new Date();
		var month = date.getMonth();
		var year = date.getFullYear();
		
		if (month == 0) {
			var newmonth = 11;
			var newyear = year-1;
		} else {
			var newmonth = month - 1;
			var newyear = year;
		}
	}
	
	$.ajax({
        type: "GET", // use $_GET method to submit data
        url: 'processcalendar.php', // where to submit the data
        data: {
            newmonth : newmonth, // PHP: $_GET['newmonth']
            newyear  : newyear, // PHP: $_GET['newyear']
        },
        success:function(data) {
            $( '#calendardiv' ).html( data ); // add HTML results to empty div
            $( '#currentmonth' ).val( newmonth );
            $( '#currentyear' ).val( newyear );
        },
        error: function(errorThrown){
            $( '#calendardiv' ).html( '<p>Error retrieving data. Please try again.</p>' );
        }
    });
}

function getNextmonth() {
	
	var currentmonth = document.getElementById('currentmonth').value;
	var currentyear = document.getElementById('currentyear').value;
	
	if (currentmonth) {
		if (currentmonth == 11) {
			var newmonth = 0;
			var newyear = Number(currentyear) + 1;
		} else {
			var newmonth = Number(currentmonth) + 1;
			var newyear = currentyear;
		}
	} else {
		var date = new Date();
		var month = date.getMonth();
		var year = date.getFullYear();
		
		if (month == 11) {
			var newmonth = 0;
			var newyear = year+1;
		} else {
			var newmonth = month + 1;
			var newyear = year;
		}
	}
	
	$.ajax({
        type: "GET", // use $_GET method to submit data
        url: 'processcalendar.php', // where to submit the data
        data: {
            newmonth : newmonth, // PHP: $_GET['newmonth']
            newyear  : newyear, // PHP: $_GET['newyear']
        },
        success:function(data) {
            $( '#calendardiv' ).html( data ); // add HTML results to empty div
            $( '#currentmonth' ).val( newmonth );
            $( '#currentyear' ).val( newyear );
        },
        error: function(errorThrown){
            $( '#calendardiv' ).html( '<p>Error retrieving data. Please try again.</p>' );
        }
    });
}

processcalendar.php

<?php
	wp_enqueue_style( 'calendar', plugins_url() . '/calendar/calendar.css',false,'1.1','all');
	wp_enqueue_script('calendar', plugins_url() . '/calendar/calendar.js', array('jquery'), null, true);
	
	if (isset($_GET["newmonth"])) {
		$month = $_GET["newmonth"];
		$month = $month + 1;
		$day = 1;
		$year = $_GET["newyear"];
		$newdate = mktime(0,0,0,$month,$day,$year);
		$displaymonth = date("F", $newdate);
		$displayyear = date("Y", $newdate);
		$linkmonth = date("m", $newdate);
		$linkyear = date("Y", $newdate);
		$current = date("j");
		$totaldays = date("t", $newdate);
	} else {
		$displaymonth = date("F");
		$displayyear = date("Y");
		$linkmonth = date("m");
		$day = 1;
		$linkyear = date("Y");
		$current = date("j");
		$totaldays = date("t");
	}
?>

<table id="calendar" border="1">
	<tr>
		<th id="prevmonth" valign="center"><button id="prev" class="button" onclick="getPrevmonth()"> < </button></th>
		<th id="mainhead" colspan="5"><?php echo $displaymonth . " " . $displayyear; ?></th>
		<th id="nextmonth" valign="center"><button id="next" class="button" onclick="getNextmonth()"> > </button></th>
	</tr>
	<tr>
		<th id="header">Sun</th>
		<th id="header">Mon</th>
		<th id="header">Tue</th>
		<th id="header">Wed</th>
		<th id="header">Thu</th>
		<th id="header">Fri</th>
		<th id="header">Sat</th>
	</tr>
	<tr>
		<?php
		$first = date("w", mktime(0,0,0,$linkmonth,$day,$linkyear));
		$ctr = 1;
		$ctrcells = 0;
		for ($i=0; $i<$first; $i++) {
			echo "<td class='nil'></td>";
		}
		for ($i=$first; $i<=6; $i++) {
			if ($ctr == $current) {
				 echo "<td class='today'><a href='#'>$ctr</a></td>";
			}else{
				echo "<td class='day'><a href='#'>$ctr</a></td>";
			}
			$ctr++;
		}
		echo "</tr><tr>";
		while ($ctr <= $totaldays) {
			if ($ctr == $current) {
				 echo "<td class='today'><a href='#'>$ctr</a></td>";
			}else{
				echo "<td class='day'><a href='#'>$ctr</a></td>";
			}
			$ctrcells++;
			if ($ctrcells == 7) {
				echo "</tr><tr>";
				$ctrcells = 0;
			}
			$ctr++;
		}
		if ($ctrcells <> 0) {
			for ($i=$ctrcells; $i<7; $i++) {
				echo "<td class='nil'></td>";
			}
		}
		
		?>
		
	</tr>
</table>
<input type="hidden" name="currentmonth" id="currentmonth" />
<input type="hidden" name="currentyear" id="currentyear" />

Este tema fue modificado hace 2 a帽os, 1 mes por.

(@ alegremente)

Hace 2 a帽os, 1 mes

Por lo general, $ como la gente se refiere a jQuery. WordPress carga la biblioteca jQuery en modo sin conflicto, por lo que $ no est谩 definido. Su plugin deber铆a hacer que su script dependa de jQuery (y no tiene que cargarlo usted mismo, aseg煤rese de no hacerlo), y aseg煤rese de devolver su c贸digo a una funci贸n que vaya m谩s all谩 de jQuery como $. Esto significar谩 que no tendr谩 que cambiar su c贸digo, sino que seguir谩 contaminando el espacio de nombres global con sus variables.

Lanzador de hilos

(@darthmikeyd)

Hace 2 a帽os, 1 mes

Gracias por la respuesta Joy. Creo que estoy poniendo en cola el c贸digo con

wp_enqueue_script('calendar', plugins_url() . '/calendar/calendar.js', array('jquery'), null, true);

No suena como un completo idiota, pero qu茅 suerte, as铆 es como me siento ahora, 驴c贸mo corro con jQuery como $?

(@ alegremente)

Hace 2 a帽os, 1 mes

Lo codificas as铆:

( function( $ ) {
  // all your code here
} )( jQuery );

Lanzador de hilos

(@darthmikeyd)

Hace 2 a帽os, 1 mes

El hizo eso !! Gracias por la respuesta y ayuda !!!

驴Solucion贸 tu problema??

0 / 0

Deja una respuesta 0

Tu direcci贸n de correo electr贸nico no ser谩 publicada. Los campos obligatorios est谩n marcados con *