PrettyPhoto and Touchwipe - php

I have tried to implement the approved answer from here: Adding jQuery TouchSwipe to prettyPhoto to accomplish using touchwipe with prettyphoto.
The site is in wordpress and I have called the touchwipe javascript properly and added the code from the link above in my page.php with in script tags.
For some reason though I cannot get it to work.
Here is my code from page.php
<?php
get_header();
$no_feat_class = '';
if( !options::logic( 'blog_post' , 'enb_featured' ) || !
has_post_thumbnail( $post -> ID ) ){
$no_feat_class = ' no_feat ';
}
$post_id = $post -> ID;
/*---------------------*/
$post_format = get_post_format( $post -> ID );
if(!strlen($post_format)){ $post_format = 'standard';}
?>
<script>
$(document).ready(function(){
function setupBox() {
$("a[rel^='prettyPhoto']").prettyPhoto({
social_tools: false,
theme:'dark_rounded',
changepicturecallback: function() {
setupSwipe();
}
});
}
function setupSwipe() {
$(".pp_hoverContainer").touchwipe({
wipeLeft: function() {
$.prettyPhoto.changePage('next');
},
wipeRight: function() {
$.prettyPhoto.changePage('previous');
},
min_move_x: 20,
min_move_y: 20,
preventDefaultEvents: true
});
}
setupBox();
});
</script>
<section id="main">
<div class="main-container">
<?php
while( have_posts () ){
the_post();
$meta = meta::get_meta( $post -> ID, 'settings' );
$meta_enb = options::logic( 'blog_post' , 'meta' );
} /*EOF while( have_posts () ) */
?>
<?php
$resizer = new LBPageResizer('page');
$resizer -> render_frontend();
?>
</div>
</section>
<?php get_footer(); ?>
Have I done something wrong?

Related

Ajax request loads the same posts

I have a question related with Wordpress Ajax posts request. And I can't figure out for hours... Maybe someone will give me advice what I'm doing wrong!
Problem:
So I have infinite scroll on my archive pages. Everything is working as it should but for some reason it loads all the time the same 20 posts... What I need to change to have infinite scroll as long as created posts exists.
Here is my JS code:
function loadArticle() {
var loading = false;
$(window).bind('scroll', function() {
var page = $(this).data('page');
var newPage = page + 1;
var maxPages = $("#content").data('max-pages');
var postType = false;
var search = getQueryVariable("s");
if ( $('body').hasClass('post-type-archive-news') ) {
postType = 'news';
} else if ( $('body').hasClass('post-type-archive-ebooks') ) {
postType = 'ebooks';
} else if ( $('body').hasClass('post-type-archive-lookbooks') ) {
postType = 'lookbooks';
} else if ( $('body').hasClass('post-type-archive-case-studies') ) {
postType = 'case-studies';
} else if ( $('body').hasClass('post-type-archive-events') ) {
postType = 'events';
} else if ( $('body').hasClass('search-results') ) {
postType = false;
} else {
postType = 'post';
}
var query = 'action=infinite_scroll';
if ( newPage ) {
query = query + '&page_no=' + newPage;
}
if ( typeof postType == "string" ) {
query = query + "&post_type=" + postType;
}
if ( typeof search == "string" ) {
query = query + "&search=" + search;
}
// Show Loader
//$('a#inifiniteLoader').show('fast');
// Load Next Page
if(!loading && $(window).scrollTop() >= ($('#content').offset().top + $('#content').outerHeight() - window.innerHeight)) {
loading = true;
$.ajax({
url: "/wp-admin/admin-ajax.php",
type:'POST',
data: query,
success: function(html){
$("#content").append(html); // This will be the div where our content will be loaded
loading = false;
}
});
}
return false;
});
}
And this is my PHP
function yieldify_infinite_scroll(){
//init ajax
$ajax = false;
//check ajax call or not
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$ajax = true;
}
$paged = $_POST['page_no'] + 1;
$post_type = $_POST['post_type'];
$search = $_POST['s'];
$args = array(
'posts_per_page' => get_option('posts_per_page'),
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish'
);
if ( $post_type ) {
$args['post_type'] = $post_type;
}
if ( $search ) {
$args['s'] = $post_type;
}
// Load the posts
//query_posts( $args );
$ajax_query = new WP_query( $args );
//echo "<pre>";
//$print_query = json_encode( $ajax_query, JSON_PRETTY_PRINT );
//$print_query = htmlentities( $print_query, ENT_QUOTES, 'utf-8' );
//print_r( $print_query );
//echo "</pre>";
if( $ajax_query->have_posts() ) {
while( $ajax_query->have_posts() ) { $ajax_query->the_post();
if ( $post_type ) { ?>
<div class='col-12 col-md-6 col-lg-4 d-flex'>
<?php get_template_part('loops/card-new'); ?>
</div><!-- .col -->
<?php } else {
echo "<div class='col-12'>";
get_template_part('loops/search-results');
echo "</div>";
}
}
}
wp_reset_postdata();
//check ajax call
if($ajax) die();
exit;
}
add_action('wp_ajax_infinite_scroll', 'yieldify_infinite_scroll'); // for logged in user
add_action('wp_ajax_nopriv_infinite_scroll', 'yieldify_infinite_scroll');
My archive layout looks like that:
<?php if( have_posts() ) : $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?>
<section id="blog-listing" class="resources-section">
<div class='container'>
<div class='row' id="content">
<?php while( have_posts() ) : the_post(); ?>
<div class='col-12 col-md-6 col-lg-4 d-flex'>
<?php get_template_part('loops/card-new'); ?>
</div><!-- .col -->
<?php endwhile; ?>
</div><!-- .row -->
<div class='row'>
<div class='col-12 text-center'>
Show More
</div><!-- .col -->
</div><!-- .row -->
</div><!-- .container -->
</section><!-- #blog-listing -->
<?php endif; ?>
I would be appreciated for any help!
It seems to me that you need to update the value in $(this).data('page')
You get it, do an increment on the variable, but you do not store it back. Try to modify as follow.
var page = $(this).data('page');
var newPage = page + 1;
$(this).data('page', newPage);

