Wp media gallery metabox Cannot read property 'state' of undefined - javascript

I have a task to create media gallery images in post type as like "woocommerce product gallery images" without any plugin, It's all custom with meta box. I have created metabox "Gallery Images" and also have JS, but when i click on Add image button then it's not opening gallery to select images, It's returning errors in console
Uncaught TypeError: Cannot read property 'state' of undefined
I found this code from here source
Here are some screenshots:
In 2nd pic, I did console these:
console.log(wp); console.log(wp.media); console.log(wp.media.gallery);
console.log(wp.media.gallery.edit('[ gallery ids="' + val + '" ]')+ " -- frame");
Now, here is my code:
/*
* Add a meta box
*/
function post_gallery_images_metabox() {
add_meta_box(
'post_gallery_images',
'Gallery Images',
'post_gallery_images_metabox_callback',
'inject_template',
'side',
'default'
);
}
add_action( 'add_meta_boxes', 'post_gallery_images_metabox' );
/*
* Meta Box Callback function
*/
function post_gallery_images_metabox_callback( $post ) {
wp_nonce_field( 'save_feat_gallery', 'inject_feat_gallery_nonce' );
$meta_key = 'template_gallery_images';
echo inject_image_uploader_field( $meta_key, get_post_meta($post->ID, $meta_key, true) );
}
function inject_image_uploader_field( $name, $value = '' ) {
$image = 'Upload Image';
$button = 'button';
$image_size = 'full';
$display = 'none';
?>
<p><?php
_e( '<i>Choose Images</i>', 'mytheme' );
?></p>
<label>
<div class="gallery-screenshot clearfix">
<?php
{
$ids = explode(',', $value);
foreach ($ids as $attachment_id) {
$img = wp_get_attachment_image_src($attachment_id, 'thumbnail');
echo '<div class="screen-thumb"><img src="' . esc_url($img[0]) . '" /></div>';
}
}
?>
</div>
<input id="edit-gallery" class="button upload_gallery_button" type="button"
value="<?php esc_html_e('Add/Edit Gallery', 'mytheme') ?>"/>
<input id="clear-gallery" class="button upload_gallery_button" type="button"
value="<?php esc_html_e('Clear', 'mytheme') ?>"/>
<input type="hidden" name="<?php echo esc_attr($name); ?>" id="<?php echo esc_attr($name); ?>" class="gallery_values" value="<?php echo esc_attr($value); ?>">
</label>
<?php
}
/*
* Save Meta Box data
*/
function template_img_gallery_save( $post_id ) {
if ( !isset( $_POST['inject_feat_gallery_nonce'] ) ) {
return $post_id;
}
if ( !wp_verify_nonce( $_POST['inject_feat_gallery_nonce'], 'save_feat_gallery') ) {
return $post_id;
}
if ( isset( $_POST[ 'template_gallery_images' ] ) ) {
update_post_meta( $post_id, 'template_gallery_images', esc_attr($_POST['template_gallery_images']) );
} else {
update_post_meta( $post_id, 'template_gallery_images', '' );
}
}
add_action('save_post', 'template_img_gallery_save');
JS:
jQuery(document).ready(function(jQuery) {
jQuery('.upload_gallery_button').click(function(event){
var current_gallery = jQuery( this ).closest( 'label' );
console.log(current_gallery);
if ( event.currentTarget.id === 'clear-gallery' ) {
//remove value from input
current_gallery.find( '.gallery_values' ).val( '' ).trigger( 'change' );
//remove preview images
current_gallery.find( '.gallery-screenshot' ).html( '' );
return;
}
// Make sure the media gallery API exists
if ( typeof wp === 'undefined' || !wp.media || !wp.media.gallery ) {
return;
}
event.preventDefault();
// Activate the media editor
var val = current_gallery.find( '.gallery_values' ).val();
var final;
if ( !val ) {
final = '[ gallery ids="0" ]';
} else {
final = '[ gallery ids="' + val + '" ]';
}
var frame = wp.media.gallery.edit( final );
console.log(wp);
console.log(wp.media);
console.log(wp.media.gallery);
console.log(frame + " -- frame");
frame.state( 'gallery-edit' ).on('update', function( selection ) {
console.log('coming');
//clear screenshot div so we can append new selected images
current_gallery.find( '.gallery-screenshot' ).html( '' );
var element, preview_html = '', preview_img;
var ids = selection.models.map(
function( e ) {
element = e.toJSON();
preview_img = typeof element.sizes.thumbnail !== 'undefined' ? element.sizes.thumbnail.url : element.url;
preview_html = "<div class='screen-thumb'><img src='" + preview_img + "'/></div>";
current_gallery.find( '.gallery-screenshot' ).append( preview_html );
return e.id;
}
);
current_gallery.find( '.gallery_values' ).val( ids.join( ',' ) ).trigger( 'change' );
}
);
return false;
});
});
I don't know what to do, why this error is occurring. Please help me.

