Make the Height of Masonry Boxes Fixed size - wordpress

the website is the following: http://smokingdesigners.com
I have a problem with the masonry view of my pages.
I have recently changed my theme to a new one and my old theme used to add automatically on every article the "more" tag in order to crop my articles to fit to their masonry, So I have never actually added the "more" tag in more than 1200 articles.
My new theme is cropping the articles weird and that causes my page to be messed up because one box has height lets say 600 (including the picture) and the other 450 and it doesn't look good. (link with problem http://smokingdesigners.com/page/10/ )
Is there a way to make a fixed size boxes with heigh 575 lets say?
here is my masonry theme code..
$def_teaser_width = ( $dtw = get_option('wpb_post_teaser_width') ) ? $dtw : 'two-third';
if ( get_option('wpb_blog_layout') == __("Masonry", "wpb") ) {
$gallery_style = 'masonry';
} else {
$gallery_style = 'fluid';
}
if ( $_GET['style'] == 'masonry' ) {
$gallery_style = 'masonry';
} else if ( $_GET['style'] == 'fluid' ) {
$gallery_style = 'fluid';
}
$holder_class = ( $gallery_style == 'masonry' ) ? 'masonry_blocks' : 'float_blocks';
?>
<?php get_header(); ?>
<div class="float_blocks_container">
<div class="blog_teasers <?php echo $holder_class; ?>">
<?php if (have_posts()) :
$teasers_count = 0;
?>
<?php while (have_posts()) : the_post(); ?>
<?php
$teasers_count++;
$teaser_width = ( $tw = get_post_meta($post->ID, "_teaser_width", true) ) ? $tw : $def_teaser_width;
$teaser_width = ( $teaser_width == 'default' ) ? $def_teaser_width : $teaser_width;
//$teaser_width = ($teaser_w = get_post_meta($post->ID, "_teaser_width", true)) ? ' '.$teaser_w : ' one-half';
if ( $teaser_width == 'one-third' || ( $gallery_style == 'masonry' && $teaser_width == 'one-half' )) {
$th_w = 320;
$th_h = 180;
}
else if ( $teaser_width == 'one-half' ) {
$th_w = 495;
$th_h = 278;
}
else if ( $teaser_width == 'two-third' || ( $gallery_style == 'masonry' && $teaser_width == 'full-width' ) ) {
$th_w = 670;
$th_h = 377;
}
else if ( $teaser_width == 'full-width' ) {
$th_w = 1020;
$th_h = 574;
}
$content_type = (get_option('wpb_full_content') == 'true') ? ' full_content_in_blog' : '';
$has_thumbnail = '';
if (has_post_thumbnail() == false) { $has_thumbnail = ' no_thumbnail'; }
?>
<div id="post-<?php the_ID(); ?>" <?php post_class("post_teaser float_block ".$teaser_width.$has_thumbnail.$content_type); ?>>
<?php
$video_w = $th_w;
$video_h = $th_h;
$p_video = get_post_meta($post->ID, "_p_video", true);
$youtube = strpos($p_video, 'youtube.com');
$vimeo = strpos($p_video, 'vimeo');
if ( $youtube || $vimeo ) : ?>
<div class="p_video">
<?php
if ( $youtube ) {
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $p_video, $matches);
echo '<iframe width="'.$video_w.'" height="'.$video_h.'" src="http://www.youtube.com/embed/'.$matches[1].'" frameborder="0" allowfullscreen></iframe>';
}
else if ( $vimeo ) {
preg_match('#vimeo.com/([A-Za-z0-9\-_]+)?#s', $p_video, $matches);
echo '<iframe src="http://player.vimeo.com/video/'.$matches[1].'?title=0&byline=0&portrait=0" width="'.$video_w.'" height="'.$video_h.'" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>';
}
?>
</d
HERE IS FUNCTIONS.PHP FILE.
<?php
/*
wpb_category_filter
wpb_get_video_or_thumbnail
wpb_blog_pagination - previous/next page navigation
wpb_tags - return array with tags attached to post from specific vocab.
wpb_posted_under - return array with taxonomy object from specific vocab.
siteAttachedImages -
metaAttachedImages
wpb_login_head - changes logo in the WP login screen
wpb_resize - resize image to the specific dimensions
curPageURL - return current page url
*/
/* Category filter
---------------------------------------------------------- */
if (!function_exists('wpb_category_filter')) {
function wpb_category_filter ( $args = array() ) {
$defaults = array( 'taxonomy' => 'portfolio_category', 'posts' => NULL, 'echo' => true, 'filter_text' => __('Filter:', 'wpb_framework') );
$args = wp_parse_args( $args, $defaults );
$args = (object) $args;
if ( $args->posts == NULL) {
global $wp_query;
$args->posts = $wp_query->posts;
}
$categories_slugs_array = array();
$categories_names_array = array();
foreach ($args->posts as $p) {
$post_categories_array = wpb_get_post_categories(array('taxonomy' => $args->taxonomy, 'pid' => $p->ID));
if ( $post_categories_array ) {
$categories_slugs_array[$p->ID] = array();
$categories_names_array[$p->ID] = array();
if ( $post_categories_array['slug'] != NULL ) {
$categories_slugs_array[$p->ID] = array_unique( array_merge($post_categories_array['slug'], $categories_slugs_array[$p->ID]) );
$categories_names_array[$p->ID] = array_unique( array_merge($post_categories_array['name'], $categories_names_array[$p->ID]) );
}
}
}
$all_cats = array(); $all_slugs = array();
foreach ( $categories_names_array as $c ) { $all_cats = array_unique( array_merge( $all_cats, $c ) ); }
foreach ( $categories_slugs_array as $c ) { $all_slugs = array_unique( array_merge( $all_slugs, $c ) ); }
$filter = '';
if ( count($all_cats) > 0 ) :
$filter .= '<ul class="wpb_sort">';
$filter .= '<li class="wpb_all_cats"><span>'.$args->filter_text.'</span> <a class="wpb_sortable_current" href="#">'. __("All", "wpb_framework") .'</a></li>';
for ( $i = 0; $i < count($all_cats); $i++) {
$filter .= '<li><a class="wpb_sortable_cats" href="#" data-value="sortable-'.$all_slugs[$i].'">'.$all_cats[$i].'</a></li>';
}
$filter .= '</ul>';
unset($i);
endif;
return array('links' => $filter, 'categories_slugs_array' => $categories_slugs_array);
/*if ( $args->echo ) {
echo $filter;
} else {
return $filter;
}*/
}
}
/* Get video or thumbnail
---------------------------------------------------------- */
if (!function_exists('wpb_get_video_or_thumbnail')) {
function wpb_get_video_or_thumbnail( $args = array() ) {
$defaults = array( 'pid' => NULL, 'width' => 300, 'height' => 'proportional', 'force_image' => false, 'video_height' => 250, 'img_class' => NULL, 'echo' => true, 'before' => '', 'after' => '' );
$args = wp_parse_args( $args, $defaults );
$args = (object) $args;
if ($args->pid == NULL) {
global $post;
$pid = $post->ID;
} else {
$pid = $args->pid;
}
$has_thumbnail = '';
if ( has_post_thumbnail($pid) == false ) { $has_thumbnail = ' no_thumbnail'; }
$video_w = $args->width;
$video_h = $args->video_height;
$p_video = get_post_meta($pid, "_p_video", true);
$hide_image = get_post_meta($pid, "_hide_image", true);
$youtube = strpos($p_video, 'youtube.com');
$vimeo = strpos($p_video, 'vimeo');
if ( ($youtube || $vimeo) && !$args->force_image ) : ?>
<div class="p_video">
<?php
if ( $youtube ) {
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $p_video, $matches);
echo $args->before.'<iframe width="'.$video_w.'" height="'.$video_h.'" src="http://www.youtube.com/embed/'.$matches[1].'" frameborder="0" allowfullscreen></iframe>'.$args->after;
}
else if ( $vimeo ) {
preg_match('#vimeo.com/([A-Za-z0-9\-_]+)?#s', $p_video, $matches);
echo $args->before.'<iframe src="http://player.vimeo.com/video/'.$matches[1].'?title=0&byline=0&portrait=0" width="'.$video_w.'" height="'.$video_h.'" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>'.$args->after;
}
?>
</div>
<?php endif; ?>
<?php if ( ($has_thumbnail == '' && $hide_image != 'no' && $youtube == false && $vimeo == false)
|| $hide_image != 'no' && $args->force_image == true
) :
$th_id = get_post_thumbnail_id($pid);
$image_src = wp_get_attachment_image_src( $th_id, 'full' );
if ( $args->height == 'proportional' ) {
$th_h = round($video_w/$image_src[1] * $image_src[2]);
} else {
$th_h = $args->height;
}
$image = wpb_resize( $th_id, '', $video_w, $th_h, true );
$html = $args->before . '<img ';
$html .= ( $args->img_class ) ? ' class="'. $args->img_class .'"' : '';
$html .= ' src="'. $image['url'] .'" alt="" />'. $args->after;
if ($image['url'] && $args->echo) :
echo $html;
else:
return $html;
endif; ?>
<?php endif; ?>
<?php
}
}
/* Outputs next/previous links paginator
---------------------------------------------------------- */
if (!function_exists('wpb_next_prev_pagination')) {
function wpb_next_prev_pagination( $args = array() ) {
$defaults = array( 'next_txt' => '', 'prev_txt' => '', 'extra_class' => '' );
$args = wp_parse_args( $args, $defaults );
$args = (object) $args;
global $wp_query;
if ( $wp_query->max_num_pages > 1 ) :
if ($args->next_txt == '') $args->next_txt = '< ' . __('Previous posts', 'wpb_framework');
if ($args->prev_txt == '') $args->prev_txt = __('Next posts', 'wpb_framework') . ' >';
if ($args->extra_class != '') $args->extra_class = ' ' . $args->extra_class;
?>
<div class="wpb_paginator<?php echo $args->extra_class; ?>">
<?php next_posts_link($args->next_txt); previous_posts_link($args->prev_txt); ?><?php //previous == Se tidligere indlæg ?>
</div>
<?php
endif;
}
}
/* Paged paginator
---------------------------------------------------------- */
add_filter('previous_posts_link_attributes', 'previous_posts_link_css' );
function previous_posts_link_css($content) {
return 'class="controls left_control"';
}
add_filter('next_posts_link_attributes', 'next_posts_link_css' );
function next_posts_link_css($content) {
return 'class="right_control"';
}
if ( !function_exists('wpb_pagination') ) {
//Thanks Kriesi for the nice paginator
function wpb_pagination( $pages = '', $range = 10 ) {
$showitems = ($range * 2)+1;
//global $paged;
$paged = get_query_var('paged');
if ( empty($paged) ) $paged = 1;
if ( $pages == '' ) {
global $wp_query;
$pages = $wp_query->max_num_pages;
if ( !$pages ) {
$pages = 1;
}
}
if ( 1 != $pages ) {
echo "<div class='wp-pagenavi'>";
//if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>«</a>";
//if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";
for ( $i=1; $i <= $pages; $i++ ) {
if ( 1 != $pages && ( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )) {
echo ( $paged == $i ) ? "<span class='current'>". $i ."</span>" : "<a href='". get_pagenum_link($i) ."' class='inactive' >". $i ."</a>";
}
}
if ($paged < $pages && $showitems < $pages) previous_posts_link('←');
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) next_posts_link('→');
//if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";
//if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>»</a>";
echo "</div>\n";
}
}
}
/* Receives taxonomy name as argument and returns array
with tags objects
---------------------------------------------------------- */
if ( !function_exists('wpb_tags') ) {
function wpb_tags( $args = array() ) {
$defaults = array( 'pid' => NULL, 'tag_vocab' => '', 'echo' => true, 'before' => '', 'separator' => '', 'after' => '' );
$args = wp_parse_args( $args, $defaults );
$args = (object) $args;
if ($args->pid == NULL) {
global $post;
$pid = $post->ID;
} else {
$pid = $args->pid;
}
if ($args->tag_vocab != '') {
$output = get_the_term_list($pid, $args->tag_vocab, $args->before, $args->separator, $args->after);
} else {
$c_arr = array();
$tags_arr = get_the_tags();
if ($tags_arr) {
foreach($tags_arr as $tag) {
$c_arr[] = $args->before.'' . $tag->name . ''.$args->after;
}
$output = implode($args->separator, $c_arr);
}
}
if ($output and $args->echo) {
echo $output;
} else if ($output) {
return $output;
}
}
}
/*
---------------------------------------------------------- */
if (!function_exists('wpb_get_post_category_names')) {
function wpb_get_post_categories( $args = array() ) {
$defaults = array( 'taxonomy' => '', 'pid' => NULL, 'echo' => TRUE );
$args = wp_parse_args( $args, $defaults );
$args = (object) $args;
if ( $args->pid == NULL ) {
global $post;
$args->pid = $post->ID;
}
if ( $args->taxonomy != '' ) {
$terms = wp_get_object_terms($args->pid, $args->taxonomy);
}
if ( $terms ) {
$term_output = array();
$names = array();
$slugs = array();
foreach ( $terms as $term ) {
$names[] = $term->name;
$slugs[] = $term->slug;
}
$term_output['name'] = array_unique($names);
$term_output['slug'] = array_unique($slugs);
return $term_output;
}
}
}
/* Receives taxonomy name as argument and returns array
with taxonomy objects
---------------------------------------------------------- */
if (!function_exists('wpb_posted_under')) {
function wpb_posted_under( $args = array() ) {
$defaults = array( 'taxonomy' => '', 'pid' => NULL, 'echo' => TRUE, 'separator' => ', ', 'link' => TRUE );
$args = wp_parse_args( $args, $defaults );
$args = (object) $args;
if ($args->pid == NULL) {
global $post;
$args->pid = $post->ID;
}
if ($args->taxonomy != '') {
$terms = wp_get_object_terms($args->pid, $args->taxonomy);
}
else {
$terms = array();
foreach((get_the_category()) as $category) {
//get_category_link($category->cat_ID)
//$category->cat_name
$terms[] = $category;
}
}
if ($terms) {
$term_output = '';
foreach ($terms as $term) {
//$term_output[] = '' . $term->name . '';
if ($args->link) {
$term_output[] = '' . $term->name . '';
}
else {
$term_output[] = $term->name;
}
}
$term_output = implode($args->separator, $term_output);
if ($args->echo) {
echo $term_output;
}
else {
return $term_output;
}
}
}
}
/* Helper function which returs list of site attached images,
and if image is attached to the current post it adds class
'added'
---------------------------------------------------------- */
if (!function_exists('siteAttachedImages')) {
function siteAttachedImages($att_ids = array()) {
$output = '';
global $wpdb;
$media_images = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'attachment' order by ID desc");
foreach($media_images as $image_post) {
$thumb_src = wp_get_attachment_image_src($image_post->ID, 'thumbnail');
$thumb_src = $thumb_src[0];
$class = (in_array($image_post->ID, $att_ids)) ? ' class="added"' : '';
if ($thumb_src) {
$output .= '<li'.$class.'>
<img rel="'.$image_post->ID.'" src="'. $thumb_src .'" alt="'. $img_details[0] .'" />
<span class="img-added">'. __('Added', 'wpb_framework') .'</span>
</li>';
}
}
if ($output != '') {
$output = '<ul class="gallery_widget_img_select">' . $output . '</ul>';
}
return $output;
}
}
/* Helper function. Outputs attached images to the post
in custom meta section.
---------------------------------------------------------- */
if (!function_exists('metaAttachedImages')) {
function metaAttachedImages($att_ids = array()) {
$output = '';
foreach ($att_ids as $img_id) {
$thumb_src = wp_get_attachment_image_src($img_id, 'thumbnail');
$thumb_src = $thumb_src[0];
if ($thumb_src) {
$output .= '<li class="added">
<img rel="'.$img_id.'" src="'. $thumb_src .'" alt="" />
<span class="img-added">'. __('Added', 'wpb_framework') .'</span>
</li>';
}
}
return $output;
}
}
function getTopLevelCategories() {
$topCat = array();
$categories = get_categories('hide_empty=0');
foreach ($categories as $category) {
if ($category->parent == 0) {
$topCat[] = $category->name;
}
}
return $topCat;
}
/* Goldmines from internet
---------------------------------------------------------- */
/* Change Wordpress logo on login screen
---------------------------------------------------------- */
if (!function_exists('wpb_login_head')) {
add_action("login_head", "wpb_login_head");
function wpb_login_head() {
echo "
<style>
body.login #login h1 a {
background: url('".get_bloginfo('template_url')."/images/logotype.png') no-repeat scroll center top transparent;
}
</style>
";
}
}
/*
* Resize images dynamically using wp built in functions
* Victor Teixeira
*
* php 5.2+
*
* Exemplo de uso:
*
* <?php
* $thumb = get_post_thumbnail_id();
* $image = vt_resize( $thumb, '', 140, 110, true );
* ?>
* <img src="<?php echo $image[url]; ?>" width="<?php echo $image[width]; ?>" height="<?php echo $image[height]; ?>" />
*
* #param int $attach_id
* #param string $img_url
* #param int $width
* #param int $height
* #param bool $crop
* #return array
*/
if (!function_exists('wpb_resize')) {
function wpb_resize( $attach_id = null, $img_url = null, $width, $height, $crop = false ) {
// this is an attachment, so we have the ID
if ( $attach_id ) {
$image_src = wp_get_attachment_image_src( $attach_id, 'full' );
$file_path = get_attached_file( $attach_id );
// this is not an attachment, let's use the image url
} else if ( $img_url ) {
$file_path = parse_url( $img_url );
$file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path'];
//$file_path = ltrim( $file_path['path'], '/' );
//$file_path = rtrim( ABSPATH, '/' ).$file_path['path'];
$orig_size = getimagesize( $file_path );
$image_src[0] = $img_url;
$image_src[1] = $orig_size[0];
$image_src[2] = $orig_size[1];
}
$file_info = pathinfo( $file_path );
$extension = '.'. $file_info['extension'];
// the image path without the extension
$no_ext_path = $file_info['dirname'].'/'.$file_info['filename'];
$cropped_img_path = $no_ext_path.'-'.$width.'x'.$height.$extension;
// checking if the file size is larger than the target size
// if it is smaller or the same size, stop right here and return
if ( $image_src[1] > $width || $image_src[2] > $height ) {
// the file is larger, check if the resized version already exists (for $crop = true but will also work for $crop = false if the sizes match)
if ( file_exists( $cropped_img_path ) ) {
$cropped_img_url = str_replace( basename( $image_src[0] ), basename( $cropped_img_path ), $image_src[0] );
$vt_image = array (
'url' => $cropped_img_url,
'width' => $width,
'height' => $height
);
return $vt_image;
}
// $crop = false
if ( $crop == false ) {
// calculate the size proportionaly
$proportional_size = wp_constrain_dimensions( $image_src[1], $image_src[2], $width, $height );
$resized_img_path = $no_ext_path.'-'.$proportional_size[0].'x'.$proportional_size[1].$extension;
// checking if the file already exists
if ( file_exists( $resized_img_path ) ) {
$resized_img_url = str_replace( basename( $image_src[0] ), basename( $resized_img_path ), $image_src[0] );
$vt_image = array (
'url' => $resized_img_url,
'width' => $proportional_size[0],
'height' => $proportional_size[1]
);
return $vt_image;
}
}
// no cache files - let's finally resize it
$new_img_path = image_resize( $file_path, $width, $height, $crop );
if ( is_string($new_img_path) == false ) { return ''; }
$new_img_size = getimagesize( $new_img_path );
$new_img = str_replace( basename( $image_src[0] ), basename( $new_img_path ), $image_src[0] );
// resized output
$vt_image = array (
'url' => $new_img,
'width' => $new_img_size[0],
'height' => $new_img_size[1]
);
return $vt_image;
}
// default output - without resizing
$vt_image = array (
'url' => $image_src[0],
'width' => $image_src[1],
'height' => $image_src[2]
);
return $vt_image;
}
}
/* Returns current page url
---------------------------------------------------------- */
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") { $pageURL .= "s"; }
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
---AND FINALLY THE MASONRY FLUID THEME FILE---
<?php
$def_teaser_width = ( $dtw = get_option('wpb_post_teaser_width') ) ? $dtw : 'two-third';
if ( get_option('wpb_blog_layout') == __("Masonry", "wpb") ) {
$gallery_style = 'masonry';
} else {
$gallery_style = 'fluid';
}
if ( $_GET['style'] == 'masonry' ) {
$gallery_style = 'masonry';
} else if ( $_GET['style'] == 'fluid' ) {
$gallery_style = 'fluid';
}
$holder_class = ( $gallery_style == 'masonry' ) ? 'masonry_blocks' : 'float_blocks';
?>
<?php get_header(); ?>
<div class="float_blocks_container">
<div class="blog_teasers <?php echo $holder_class; ?>">
<?php if (have_posts()) :
$teasers_count = 0;
?>
<?php while (have_posts()) : the_post(); ?>
<?php
$teasers_count++;
$teaser_width = ( $tw = get_post_meta($post->ID, "_teaser_width", true) ) ? $tw : $def_teaser_width;
$teaser_width = ( $teaser_width == 'default' ) ? $def_teaser_width : $teaser_width;
//$teaser_width = ($teaser_w = get_post_meta($post->ID, "_teaser_width", true)) ? ' '.$teaser_w : ' one-half';
if ( $teaser_width == 'one-third' || ( $gallery_style == 'masonry' && $teaser_width == 'one-half' )) {
$th_w = 320;
$th_h = 180;
}
else if ( $teaser_width == 'one-half' ) {
$th_w = 495;
$th_h = 278;
}
else if ( $teaser_width == 'two-third' || ( $gallery_style == 'masonry' && $teaser_width == 'full-width' ) ) {
$th_w = 670;
$th_h = 377;
}
else if ( $teaser_width == 'full-width' ) {
$th_w = 1020;
$th_h = 574;
}
$content_type = (get_option('wpb_full_content') == 'true') ? ' full_content_in_blog' : '';
$has_thumbnail = '';
if (has_post_thumbnail() == false) { $has_thumbnail = ' no_thumbnail'; }
?>
<div id="post-<?php the_ID(); ?>" <?php post_class("post_teaser float_block ".$teaser_width.$has_thumbnail.$content_type); ?>>
<?php
$video_w = $th_w;
$video_h = $th_h;
$p_video = get_post_meta($post->ID, "_p_video", true);
$youtube = strpos($p_video, 'youtube.com');
$vimeo = strpos($p_video, 'vimeo');
if ( $youtube || $vimeo ) : ?>
<div class="p_video">
<?php
if ( $youtube ) {
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $p_video, $matches);
echo '<iframe width="'.$video_w.'" height="'.$video_h.'" src="http://www.youtube.com/embed/'.$matches[1].'" frameborder="0" allowfullscreen></iframe>';
}
else if ( $vimeo ) {
preg_match('#vimeo.com/([A-Za-z0-9\-_]+)?#s', $p_video, $matches);
echo '<iframe src="http://player.vimeo.com/video/'.$matches[1].'?title=0&byline=0&portrait=0" width="'.$video_w.'" height="'.$video_h.'" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>';
}
?>
</div>
<?php endif; ?>
<?php if ( $has_thumbnail == '' && $youtube == false && $vimeo == false) : ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php
$th_id = get_post_thumbnail_id();
$image_src = wp_get_attachment_image_src( $th_id, 'full' );
$th_h = 220;
$image = wpb_resize( $th_id, '', $th_w, $th_h, true );
if ($image['url']) : ?>
<img class="post_teaser_img" src="<?php echo $image['url']; ?>" alt="" />
<?php endif; ?>
</a>
<?php endif; ?>
<div class="teaser_content">
<h2 class="post_title"><?php the_title(); ?></h2>
<div class="post_info">
<span class="light"><?php _e("Posted by", "wpb"); ?></span> <?php the_author(); ?> <span class="light"><?php _e("in", "wpb"); ?></span> <?php wpb_posted_under(); ?> <span class="date"><span class="light"><?php _e("on ", "wpb"); ?></span><?php the_time('F j, Y'); ?></span>
</div>
<?php
if ($content_type == ' full_content_in_blog') {
the_content('');
} else {
the_excerpt('');
}
?>
</div> <!-- end .teaser_content -->
<div class="teaser_meta">
<a class="read_more" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php _e("Read more...", "wpb"); ?></a>
<span class="comment_balloon"><?php comments_popup_link( __( 'Leave a comment', 'wpb' ), __( '1 Comment', 'wpb' ), __( '% Comments', 'wpb' ) ); ?></span>
<div class="social_buttons">
<?php echo do_shortcode('[vc_facebook type="button_count" url="'.get_permalink().'"]'); ?>
<?php echo do_shortcode('[vc_tweetmeme]'); ?>
</div>
<div class="wpb_clear"></div>
</div> <!-- end .teaser_ment -->
</div> <!-- end .post_teaser -->
<?php
endwhile;
endif;
?>
<?php if ( $teasers_count > 1 && $gallery_style != 'masonry') : ?>
<a id="float_prev" class="tooltip" title="<?php _e("Previous post", "wpb"); ?>"></a>
<a id="float_next" class="tooltip" title="<?php _e("Next post", "wpb"); ?>"></a>
<?php endif; ?>
<?php if ( $gallery_style != 'masonry' ) { wpb_pagination(); } ?>
<div class="wpb_clear"></div>
</div> <!-- end main_content -->
<?php
if ( $gallery_style == 'masonry' ) {
echo '<div class="masonry_paginator">';
wpb_pagination();
echo '</div>';
}
?>
<div class="wpb_clear"></div>
</div> <!-- end container_12 -->
<?php get_footer(); ?>