Ob_start filtering closes <script> tag wrong

I am using ob_start to filter a WordPress backend page.
My script looks like this:
function remove_extra_field_profile()
{
$current_file_url = preg_replace( "#\?.*#" , "" , basename( $_SERVER['REQUEST_URI'] ) );
if( $current_file_url == "profile.php" )
{
add_action( 'wp_loaded', function(){ ob_start("profile_callback"); } );
add_action( 'shutdown', function(){ ob_end_flush(); } );
}
}
add_action( 'init', 'remove_extra_field_profile' );
function profile_callback( $html )
{
$profile_dom = new DOMDocument;
$profile_dom->loadHTML( $html );
$all_lines = $profile_dom->getElementsByTagname( 'tr' );
$excludes = array(
'user-syntax-highlighting-wrap',
'user-rich-editing-wrap'
);
$deletes = array();
foreach ( $all_lines as $line )
{
$tr_calss = $line->getAttribute("class");
if( in_array( $tr_calss, $excludes ) )
{
$deletes[] = $line;
}
}
$deletes[] = $profile_dom->getElementsByTagname( 'h2' )->item(0);
foreach ($deletes as $delete)
{
$delete->parentNode->removeChild( $delete );
}
return $profile_dom->saveHTML();
}
this works fine.
But once I add a plugin which adds a select field to profile.php (wordpress adds somethings automatically), things get strange:
With the "filtering-script" from above in place, the closing </script> tag (which is supposed to be at the end) will be moved forward:
<script type="text/html" id="tmpl-media-frame">
<div class="media-frame-menu"></script></div>
<div class="media-frame-title"></div>
<div class="media-frame-router"></div>
<div class="media-frame-content"></div>
<div class="media-frame-toolbar"></div>
<div class="media-frame-uploader"></div>
Once I remove the PHP script, everything is fine.
Why is the script affecting this <script> part? What can I do differently?
Thanks a lot!