Replace [ gallery ids="0" ] with [gallery ids="0"], and [ gallery ids="' + val + '" ] with [gallery ids="' + val + '"]

Related

ERR_CONNECTION_CLOSED - PHP and Javascript

The script below works perfectly when my site is without SSL, that is, with the domain http://www.dominio.com.br, but when I activate SSL for the site, it will be like https://www.dominio.com.br, Google Chrome displays the error "ERR_CONNECTION_CLOSED". But in firefox the error does not occur.
<?php
function redirecionaVariaveisCF7() {
?>
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '4' == event.detail.contactFormId ) {
var inputs = event.detail.inputs;
for ( var i = 0; i < inputs.length; i++ ) {
if ( 'nome' == inputs[i].name ) {
var nome = inputs[i].value;
}
if ( 'email' == inputs[i].name ) {
var email = inputs[i].value;
}
}
window.location.href = 'testes/wp_01/teste-sucesso/?nome='+nome+'&email='+email;
}
}, false );
</script>
<?php
}
add_action( 'wp_footer', 'redirecionaVariaveisCF7' );
add_action( 'the_content', 'exibeVariaveisCF7' );
function exibeVariaveisCF7($cf7_exibe_mensagem_conteudo) {
if(is_page('teste-sucesso')){
$nome = htmlspecialchars($_GET["nome"]);
$email = htmlspecialchars($_GET["email"]);
?><script>
function cont(){
var conteudo = document.getElementById('boxImpressaoDisponivel').innerHTML;
tela_impressao = window.open('https://www.meudominio.com.br');
tela_impressao.document.write(conteudo);
tela_impressao.window.print();
tela_impressao.window.close();
}
</script><?php
$cf7_exibe_mensagem_txt = "<div class='container' id='boxImpressaoDisponivel'> <br> <center><img src='https://www.meudominio.com.br/testes/wp_01/wp-content/uploads/2019/03/logo.png' width='120'></center> <br><br><br>";
if ($nome != NULL){
$cf7_exibe_mensagem_txt .= "<b>Nome:</b> " . $nome ."<br>";
}
if ($email != NULL){
$cf7_exibe_mensagem_txt .= "<b>E-mail:</b> " . $email ."<br>";
}
$cf7_exibe_mensagem_txt .= "</div>";
$cf7_exibe_mensagem_txt .= "<div class='container'>";
$cf7_exibe_mensagem_txt .= "<input type='button' onclick='cont();' value='Imprimir'>";
$cf7_exibe_mensagem_txt .= "</div>";
}
$cf7_exibe_mensagem_resultado = $cf7_exibe_mensagem_txt . $cf7_exibe_mensagem_conteudo;
return $cf7_exibe_mensagem_resultado;
}
Google Chrome have strange behavior when switching between http/https. It has some kind of cache I think. There's nothing wrong with your PHP-script if it works in FF. So give Chrome some time...

How to add custom html to ajax load more (wordpress)

