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

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?

Related

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

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 + '"]

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...

Insert hash into url to turn it into an anchor

I'm using Wordpress, and trying to figure out how to hack the links within the sub-menus.
I've set up a demo here: http://brandsite.simpletruth.io/logo/
Specifically, I want to add a hash in front of second-level menu links so that they become same-page anchors instead of going to a separate page.
For instance:
http://brandsite.simpletruth.io/logo/logo-spacing/
Becomes:
http://brandsite.simpletruth.io/logo#logo-spacing
Ideally this happens within Wordpress, but I think doing it with javascript would be an okay solution too.
Thanks!
you have to use a custom walker function
in your instance:
in your functions
class custom_names extends Walker_Nav_Menu
{
/* Start of the <ul>
*
* Note on $depth: Counterintuitively, $depth here means the "depth right before we start this menu".
* So basically add one to what you'd expect it to be
*/
function start_lvl(&$output, $depth = 0, $args = array())
{
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"children\">\n";
}
/* End of the <ul>
*
* Note on $depth: Counterintuitively, $depth here means the "depth right before we start this menu".
* So basically add one to what you'd expect it to be
*/
function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n";
}
/* Output the <li> and the containing <a>
* Note: $depth is "correct" at this level
*/
function start_el( &$output, $item, $depth = 0, $args = array(), $current_object_id = 0 )
{
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $class_names .'>';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
if ($depth == 1) {
$attributes = ' ' . $attr . '="'.str_replace(basename ($item->url), '#'.str_replace(' ', '-', strtolower ($item->title)), $value).'"';
}
}
$title = apply_filters( 'the_title', $item->title, $item->ID );
$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . $title . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
/* Close the <li>
* Note: the <a> is already closed
* Note 2: $depth is "correct" at this level
*/
function end_el ( &$output, $item, $depth = 0, $args = array())
{
$output .= '</li>';
return;
}
/* Add a 'hasChildren' property to the item
* Code from: http://wordpress.org/support/topic/how-do-i-know-if-a-menu-item-has-children-or-is-a-leaf#post-3139633
*/
function display_element ($element, &$children_elements, $max_depth, $depth = 0, $args, &$output)
{
// check whether this item has children, and set $item->hasChildren accordingly
$element->hasChildren = isset($children_elements[$element->ID]) && !empty($children_elements[$element->ID]);
// continue with normal behavior
return parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
}
}
in your header.php (or wherever your menu is)
<?php wp_nav_menu( array('walker' => new custom_names())); ?>

What does "array must have exactly two members" mean?

I am trying to set up a custom walker for my wordpress menu. Its purpose is to allow me to add php code to the menu links as I could with text and images like this:
<a href="http://mcadrives.com/?ref=<?PHP code goes here?>">
The php coding I have been using on every hyperlink and image is this:
<a href="http://mcadrives.com/?ref=
<?php
if (!empty ( $_SERVER['QUERY_STRING'])){
echo substr($_SERVER['QUERY_STRING'],4); }
else{
echo 'mhammonds'; }
?>>
I added this to my functions.php file:
class Query_Nav extends Walker_Nav_Menu
{
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
//ADD YOUR PHP HERE TO DETERMINE WHATEVER IT IS YOU NEED FOR YOUR LINK
if ( ! empty ( $_SERVER['QUERY_STRING'] ) ) {
$addedStuff = '?ref=' . substr( $_SERVER['QUERY_STRING'], 4 );
}else {
$addedStuff = '?ref=mhammonds';
}
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url.$addedStuff) .'"' : '';
////////////////////
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
and I added this walker 'new Query_Nav' to my nav-menu-template.php:
function wp_nav_menu( $args = array() ) {
static $menu_id_slugs = array();
$defaults = array( 'menu' => '', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '',
'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0, 'walker' => 'new Query_Nav()', 'theme_location' => '' );
I was then informed by a WARNING that class 'new Query_Nav()' is not found on Line 660, so I added it like so:
function walk_nav_menu_tree( $items, $depth, $r ) {
$walker = ( empty($r->walker) ) ? new Walker_Nav_Menu : $r->walker;
$args = array( $items, $depth, $r );
return call_user_func_array( array( $walker, 'walk', 'new Query_Nav()'), $args );
Now I have another WARNING stating:
call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in /home/ballaboy258/public_html/wp-includes/nav-menu-template.php on line 660
I have removed each one and neither has solved the problem. If I remove $walker, then 'walk' is not found. If I remove 'walk', then 'new Query_Nav()' is not found. If I remove 'new Query_Nav()', again, "new Query_Nav()' is not found. It doesn't make any sense.
Did I miss a step, or is my syntax wrong? I'm confused and I can't find anything on the web to help me.
It means that your callback array
array( $walker, 'walk', 'new Query_Nav()'),
should comprise two elements
a class
a method
that represent the function you are calling
You have provided three

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;
}

Categories