WordPress: Function for loading a specific page with shortcode

I have this structure of pages in WordPress:
Materials //parent
-> Plastic //children
-> Metal //children
-> ...
I want to include content from my file grid-fasads.php with shortcode exactly where I need to.
I have this code in a product.php where I use a shortcode:
$fasads = get_field('fasad_type');
foreach ($fasads as $f) {
echo do_shortcode('[grid-fasad]');
}
I wrote this function in functions.php:
function get_fasads($atts, $content = null ) {
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query( array( 'post_type' => 'page' ) );
// get a specific page ID
$materials = get_page( 4702 );
// filter for choosing a children pages of 'materials'
$materials_children = get_page_children( $materials->ID, $all_wp_pages );
foreach ( $materials_children as $children ) {
$page = $children->ID;
echo $page;
}
// It's ok. The pages IDs are shown.
// After that I have this:
$recent = new WP_Query( "page_id = " . $page );
while( $recent->have_posts() ) : $recent->the_post();
require( '/fasads/grid-fasads.php' );
the_content();
endwhile;
}
add_shortcode( 'grid-fasad','get_fasads' );
I understand that the problem is ( "page_id = " . $page). I need to include a .php file's content for each children pages of 'Materials' page. Tried to insert last part of code into a loop, but failed every time.
Here is a fragment from
I also tried this loop:
foreach ($materials_children as $children) {
$page = $children->ID;
$recent = new WP_Query("page_id=".$page);
while ($recent->have_posts()) : $recent->the_post();
require('/fasads/grid-fasads.php');
the_content();
endwhile;
print_r(array_count_values((array)$page));
}
But as a result it shows a duplicates of values. Something is wrong.
Please, help.
I've solved this problem.
Here is a function:
function get_pallette() {
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));
// get a specific page ID
$materials = get_page_by_title('Materials');
$materials_children = get_page_children( $materials->ID, $all_wp_pages );
if (isset ($materials_children)) :
foreach ($materials_children as $children) {
$page = $children->ID;
}
$fasads = get_field('fasad_type');
if (isset ($fasads)) :
foreach ($fasads as $f) {
$p = get_page_by_title( $f );
if (!empty ($p)) :
echo do_shortcode("[grid-fasad page=\"$p->ID\"]");
else :
//do something;
endif;
}
else :
//do something;;
endif;
endif;
//do something;
}
And here is another function for a generating shortcode:
function get_fasads($atts, $content = null ){
$atts = shortcode_atts(
array(
'page' => 0
), $atts, 'grid-fasad');
$recent = new WP_Query('page_id='. $atts['page']);
$path = $_SERVER['DOCUMENT_ROOT'].'/wp-content/themes/theme/fasads/grid-fasads.php';
while ($recent->have_posts()) : $recent->the_post();
require $path;
endwhile;
}
add_shortcode('grid-fasad','get_fasads');
A good's page fragment:
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); global $_product; $_product = new jigoshop_product( $post->ID ); ?>
<div id="post-<?php $id_page ?>" <?php post_class(); ?>>
<div class="summary">
<?php do_action('jigoshop_after_single_product_summary', $post, $_product); ?>
...
<?php get_pallette(); ?>
</div>
<?php endwhile; ?>
Maybe it's not an elegant decision, but it works.
There is only 1 problem still: after execution function get_pallette() the page loose it's own ID, because I'm using "new WP_Query" with a new IDs of page's children. And if this function goes before action "jigoshop_after_single_product_summary" (as I want to), it cannot load a content of an actual good's page.

Echo shortcode in WordPress AJAX function return