I have added a "load more" button with ajax by following this posting...
Load More Posts Ajax Button in Wordpress
However, I need to add in some custom HTML for the content to sit in. I tried making a template and adding that into my ajax call but I couldn't get it working as the entire template would post 5 times.(I'm incrementing posts by 5). My question is, how do you structure the HTML in PHP for the ajax object?
My ajax function is here (in functions.php):
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 5;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$myposts = get_posts( $args );
$postcounter = 1;
$mediumcounter = 0;
$smallcounter = 0;
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
// 'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
/******I NEED TO CHANGE THE BELOW*******/
$out .= '<div class="parent">
<h1>play ball '.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
The template file I was trying to load up looks like this...
<?php
$args = array(
'posts_per_page' => 5
);
$myposts = get_posts( $args );
$postcounter = 1;
$mediumcounter = 0;
$smallcounter = 0;
foreach ( $myposts as $post ) : setup_postdata( $post );
if($postcounter == 1 ){
echo '<div class="parent">';
echo '<div class="single postwrapper child-2 postwrapper'.$postcounter.' mediumpost gray">';
}
else if($postcounter == 2 ){
echo '<div class="multi postwrapper child-2 ">';
echo '<div class="parent">';
}else{
$smallcounter = $smallcounter + 1;
if(in_array($smallcounter, array(1,2))){
$postcolor = 'blue';
}else{
$postcolor = 'gray';
}
}
echo '<div class="postwrapper child-2 postwrapper'.$postcounter.' smallpost '. $postcolor .'">';
get_template_part( 'homenew', get_post_format() );
echo '</div>';
if($postcounter == 1 || $postcounter == 5 ){
echo '</div>';
if($postcounter == 5){
echo '</div>';
}
}
$postcounter = $postcounter + 1;
endforeach;
wp_reset_postdata();?>
Would I have to write the template file out in the ajax function? Or just send post info to the javascript and append custom js with jquery?

foreach slider only shows one db entry

I've got an array which gets all the testimonials from the database table and displays them via a foreach array. I want some kind of a slider which fades-in and fades-out the results.
This is my query:
$showTestimonials = array();
$getTestimonials = mysqli_query($mysqli,"SELECT * FROM testimonials ORDER BY testimonial_id DESC") OR die (mysqli_error($mysqli));
while($row = mysqli_fetch_array($getTestimonials)){
$row = array(
'testimonialName' => $row['name'],
'testimonialMessage' => $row['message']);
$showTestimonials[] = $row;
}
My PHP foreach code:
$count = 0;
foreach ($showTestimonials as $stt):
echo '<div class="content welcome features container">';
echo '<div class="content welcome features testimonial">';
echo '<div id="goSlide">';
if($count == 0) {
echo '<div class="slide show">';
echo '<div>'.$stt['testimonialMessage'].' '.$stt['dModel'].'</div>';
echo '<div>'.$stt['testimonialName'].'</div>';
echo '</div>';
}
echo '</div>';
echo '</div>';
echo '</div>';
$count++;
endforeach;
My piece of Javascript code
$(document).ready(function(){
var slides = $('#goSlide > .slide').length;
var current = 0;
setInterval(function() {
var next = ( ( current + 1 ) == slides ? 0 : current + 1 );
$( $( "#goSlide > .slide" )[ current ] ).fadeOut(1000).removeClass(".show");
$( $( "#goSlide > .slide" )[ next ] ).fadeIn(1000);
current = next;
}, 4000);
});
It's currently only showing ONE (the latest in the database) and only fades-in and out that one. It does not show the other testimonials.
The problem is you are updating $row inside the loop
while($row = mysqli_fetch_array($getTestimonials)){
$row = array( <---- here $row is getting updated
'testimonialName' => $row['name'],
'testimonialMessage' => $row['message']);
$showTestimonials[] = $row;
}
change it to
while($row = mysqli_fetch_array($getTestimonials)){
$row_1 = array(
'testimonialName' => $row['name'],
'testimonialMessage' => $row['message']);
$showTestimonials[] = $row_1;
}

Set the options of DropDown with TextField value

