Pergunta sobre Desenvolvimento com WordPress por WordPress: Converter aplicativo PHP/Javascript em um plugin do WordPress

Um usuário perguntou ?

Estou tentando converter o aplicativo de calendário PHP/Javascript para o widget do WordPress. Quase funciona, mas quando tento passar para o mês seguinte ou anterior, recebo o seguinte erro:

TypeError: $ is undefined[Learn More] calendar.js:28:2
getPrevmonth 
onclick 

Este erro se concentra no seguinte 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>' );
        }
    });

Meu problema, acho, é que tenho que incluir as bibliotecas ajax no código, mas tentei algumas coisas diferentes, mas não consigo fazê-lo funcionar. Agradecemos qualquer conselho. Como nota, o desenvolvimento do WordPress é novo para mim e nunca usei AJAX ou JQuery. Aqui está o código:

eventos.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="
							}else{
								echo "<td class="day"><a href="
							}
							$ctr++;
						}
						echo "</tr><tr>";
						while ($ctr <= $totaldays) {
							if ($ctr == $current) {
								 echo "<td class="today"><a href="
							}else{
								echo "<td class="day"><a href="
							}
							$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="
			}else{
				echo "<td class="day"><a href="
			}
			$ctr++;
		}
		echo "</tr><tr>";
		while ($ctr <= $totaldays) {
			if ($ctr == $current) {
				 echo "<td class="today"><a href="
			}else{
				echo "<td class="day"><a href="
			}
			$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 tópico foi modificado 2 anos, 1 mês atrás por.

(@ alegremente)

2 anos, 1 mês atrás

Normalmente $ como as pessoas se referem a jQuery. O WordPress carrega a biblioteca jQuery no modo sem conflito, então $ é indefinido. Seu plugin deve tornar seu script dependente do jQuery (e você não precisa carregá-lo sozinho, certifique-se de não fazer isso) e certifique-se de retornar seu código para uma função que vá além do jQuery como $. Isso significa que você não precisará alterar seu código, mas continuará poluindo o namespace global com suas variáveis.

lançador de tópicos

(@darthmikeyd)

2 anos, 1 mês atrás

Obrigado pela resposta Joice. Acho que estou enfileirando o código com

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

Não soa como um idiota completo, mas, felizmente, é assim que me sinto agora, como eu corro com jQuery como $?

(@ alegremente)

2 anos, 1 mês atrás

Você codifica assim:

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

lançador de tópicos

(@darthmikeyd)

2 anos, 1 mês atrás

Ele fez isso!! Obrigado pela resposta e ajuda!!!

Isto foi útil?

0 / 0

Deixe uma resposta 0

O seu endereço de email não será publicado. Campos obrigatórios são marcados *