I have searched all over here and the web but cant seem to get this to work - hopefully you all can help.
I am trying to setup product filters for WooCommerce on the category page (like filter products depending on color etc)
I have the ajax working but I have a shortcode that I want to display for each product and this doesnt work - any ideas how to get it to show?
Code below:
PHP
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', plugins_url() . '/plugin-name/js/product-filter-ajax.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
JS
jQuery(document).ready(function($) {
$(".loading").hide();
var taxonomy = [];
var terms = [];
$('.filter-option input').click( function(event) {
var taxonomy_idx = $.inArray($(this).closest(".filter-title-wrapper").attr('data-attribute'), taxonomy);
if (taxonomy_idx == -1) {
taxonomy.push($(this).closest(".filter-title-wrapper").attr('data-attribute'));
} else {
taxonomy.splice(taxonomy_idx, 1);
}
var terms_idx = $.inArray($(this).val(), terms);
if (terms_idx == -1) {
terms.push($(this).val());
} else {
terms.splice(terms_idx, 1);
}
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = taxonomy.toString();;
var selected_term = terms.toString();
var selected_term_speach = '\'' + selected_term.split(',').join('\',\'') + '\'';
console.log(selecetd_taxonomy);
console.log(selected_term_speach);
// After user click on tag, fade out list of posts
$('.products').fadeOut();
$(".loading").fadeIn();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
term: selected_term_speach,
};
$.post( afp_vars.afp_ajax_url, data, function(response) {
$(".loading").fadeOut();
if( response ) {
// Display posts on page
$('.products').html( response );
// Restore div visibility
$('.products').fadeIn();
};
});
});
});
PHP TO GET POSTS
// Script for getting posts
function ajax_filter_get_posts( $taxonomy, $term ) {
ob_start();
global $woocommerce, $product;
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
$term = $_POST['term'];
$term = str_replace("\\", '', $term);
// WP Query
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
);
if ($term == "''") {
}
else {
$args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => array($term),
'field' => 'slug',
'operator' => 'IN'
),
)
);
}
?>
<h1> <?php echo $term ?> </h1>
<?php
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<li <?php wc_product_class(); ?>>
<?php echo do_shortcode('[product_shortcode]'); ?>
</li>
<?php
?>
<?php endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
return ob_get_clean();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
Excuse the messyness of the code, just trying to get it to work before I can start to neaten it up. Any advice on how to approach this in a better way please let me know.
Thanks and appreciate the help!
UPDATE-----
Tried to add the shortcode callback, but this doesnt work or I have the wrong code
add_action( 'init', function() {
ps_register_shortcode_ajax( 'ajax_filter_get_posts', 'ajax_filter_get_posts' );
} );
function ps_register_shortcode_ajax( $callable, $action ) {
if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
return;
call_user_func( $callable );
}
WordPress Ajax calls don't have the access to whole WordPress environment and that's why your shortcode not working. Instead of calling the shortcode directly, call its callback. Refer https://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request for more details.

inserting ads between every 7th post of homepage and category wordpress page