I want a checkbox that enable/disable a textfield. Once checkbox and textfield is enabled, get the value of textfield and set the number of options for dropdown accordingly,
For Example: if textfield have value 4, then the options for dropdown should be 1 2 3 4.
I have the following code. Please help me to fix it, Thanks.
Cakephp Form
echo $this->Form->checkbox('custom_lvl_def', array('hiddenField' => false,'OnClick'=>"enable_disable()"));
echo "Use custom level definitions"."&nbsp";
echo $this->Form->input('alternative_no_of_levels', array('style'=>'width:70px','label'=>'levels','div'=>false, 'disabled'=>TRUE));
echo "<br>";
echo $this->Form->input('dropdown', array(
'options'=>$options,
'empty' => 'Select Level',
'label'=>'Type:',
'selected'=>'Select Level',
'style'=>'width:130px',
'div'=>false
));
JavaScript Function
function enable_disable()
{
if($('#CompetenceCustomLvlDef').attr('checked'))
{
$('#CompetenceAlternativeNoOfLevels').removeAttr("disabled");
// var $a=array ('Level');
var value = $('#CompetenceAlternativeNoOfLevels').val();
for ( var i = 0; i < value; i++ ) {
$('#CompetenceDropdown').options[i].selected = i;
return; }
}
else
$('#CompetenceAlternativeNoOfLevels').attr('disabled', true);
}
This might help you to get the array of dropdown list for the number of levels you entered.
As per the question you can try this in the form..
echo $this->Form->checkbox('custom_lvl_def', array('hiddenField' => false,'id'=>'id_custom_lvl_def', 'onclick'=>"javascript:enable_disable()"));
echo "Use custom level definitions"."&nbsp";
echo $this->Form->input('alternative_no_of_levels', array('style'=>'width:70px','id'=>'id_alternative_no_of_levels','label'=>'levels','onblur'=>'javascript:enable_disable();', 'div'=>false, ));
echo "<br>";
echo $this->Form->input('dropdown', array(
'options'=>'',
'empty' => 'Select Level',
'label'=>'Type:',
'type'=>'select',
'id'=>'id_dropdown',
'name'=>'dropdown',
'style'=>'width:130px',
'div'=>false
));
In the script:
function enable_disable()
{
$("#id_dropdown").empty();
if($('#id_custom_lvl_def').attr('checked'))
{
$('#id_alternative_no_of_levels').removeAttr("disabled");
var value = $('#id_alternative_no_of_levels').val();
var optionsAsString = "";
optionsAsString += "<option value=''>" + "Select Level" + "</option>";
for ( var i = 1; i <= value; i++ ) {
optionsAsString += "<option value='" + i + "'>" + i + "</option>";
}
$( 'select[name="dropdown"]' ).append( $( optionsAsString ) );
}
else
$('#id_alternative_no_of_levels').attr('disabled', true);
}

Getting buddypress user name in a javascript file

From within my buddypress PHP templates I usually get the username of any given user by referencing the user ID like this:-
<?php echo bp_core_get_username( '{{userID}}' ) ?>
However I need to retrieve the username from within an external Javascript file.
The user ID is already passed in as var aData[11]. I have tried the following with no luck:-
$('td:eq(3)', nRow).html( '<div class="table-row"><h4 class="nomargin">' + aData[0] + '</h4>' + aData[1] + '</div>' );
I am trying to return a URL... This cirrently gives me:
http://www.mysite.com/members//song/?songsID=6
Whe it should be:
http://www.mysite.com/members/username/song/?songsID=6
Any ideas?
Edit: Below is the server side code that I am using to ouput the JSON
<?php
$aColumns = array( 'song_name', 'artist_band_name', 'author', 'song_artwork', 'song_file', 'genre', 'song_description', 'uploaded_time', 'emotion', 'tempo', 'songsID', 'user' );
$sIndexColumn = "songsID";
/* DB table to use */
$sTable = "wp_dbt_songs";
/* Database connection information */
$gaSql['user'] = "";
$gaSql['password'] = "";
$gaSql['db'] = "";
$gaSql['server'] = "";
$gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or
die( 'Could not open connection to server' );
mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
mysql_real_escape_string( $_GET['iDisplayLength'] );
}
if ( isset( $_GET['iSortCol_0'] ) )
{
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = mysql_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
?>
The html you're setting is being set on the client side, not on the server side, meaning that the php code will not be evaluated.
I guess what you can do is either put the already-evaluated username in a hidden tag and get that using jquery or expose it to the javascript on the page within script tags.
EDIT: So is the userID or the username in the json as well? If not, you could probably put it there. I'm still not so sure what the situation is. But if you're currently passing the userID in the json and actually want the username as bp_core_get_username would return it, why not just put the already retrieved (with bp_core_get_username) username into the json as well?
In other words, in your php code, figure out what the username is based on the userid with bp_core_get_username and then pass that into the json. That is, if I'm understanding the situation correctly.

Categories