You can solve this by making sure all the excerpts, as the auto-generated short intro-texts are called, are the same length. Also, there is HTML markup in these excerpts, which is not a good idea if you want consistent use of space. So, here we go.
In your theme's functions.php you should add the following:
function my_new_excerpt_length($length) {
return 20;
}
add_filter( 'excerpt_length', 'my_new_excerpt_length', 999 );
Here, my_new_excerpt_length is the custom name of your function. The 20 is the amount of words you would like your excerpt to be. You can tweak these values, of course. Just experiment until it fits your needs.
Note: It might be that the changes are not showing up for you on that specific page. Please post the complete template, so I can take a look at what's happening further down the page.

Related

Place ads after second paragraph of the posts in a specific category

I want to place ads after second paragraph of the posts located under a specific category. For this I am trying to run the following piece of codes but it is not working. Kindly help me out.
//Insert ads after second paragraph of single post content.
$catarray = get_the_category( $post->ID );
foreach ($catarray as $cat) {
$catid = $cat->term_id;
if ($catid == 124);
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Insert Ad code here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
you can use this code for it
add_filter('the_content', 'ak_the_content_filter', 10, 1);
function ak_the_content_filter($content)
{
$catarray = get_the_category( $post->ID );
foreach ($catarray as $cat) {
$catid = $cat->term_id;
if ($catid != 124) { return $content; }
else{
$parags = explode('</p>', $content);
$parags[1] .= '<br>'.do_shortcode('[SHORTCODE HERE]');// add whatever you want after first paragraph
$content_new = '';
foreach ($parags as $parag) {
$content_new .= $parag;
}
return $content_new;
}
}
}

Category slug - Custom post type Wordpress

With custom post type, i need to use category slug for my class (css).
<?php
global $post;
$terms = wp_get_post_terms($post->ID, 'typeresources');
if ($terms) {
$output = array();
foreach ($terms as $term) {
if ($term->term_id != 14)
{
$output[] = '<div class="cat-resources">' .$term->name .'</div>';
}
}
echo join( ' ', $output );
};
?>
Would like to add at my "cat-resources class" the categroy slug
How can i do that ?
There you go.
global $post;
$terms = wp_get_post_terms($post->ID, 'typeresources');
if ($terms) {
$output = array();
foreach ($terms as $term) {
if ($term->term_id != 14) {
$output[] = '<div class="cat-resources '.$term->slug.'">' .$term->name .'</div>';
}
}
echo join( ' ', $output );
};

WordPress page shows shortcodes

My WordPress page shows shortcodes like [vc_row][vc_column][vc_column_text] .
Help me identify the root cause.
I have migrated the wordpress sql files from one host to another.
You could modify this Utility Script Runner script to remove shortcodes that no longer exist but are in your page content. Definitely do this on staging before you do it on live. high likelyhood of wrecking up the place. This script has been sitting for close to a year and I honestly can't remember if any of it doesn't work as expected. test a lot on staging before running this on anything you really care about.
<?php if(!defined('ABSPATH')) { die(); }
/**
* Utility Name: Remove and Flatten Shortcodes
* Description: Strip Shortcodes from all posts, with several processing options
* Supports: input
* Version: 0.0.2
**/
if (!class_exists('StripShortcodes')) {
class StripShortcodes {
var $wrappers = array(),
$swaps = array();
public static function Instance() {
static $instance = null;
if ($instance === null) {
$instance = new self();
}
return $instance;
}
public function __construct() {
add_filter('wp_util_script', array($this, 'strip_shortcodes_run'), 10, 3);
add_filter('wp_util_input_html', array($this, 'strip_shortcodes_input_html'));
}
public function strip_shortcodes_input_html( $html ) {
global $shortcode_tags;
$post_types = get_post_types( array(
'exclude_from_search' => false
), 'names' );
$post_types = array_diff( $post_types, array( 'revision', 'attachment' ) );
?>
<p>
<strong>WARNING! DO NOT RUN THIS ON A LIVE SITE!</strong><br>
This utility may cause data loss. Even restoring a backup may wipe out any changes since the last run of this utility.
</p>
<label>
<input type="checkbox" name="restore" value="restore"/>
<span>Restore From Backup</span>
</label>
<label>
<span>Post Types to Process</span>
<select name="post_types[]" multiple="multiple">
<option value="none" selected="selected">none</option>
<option value="any">all</option>
<?php
foreach( $post_types as $post_type ) {
echo '<option value="' . esc_attr( $post_type ) . '">' . $post_type . '</option>';
}
?>
</select>
</label>
<hr/>
<p>
Select what you would like to do with each shortcode.
</p>
<?php
if( !empty( $shortcode_tags ) ) {
foreach( $shortcode_tags as $tag => $callable ) {
?>
<div class="shortcode-options-wrapper">
<label>
<span>[<?php echo $tag; ?>]</span>
<select class="shortcode-select" name="shortcodes[<?php echo esc_attr( $tag ); ?>]"/>
<option value="skip">Skip (do not process)</option>
<option value="strip">Remove (deletes shortcode content)</option>
<option value="unwrap">Unwrap Content</option>
<option value="parse">Flatten (parses to HTML)</option>
<option value="swap">Swap (Replace with another shortcode)</option>
</select>
</label>
</div>
<?php
}
}
echo $this->build_form_script();
return ob_get_clean();
}
private function build_form_script () {
global $shortcode_tags;
ob_start(); ?>
<script type="text/javascript">
(jQuery)(function($) {
'use strict';
var unwrap = '<div class="wrap-wrapper"><p>Wrapper for content (use "sprintf()" formatting, including the %s for the content)</p><label>Wrapper<input class="shortcode-wrap"></label></div>';
var swap = '<div class="swap-wrapper"><select class="shortcode-swap"><?php foreach ($shortcode_tags as $tag => $callable) { echo '<option value="' . $tag . '">' . esc_attr($tag) . '</option>'; }?></select></div>'
$(document).on('change', '.shortcode-select', function () {
var $this = $(this);
var name = $this.attr('name');
if ($this.val() == 'unwrap') {
$this.closest('.shortcode-options-wrapper').append(unwrap);
$this.closest('.shortcode-options-wrapper').find('.shortcode-wrap').attr('name', 'wrap_' + name);
$this.closest('.shortcode-options-wrapper').find('.swap-wrapper').remove();
}
else if ($this.val() == 'swap') {
$this.closest('.shortcode-options-wrapper').append(swap);
$this.closest('.shortcode-options-wrapper').find('.shortcode-swap').attr('name', 'swap_' + name);
$this.closest('.shortcode-options-wrapper').find('.wrap-wrapper').remove();
} else {
$this.closest('.shortcode-options-wrapper').find('.wrap-wrapper').remove();
$this.closest('.shortcode-options-wrapper').find('.swap-wrapper').remove();
}
})
});
</script>
<?php return ob_get_clean();
}
public function strip_shortcodes_run( $legacy, $state, $atts ) {
$batch = 10;
$offset = 0;
if( !empty( $state['offset'] ) ) {
$offset = $state['offset'];
}
$result = array(
'state' => 'error',
'message' => 'an unknown error has occurred',
);
$post_types = 'none';
if( !empty( $atts['post_types'] ) && !in_array( 'none', $atts['post_types'] ) ) {
$post_types = $atts['post_types'];
}
$shortcode_settings = array();
if( !empty( $atts['shortcodes'] ) ) {
$shortcode_settings['core'] = $atts['shortcodes'];
$shortcode_settings['wrap'] = $atts['wrap_shortcodes'];
$shortcode_settings['swap'] = $atts['swap_shortcodes'];
}
$restore = true;
if( empty( $atts['restore'] ) ) {
$this->replace_shortcode_functions( $shortcode_settings );
$restore = false;
}
$query = new WP_Query( array(
'posts_per_page' => $batch,
'offset' => $offset,
'post_type' => $post_types
) );
if( !$query->have_posts() ) {
$result = array(
'state' => 'complete',
'message' => 'successfully processed all posts'
);
} else {
$offset += $query->post_count;
while( $query->have_posts() ) {
$query->the_post();
$post = get_post();
$backup = get_post_meta( $post->ID, 'flatten_shortcodes_backup', true );
if( $restore ) {
if( $backup ) {
$post->post_content = $backup;
wp_update_post( $post );
delete_post_meta( $post->ID, 'flatten_shortcodes_backup' );
}
} else {
if( !$backup ) {
update_post_meta( $post->ID, 'flatten_shortcodes_backup', $post->post_content );
}
$post->post_content = do_shortcode( $post->post_content );
wp_update_post( $post );
}
}
$result = array(
'state' => array(
'offset' => $offset
),
'message' => $offset . ' posts processed'
);
}
return $result;
}
private function replace_shortcode_functions( $settings = array() ) {
global $shortcode_tags;
foreach( $shortcode_tags as $tag => $callable ) {
$setting = 'skip';
if( !empty( $settings['core'][$tag] ) ) {
$setting = $settings['core'][$tag];
}
switch( $setting ) {
case 'strip' :
$shortcode_tags[$tag] = "__return_empty_string";
break;
case 'unwrap':
$shortcode_tags[$tag] = array($this, 'replace_shortcode_unwrap');
$this->wrappers[$tag] = $settings['wrap'][$tag];
break;
case 'parse' :
// nothing needed
break;
case 'swap' :
$shortcode_tags[$tag] = array($this, 'swap_shortcode');
$this->swaps[$tag] = $settings['swap'][$tag];
break;
case 'skip' :
default :
unset( $shortcode_tags[$tag] );
}
}
}
public function replace_shortcode_unwrap( $atts=array(), $content='', $tag ) {
return sprintf($this->wrappers[$tag], $content);
}
public function swap_shortcode( $atts=array(), $content='', $tag ) {
$attString = '';
$newTag = $this->swaps[$tag];
if (!empty($atts)) {
foreach ($atts as $key => $att) {
$attString .= ' ' . $key . '="' . $att . '"';
}
}
$output = '[' . $newTag . $attString . ']';
if ($content) {
$output .= $content . '[/' . $newTag . ']';
}
return $output;
}
}
StripShortcodes::Instance();
}
I have got same result. My theme is wp baker. I activated edge core plugin and other required plug ins and it was solved.

WP shortcode output always at top of page

When placing a shortcode on a custom WordPress page the output is always displayed at the top of my page content.
I found out that the problem can be fixed by either using return instead of echo, or by using output buffering: (ob_start() / ob_get_contents())
Unfortunately my coding skills are not what I would like them to be.. And I don't know exactly where to implement these fixes.
Can someone help me out please? The plugin developer is not responding to my mails and I need to get this to work a.s.a.p.
I assume this needs to be implemented in the faulty plugin's functions file so I added it below.
<?php
/**
* Woocommerce Category Accordion Functions
*
* #author TechieResource
* #category Shortcode
* #package woocommerce-category-accordion/inc
* #version 1.2.1
*/
/**
/* Clean variables
*
* #param string $var
* #return string
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
class trwca_wc_category_accordion{
/**
* Constructor
*/
private $shortcode_tag = "WC-Category-Accordion";
public function __construct() {
add_action( 'woocommerce_category_accordion', array( $this, 'woocommerce_category_accordion_func' ), 10, 2 );
add_shortcode( $this->shortcode_tag, array( $this, 'wc_category_accordion_sc' ) );
if ( is_admin() ){
add_action('admin_head', array( $this, 'admin_head') );
add_action( 'admin_enqueue_scripts', array($this , 'admin_enqueue_scripts' ) );
}
}
/**
* Display the Woocommerce Category Accordion.
* #since 1.2.1
* #param array $instance Arguments.
* #param bool $echo Whether to display or return the output.
* #return string
*/
public function woocommerce_category_accordion_func( $instance, $echo = true ) {
extract( $instance, EXTR_SKIP );
global $wp_query;
global $post, $product;
$exclude_tree = esc_attr($exclude_tree );
$hide_empty = esc_attr($hide_empty );
$show_count = esc_attr($show_count );
$open_cat = esc_attr($open_cat );
$ac_speed = esc_attr($ac_speed );
$ac_type = esc_attr($ac_type );
$event_type = esc_attr($event_type );
$ac_icon = esc_attr($ac_icon );
$sortby = esc_attr($sortby );
$ac_theme = esc_attr($ac_theme );
$order = esc_attr($order );
$level = esc_attr($level );
$cats_id = esc_attr($ac_opencat);
$disable_parent = esc_attr($disable_parent);
$disable_aclink = esc_attr($disable_aclink);
if(!empty($instance['id'])){
$widgetid= $instance['id'];
}
else{
if($sh_id!=""){
$widgetid= "wc_category_accordion-".$sh_id;
}
else{
$widgetid= "wc_category_accordion-".$this->trwca_generate_random_code(3);
}
}
$instance_categories = get_terms( 'product_cat', '&parent=0&exclude='.$exclude_tree.'');
if (is_array($instance_categories)) {
foreach($instance_categories as $categories) {
$term_id[] = $categories->term_id;
$term_name = $categories->name;
}
}
if(!empty($post->ID)){
$terms =get_the_terms( $post->ID, 'product_cat' );
}
else {
$terms="";
}
if (is_array($terms )) {
foreach ( $terms as $term) {
$_cat=$term->term_id;
break;
}
}
/* For current category highlight */
if(is_product()){
$current_cat= array();
$cat = $wp_query->get_queried_object();
if (!empty($cat->term_id))
{
$current_cat = $cat->term_id;
}
else{
$_cat_id="1";
if (isset($term->term_id))
{
$_cat=$term->term_id;
$_cat_id = !empty($_cat) ? $_cat_id=$_cat : $_cat_id=1 ;
}
if (is_shop())
{
$_cat_id="1";
}
if (!is_shop()){
if (is_array($terms )) {
foreach($terms as $term){
$myterms[]= $term->term_id;
}
$cats_id=end($myterms);
?>
<script type="text/javascript">
var cats_id= <?php return end($myterms); ?>;
</script>
<style type="text/css">
<?php foreach((get_the_terms($post->ID, 'product_cat')) as $term) {
$myterms= $term->term_id;
return 'ul.'.$widgetid.' li.cat-item-'.$myterms.' > a{font-weight:bold;}';
}
}
}
?>
</style>
<?php
}
}
$cat = $wp_query->get_queried_object();
if (!empty($cat->term_id) && !is_product() ){
$cats_id = $cat->term_id;
return '<script type="text/javascript">
var cats_id= '.$cats_id.';
</script>';
}
else if(!is_product_category() && !is_product()){
$cats_id=$ac_opencat;
}
$ac_type = $ac_type=="toggle" ? $ac_type= "true" : $ac_type= "false";
$open_cat = $open_cat== true || $open_cat =='on' ? $open_cat=true : $open_cat=false;
/* Icon Selection */
switch ($ac_icon) {
case 'angle' :
$open_icon="angle-down";
$close_icon="angle-right";
break;
case 'doubleangle' :
$open_icon="angle-double-down";
$close_icon="angle-double-right";
break;
case 'arrow-circle1' :
$open_icon="arrow-circle-down";
$close_icon="arrow-circle-right";
break;
case 'arrow-circle2' :
$open_icon="arrow-circle-o-down";
$close_icon="arrow-circle-o-right";
break;
case 'arrow-right' :
$open_icon="arrow-down";
$close_icon="arrow-right";
break;
case 'caret' :
$open_icon="caret-down";
$close_icon="caret-right";
break;
case 'caret-square' :
$open_icon="caret-square-o-down";
$close_icon="caret-square-o-right";
break;
case 'chevron' :
$open_icon="chevron-down";
$close_icon="chevron-right";
break;
case 'chevron-circle' :
$open_icon="chevron-circle-down";
$close_icon="chevron-circle-right";
break;
case 'hand' :
$open_icon="hand-o-down";
$close_icon="hand-o-right";
break;
case 'plus' :
$open_icon="minus";
$close_icon="plus";
break;
case 'plus-circle' :
$open_icon="minus-circle";
$close_icon="plus-circle";
break;
case 'plus-square1' :
$open_icon="minus-square";
$close_icon="plus-square";
break;
case 'plus-square2' :
$open_icon="minus-square-o";
$close_icon="plus-square-o";
break;
}
if($disable_aclink==true){
$disable_aclink='true';
}
else if($disable_aclink==""){
$disable_aclink= 'false';
}
if($disable_parent==true){
$disable_parent='true';
}
else if($disable_parent==""){
$disable_parent='false';
}
$cats_id= empty($cats_id) ? 1 : $cats_id;
?>
<script type="text/javascript">
var $=jQuery.noConflict();
$(document).ready(function($){
$('.<?php echo $widgetid; ?>').trwcAccordion({
classParent : 'trwca-parent',
classActive : 'active',
classArrow : 'trwca-icon',
classCount : 'trwca-count',
classExpand : 'trwca-current-parent',
eventType : '<?php echo $event_type; ?>',
hoverDelay : 100,
menuClose : true,
cats_id: <?php echo $cats_id; ?>,
ac_type : <?php echo $ac_type; ?>,
autoExpand : true,
speed : '<?php echo $ac_speed ?>',
saveState : '<?php echo $open_cat; ?>',
disableLink : <?php echo $disable_aclink; ?>,
disableparentLink : <?php echo $disable_parent; ?>,
auto_open: 1,
showCount : true,
widget_id : "<?php echo $widgetid; ?>",
openIcon : '<?php echo $open_icon; ?>',
closeIcon : '<?php echo $close_icon; ?>',
});
});
</script>
<div class="block-content trwca-actheme <?php echo $ac_theme; ?>">
<div class="trwca-loader"></div>
<ul class="<?php echo $widgetid; ?> accordion" id="outer_ul">
<?php
$subcat_args = array(
'taxonomy' => 'product_cat',
'title_li' => '',
'orderby' => $sortby,
'order' => $order,
'depth' => $level,
'show_count' => $show_count,
'hide_empty' => $hide_empty,
'use_desc_for_title' => 1,
'echo' => false,
'exclude' => $exclude_tree,
'hierarchical' => true ,
'show_option_none' => __('No Categories Found','trwca'),
'link_after' => '',
'walker'=> new trwca_walker
);
?>
<?php $subcategories = wp_list_categories( $subcat_args );
$subcategories=preg_replace_callback(
'/<\/a> \(([0-9]+)\)/',
function ($matches) {
return ' <span class="count">('.($matches[1]).')</span></a>';
},$subcategories
);
?>
<?php if ( $subcategories ) {
echo $subcategories;
}
?>
</ul>
</div>
<?php
}
public function trwca_generate_random_code($length=3) {
$string = '';
$characters = "123456789";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $string;
}
/**
* admin_head
* calls your functions into the correct filters
* #return void
*/
function admin_head() {
// check user permissions
if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) {
return;
}
// check if WYSIWYG is enabled
if ( 'true' == get_user_option( 'rich_editing' ) ) {
add_filter( 'mce_external_plugins', array( $this ,'mce_external_plugins' ) );
add_filter( 'mce_buttons', array($this, 'mce_buttons' ) );
}
}
/**
* mce_external_plugins
* Adds our tinymce plugin
* #param array $plugin_array
* #return array
*/
function mce_external_plugins( $plugin_array ) {
$plugin_array['WC_Category_Accordion'] = plugins_url( 'admin/js/mce-button.js' , __FILE__ );
return $plugin_array;
}
/**
* mce_buttons
* Adds our tinymce button
* #param array $buttons
* #return array
*/
function mce_buttons( $buttons ) {
array_push( $buttons, 'WC_Category_Accordion' );
return $buttons;
}
/**
* admin_enqueue_scripts
* Used to enqueue custom styles
* #return void
*/
function admin_enqueue_scripts(){
wp_enqueue_style('WC-Category-Accordion-sh', plugins_url( 'admin/css/mce-button.css' , __FILE__ ) );
}
public function wc_category_accordion_sc( $atts, $content = null ) {
$defaults = array(
'show_count' => 0,
'ac_speed' => 'fast',
'exclude_tree' =>'',
'hide_empty' => 0,
'sortby' =>'name',
'order' =>'ASC',
'level' => 0,
'event_type' => 'click',
'ac_type' => 'toggle',
'open_cat' => 0,
'ac_opencat' => 1,
'ac_icon' =>'plus',
'disable_parent' => 0,
'disable_aclink' => 0,
'ac_theme' => '',
'sh_id'=> '' );
$settings = shortcode_atts( $defaults, $atts );
return $this->woocommerce_category_accordion_func( $settings, false );
}
}
new trwca_wc_category_accordion();
function trwca_clean( $var ) {
return sanitize_text_field( $var );
}
}
?>
Thank you guys!
function your_shortcode_function(){
ob_start(); ?>
<div>
// all your stuffs here
</div>
<?php
$contents=ob_get_contents();
ob_end_clean();
return $contents;
}
add_shortcode('your_shortcode', 'your_shortcode_function');
You need ob_start and ob_end_clean() as said as above OUTPUT BUFFERING
You'll want to use ob_start() and return ob_get_clean() inside the shortcode function.
Likeso:
<?php
function my_shortcode(){ // The function that is our shortode output.
ob_start();?>
<div class="my-shortcode-output">
<em>I'm <strong>the best</strong></em>
</div>
<?php
return $ob_get_clean();
}
add_shortcode( 'my-shortcode', 'my_shortcode' );
I'd also consider not echoing js from your php, using wp_enque_script and wp_localize_script is much nicer.
This should work.
<?php
/**
* Woocommerce Category Accordion Functions
*
* #author TechieResource
* #category Shortcode
* #package woocommerce-category-accordion/inc
* #version 1.2.1
*/
/**
/* Clean variables
*
* #param string $var
* #return string
*/
if (!defined('ABSPATH')) {
exit;
} // Exit if accessed directly
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
class trwca_wc_category_accordion
{
/**
* Constructor
*/
private $shortcode_tag = "WC-Category-Accordion";
public function __construct()
{
add_action('woocommerce_category_accordion', array(
$this,
'woocommerce_category_accordion_func'
), 10, 2);
add_shortcode($this->shortcode_tag, array(
$this,
'wc_category_accordion_sc'
));
if (is_admin()) {
add_action('admin_head', array(
$this,
'admin_head'
));
add_action('admin_enqueue_scripts', array(
$this,
'admin_enqueue_scripts'
));
}
}
/**
* Display the Woocommerce Category Accordion.
* #since 1.2.1
* #param array $instance Arguments.
* #param bool $echo Whether to display or return the output.
* #return string
*/
public function woocommerce_category_accordion_func($instance, $echo = true)
{
ob_start();
extract($instance, EXTR_SKIP);
global $wp_query;
global $post, $product;
$exclude_tree = esc_attr($exclude_tree);
$hide_empty = esc_attr($hide_empty);
$show_count = esc_attr($show_count);
$open_cat = esc_attr($open_cat);
$ac_speed = esc_attr($ac_speed);
$ac_type = esc_attr($ac_type);
$event_type = esc_attr($event_type);
$ac_icon = esc_attr($ac_icon);
$sortby = esc_attr($sortby);
$ac_theme = esc_attr($ac_theme);
$order = esc_attr($order);
$level = esc_attr($level);
$cats_id = esc_attr($ac_opencat);
$disable_parent = esc_attr($disable_parent);
$disable_aclink = esc_attr($disable_aclink);
if (!empty($instance['id'])) {
$widgetid = $instance['id'];
} else {
if ($sh_id != "") {
$widgetid = "wc_category_accordion-" . $sh_id;
} else {
$widgetid = "wc_category_accordion-" . $this->trwca_generate_random_code(3);
}
}
$instance_categories = get_terms('product_cat', '&parent=0&exclude=' . $exclude_tree . '');
if (is_array($instance_categories)) {
foreach ($instance_categories as $categories) {
$term_id[] = $categories->term_id;
$term_name = $categories->name;
}
}
if (!empty($post->ID)) {
$terms = get_the_terms($post->ID, 'product_cat');
} else {
$terms = "";
}
if (is_array($terms)) {
foreach ($terms as $term) {
$_cat = $term->term_id;
break;
}
}
/* For current category highlight */
if (is_product()) {
$current_cat = array();
$cat = $wp_query->get_queried_object();
if (!empty($cat->term_id)) {
$current_cat = $cat->term_id;
} else {
$_cat_id = "1";
if (isset($term->term_id)) {
$_cat = $term->term_id;
$_cat_id = !empty($_cat) ? $_cat_id = $_cat : $_cat_id = 1;
}
if (is_shop()) {
$_cat_id = "1";
}
if (!is_shop()) {
if (is_array($terms)) {
foreach ($terms as $term) {
$myterms[] = $term->term_id;
}
$cats_id = end($myterms);
?>
<script type="text/javascript">
var cats_id= <?php
return end($myterms);
?>;
</script>
<style type="text/css">
<?php
foreach ((get_the_terms($post->ID, 'product_cat')) as $term) {
$myterms = $term->term_id;
return 'ul.' . $widgetid . ' li.cat-item-' . $myterms . ' > a{font-weight:bold;}';
}
}
}
?>
</style>
<?php
}
}
$cat = $wp_query->get_queried_object();
if (!empty($cat->term_id) && !is_product()) {
$cats_id = $cat->term_id;
return '<script type="text/javascript">
var cats_id= ' . $cats_id . ';
</script>';
} else if (!is_product_category() && !is_product()) {
$cats_id = $ac_opencat;
}
$ac_type = $ac_type == "toggle" ? $ac_type = "true" : $ac_type = "false";
$open_cat = $open_cat == true || $open_cat == 'on' ? $open_cat = true : $open_cat = false;
/* Icon Selection */
switch ($ac_icon) {
case 'angle':
$open_icon = "angle-down";
$close_icon = "angle-right";
break;
case 'doubleangle':
$open_icon = "angle-double-down";
$close_icon = "angle-double-right";
break;
case 'arrow-circle1':
$open_icon = "arrow-circle-down";
$close_icon = "arrow-circle-right";
break;
case 'arrow-circle2':
$open_icon = "arrow-circle-o-down";
$close_icon = "arrow-circle-o-right";
break;
case 'arrow-right':
$open_icon = "arrow-down";
$close_icon = "arrow-right";
break;
case 'caret':
$open_icon = "caret-down";
$close_icon = "caret-right";
break;
case 'caret-square':
$open_icon = "caret-square-o-down";
$close_icon = "caret-square-o-right";
break;
case 'chevron':
$open_icon = "chevron-down";
$close_icon = "chevron-right";
break;
case 'chevron-circle':
$open_icon = "chevron-circle-down";
$close_icon = "chevron-circle-right";
break;
case 'hand':
$open_icon = "hand-o-down";
$close_icon = "hand-o-right";
break;
case 'plus':
$open_icon = "minus";
$close_icon = "plus";
break;
case 'plus-circle':
$open_icon = "minus-circle";
$close_icon = "plus-circle";
break;
case 'plus-square1':
$open_icon = "minus-square";
$close_icon = "plus-square";
break;
case 'plus-square2':
$open_icon = "minus-square-o";
$close_icon = "plus-square-o";
break;
}
if ($disable_aclink == true) {
$disable_aclink = 'true';
} else if ($disable_aclink == "") {
$disable_aclink = 'false';
}
if ($disable_parent == true) {
$disable_parent = 'true';
} else if ($disable_parent == "") {
$disable_parent = 'false';
}
$cats_id = empty($cats_id) ? 1 : $cats_id;
?>
<script type="text/javascript">
var $=jQuery.noConflict();
$(document).ready(function($){
$('.<?php
echo $widgetid;
?>').trwcAccordion({
classParent : 'trwca-parent',
classActive : 'active',
classArrow : 'trwca-icon',
classCount : 'trwca-count',
classExpand : 'trwca-current-parent',
eventType : '<?php
echo $event_type;
?>',
hoverDelay : 100,
menuClose : true,
cats_id: <?php
echo $cats_id;
?>,
ac_type : <?php
echo $ac_type;
?>,
autoExpand : true,
speed : '<?php
echo $ac_speed;
?>',
saveState : '<?php
echo $open_cat;
?>',
disableLink : <?php
echo $disable_aclink;
?>,
disableparentLink : <?php
echo $disable_parent;
?>,
auto_open: 1,
showCount : true,
widget_id : "<?php
echo $widgetid;
?>",
openIcon : '<?php
echo $open_icon;
?>',
closeIcon : '<?php
echo $close_icon;
?>',
});
});
</script>
<div class="block-content trwca-actheme <?php
echo $ac_theme;
?>">
<div class="trwca-loader"></div>
<ul class="<?php
echo $widgetid;
?> accordion" id="outer_ul">
<?php
$subcat_args = array(
'taxonomy' => 'product_cat',
'title_li' => '',
'orderby' => $sortby,
'order' => $order,
'depth' => $level,
'show_count' => $show_count,
'hide_empty' => $hide_empty,
'use_desc_for_title' => 1,
'echo' => false,
'exclude' => $exclude_tree,
'hierarchical' => true,
'show_option_none' => __('No Categories Found', 'trwca'),
'link_after' => '',
'walker' => new trwca_walker
);
$subcategories = wp_list_categories($subcat_args);
$subcategories = preg_replace_callback('/<\/a> \(([0-9]+)\)/', function($matches)
{
return ' <span class="count">(' . ($matches[1]) . ')</span></a>';
}, $subcategories);
if ($subcategories) {
echo $subcategories;
}
?>
</ul>
</div>
<?php
$contents=ob_get_contents();
ob_end_clean();
return $contents;
}
public function trwca_generate_random_code($length = 3)
{
$string = '';
$characters = "123456789";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
return $string;
}
/**
* admin_head
* calls your functions into the correct filters
* #return void
*/
function admin_head()
{
// check user permissions
if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) {
return;
}
// check if WYSIWYG is enabled
if ('true' == get_user_option('rich_editing')) {
add_filter('mce_external_plugins', array(
$this,
'mce_external_plugins'
));
add_filter('mce_buttons', array(
$this,
'mce_buttons'
));
}
}
/**
* mce_external_plugins
* Adds our tinymce plugin
* #param array $plugin_array
* #return array
*/
function mce_external_plugins($plugin_array)
{
$plugin_array['WC_Category_Accordion'] = plugins_url('admin/js/mce-button.js', __FILE__);
return $plugin_array;
}
/**
* mce_buttons
* Adds our tinymce button
* #param array $buttons
* #return array
*/
function mce_buttons($buttons)
{
array_push($buttons, 'WC_Category_Accordion');
return $buttons;
}
/**
* admin_enqueue_scripts
* Used to enqueue custom styles
* #return void
*/
function admin_enqueue_scripts()
{
wp_enqueue_style('WC-Category-Accordion-sh', plugins_url('admin/css/mce-button.css', __FILE__));
}
public function wc_category_accordion_sc($atts, $content = null)
{
$defaults = array(
'show_count' => 0,
'ac_speed' => 'fast',
'exclude_tree' => '',
'hide_empty' => 0,
'sortby' => 'name',
'order' => 'ASC',
'level' => 0,
'event_type' => 'click',
'ac_type' => 'toggle',
'open_cat' => 0,
'ac_opencat' => 1,
'ac_icon' => 'plus',
'disable_parent' => 0,
'disable_aclink' => 0,
'ac_theme' => '',
'sh_id' => ''
);
$settings = shortcode_atts($defaults, $atts);
return $this->woocommerce_category_accordion_func($settings, false);
}
}
new trwca_wc_category_accordion();
function trwca_clean($var)
{
return sanitize_text_field($var);
}
}
?>

Insert content after x img tag

My code counts p tags, then insert ads code after x-th p tag.
If I want to count img tags, then insert ads code after x-th img tag how should I do it?
add_filter( 'the_content', 'prefix_insert_post_ads2' );
function prefix_insert_post_ads2( $content ) {
$imgs = preg_match_all("#<img.+>#U", $content, $matches);
$ad_codea = "ads code";
if ( is_single() && ! is_admin() && $imgs >= 4) {
return prefix_insert_after_paragraph2( $ad_codea, 3, $content );
}
return $content;
}
function prefix_insert_after_paragraph2( $insertion, $paragraph_id, $content ) {
$closing_p = '></p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
I have solved by myself.
add_filter( 'the_content', 'prefix_insert_post_ads2' );
function prefix_insert_post_ads2( $content ) {
$imgs = preg_match_all("#<img.+>#U", $content, $matches);
preg_match_all('/<img[^>]+>/i',$content, $result);
$ad_codea = '123';
if ($imgs < 4 ) {$result[0][1]='';}
if ( is_single() && ! is_admin()) {
return str_replace($result[0][1], $result[0][1].$ad_codea, $content);
}
}

Resources