I am trying to insert google ads between every 7th posts in my wordpress site with infinite scroll. i searched and found results but that didn't worked for me because the WordPress theme i am using is little complex. the result i found was to add this code
<?php $postnum++; if($postnum%5 == 0) { ?>
YOUR AD CODE HERE
<?php } ?>
after <?php endwhile; ?> in index.php, but in my case the loop is different from the general wordpress theme. the loop i have is like this and i want to know how can i implement the above code in my case.
loop code
static function loop( $template ) {
global $wp_query;
echo '<input type="hidden" id="query-' . $template . '" value="' . urlencode( json_encode( $wp_query -> query ) ) . '" />';
if ( count( $wp_query->posts) > 0 ) {
if( self::is_grid( $template ) ){
?>
<div class="loop-container-view grid">
<?php self::loop_switch( $template , 1 ); ?>
</div>
<?php
}else{
?>
<div class="loop-container-view list" id="contloop">
<?php self::loop_switch( $template , 0 ); ?>
</div>
<?php
}
get_template_part('pagination');
} else {
get_template_part('loop', '404');
}
}
which then call this code, i made it a little shorter
static function get( $post , $template = 'blog_page' ){
$meta = meta::get_meta( $post -> ID , 'settings' );
if( isset( $meta['safe'] ) ){
if( meta::logic( $post , 'settings' , 'safe' ) ){
$classes = ' nsfw';
}else{
$classes = ' ';
}
}else{
$classes = ' ';
}
?>
<!-- post -->
<article id="post-<?php echo $post -> ID; ?>" <?php post_class( 'post ' . $classes , $post -> ID ); ?>>
</article>
<?php
}
loop switch function
static function loop_switch( $template = '' , $grid = 1 ) {
global $wp_query;
if ( !empty( $template ) ) {
$ajax = false;
} else {
$query = array();
$template = isset( $_POST['template'] ) && strlen( $_POST['template'] ) ? $_POST['template'] : exit();
$query = isset( $_POST['query'] ) && !empty( $_POST['query'] ) ? (array)json_decode( urldecode( $_POST['query'] ) ) : exit();
$query['post_status'] = 'publish';
$wp_query = new WP_Query( $query );
$grid = isset($_POST['grid']) ? (int)$_POST['grid'] : 1;
$ajax = true;
}
$template = str_replace( array( '_hot' , '_new' , '_like' ) , '' , $template );
if( $grid == 1 ){
$k = 1;
$i = 1;
$nr = $wp_query->post_count;
if (layout::get_length(0, $template) == 940 ) {
$div = 3;
} else {
$div = 2;
}
foreach ($wp_query->posts as $post) {
$wp_query->the_post();
if ($i == 1) {
if (( $nr - $k ) < $div) {
$classes = 'class="last"';
} else {
$classes = '';
}
echo '<div ' . $classes . '>';
}
self::grid( $post, $template );
if ($i % $div == 0) {
echo '</div>';
$i = 0;
}
$i++;
$k++;
}
if ($i > 1) {
echo '</div>';
}
}else{
foreach( $wp_query->posts as $index => $post ) {
$wp_query->the_post();
if ($index > 0) {
?><!--<p class="delimiter"> </p>--><?php
}
self::get( $post, $template );
}
}
if( $ajax ){
exit();
}
}
and post is called here in front-page.php file
<?php
$wp_query = new WP_Query(array( 'page_id' => options::get_value( 'front_page' , 'page' ) ) );
if( $wp_query -> post_count > 0 ){
foreach( $wp_query -> posts as $post ){
$wp_query -> the_post();
$post_id = $post -> ID;
?>
<article id="post-<?php the_ID(); ?>" <?php post_class() ?>>
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
<!-- post meta top -->
<?php
if( meta::logic( $post , 'settings' , 'meta' ) ){
get_template_part( 'post-meta-top' );
}
?>
</header>
<div class="entry-content">
<?php
/* if show featured image */
if( options::logic( 'blog_post' , 'show_featured' ) ){
if( has_post_thumbnail ( $post -> ID ) ){
$src = wp_get_attachment_image_src( get_post_thumbnail_id( $post -> ID ) , 'full' );
?>
<div class="featimg circle">
<div class="img">
<?php
ob_start();
ob_clean();
get_template_part( 'caption' );
$caption = ob_get_clean();
?>
<?php the_post_thumbnail( '600x200' ); ?>
<?php
if( strlen( trim( $caption) ) ){
?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
<?php
}
?>
</div>
</div>
<?php
}
}
?>
</div>
<footer class="entry-footer">
<div class="share">
<?php get_template_part( 'social-sharing' ); ?>
</div>
<div class="excerpt">
<?php the_content(); ?>
<?php wp_link_pages(); ?>
</div>
</footer>
</article>
<?php
}
}else{
/* not found page */
get_template_part( 'loop' , '404' );
}
Try this in front-page.php. You may have to adjust it to add after correct number of posts.
if( $wp_query -> post_count > 0 ){
$postnum = 0;
foreach( $wp_query -> posts as $post ){
$postnum++;
if( $postnum%5 == 0 ) {
echo '<p> ---- insert ad here ---- </p>';
}
$wp_query -> the_post();
$post_id = $post -> ID;
?>
it should replace this bit of code
if( $wp_query -> post_count > 0 ){
foreach( $wp_query -> posts as $post ){
$wp_query -> the_post();
$post_id = $post -> ID;
?>

Categories