What is the best approach for a shortcode to get its output from another function. echo works but it generate the shortcode before all content. before ending file there is a php switch that I am loading different functions in base of which style selected. This is the function:
staticMarkup($titleRendered, $contentRendered, $feedbackRendered, $roleRendered, $companyRendered, $image_urlRendered, $slider, $color);
<?php
add_shortcode('sample', 'sample_shortcode');
function sample_shortcode($atts)
{
global $tesio;
$markup = '';
// Attributes
$atts = shortcode_atts(array(
'style' => '',
'testio_id' => '',
'slider' => '',
'colors' => '',
'color' => '',
'wide' => 'no',
'bgcolor' => '',
'dpadding' => '',
'tpadding' => '',
'spadding' => '',
'instance' => 1
) , $atts);
wp_enqueue_script('testio-front-js');
wp_localize_script('testio-front-js', 'testio_var', $atts);
$testio_id = $explodeID = $style = $slider = $colors = $bgcolor = $vpadding = $color = $wide = $colorContrast = '';
$testio_id = $atts['testio_id'];
$explodeID = explode(',', $testio_id);
$style = $atts['style'];
$slider = $atts['slider'];
$colors = $atts['colors'];
$bgcolor = $atts['bgcolor'];
$dpadding = $atts['dpadding'];
$tpadding = $atts['tpadding'];
$spadding = $atts['spadding'];
$color = $atts['color'];
$wide = $atts['wide'];
$testioAmount = count(explode(',', $testio_id));
if (!empty($colors))
{
$colors = explode(',', $colors);
}
if (!empty($bgcolor))
{
$colorContrast = getContrast50($bgcolor);
}
static $uniqueID;
if ($testio_id !== '')
{
if ($testio_id == 'all')
{
$args = array(
'post_type' => 'testio_wp',
'post_status' => 'publish',
'posts_per_page' => - 1
);
}
else
if ($testioAmount > 1)
{
$args = array(
'post_type' => 'testio_wp',
'post_status' => 'publish',
'post__in' => $explodeID,
'posts_per_page' => $testioAmount,
'orderby' => 'post__in'
);
}
else
if ($testioAmount == 1)
{
$args = array(
'post_type' => 'testio_wp',
'post_status' => 'publish',
'p' => $testio_id,
'posts_per_page' => 1
);
}
$posts = get_posts($args);
$wrapperClass = 'staticWrap';
$wideClass = '';
$sliderClass = '';
$masonryContainer = '';
$masonryContainerClose = '';
$backgroundStyle = '';
$sliderMarkup = '';
$sliderCloseMarkup = '';
$wrapperClassExtra = '';
$dataAttr = 'data-padding = ' . $dpadding . ',' . $tpadding . ',' . $spadding;
switch ($style)
{
case 'static':
if ($wide == 'yes')
{
$wideClass = ' wide';
}
default:
break;
}
if ($testioAmount == 1)
{
$slider == 'no';
$sliderContainer = '';
}
$markup.= '<div class="testioWrap ' . $wrapperClass . $wrapperClassExtra . '" ' . $backgroundStyle . ' data-id="' . $wrapperClass . $uniqueID . '" ' . $dataAttr . '>';
$markup.= $sliderMarkup;
$markup.= $masonryContainer;
$x = 0;
$colorClass = '';
$postCount = '';
foreach($posts as $post)
{
$titleRendered = $post->post_title;
$contentRendered = $post->post_content;
$idRendered = $post->ID;
$feedbackRendered = get_field('testio_rate', $idRendered);
$roleRendered = get_field('testio_role', $idRendered);
$companyRendered = get_field('testio_company', $idRendered);
$image_urlRendered = get_the_post_thumbnail($idRendered, 'thumbnail');
if (!empty($colors))
{
$colorClass = $colors[$x % 5];
}
$x++;
$postCount++;
$freeMessage = '<div class="testio-notice"> Please get the pro version to unlock ' . $style . ' style Upgrade</div>';
switch ($style)
{
case "static":
staticMarkup($titleRendered, $contentRendered, $feedbackRendered, $roleRendered, $companyRendered, $image_urlRendered, $slider, $color);
default:
break;
}
}
$markup.= $masonryContainerClose;
$markup.= $sliderCloseMarkup;
$markup.= '</div>';
return $markup;
}
else
{
$markup.= '<div class="testio">';
$markup.= __('Please put an id to the shortcode', 'testio-wp');
$markup.= '</div>';
}
$uniqueID++;
}
?>
This is the codes inside the staticMarkup function:
<?php
function staticMarkup($title, $content, $feedback, $role, $company, $image_url, $slider, $color){
$markup ='';
$colorStyle = 'style="color: '.$color.';"';
if($slider == 'yes'){
$markup .= '<div>';
}
$markup .= '<div class="testio testioStatic" data-color="'.$color.'">';
$markup .= '<div class="leftBorder"></div>';
if($image_url !== '' ){
$markup .= '<div class="thumbnailWrapper">';
$markup .= $image_url;
$markup .= '</div>';
}
$markup .= feedbackMarkup($feedback);
$markup .= '<div class="testio-content">';
$markup .= '<p>'.$content.'</p>';
$markup .= '</div>';
$markup .= '<h3 class="testio-name" '.$colorStyle.'>~ ' .$title. '</h3>';
$markup .= '<h4 class="testio-role">' .$role. ' <span class="role-divider icon-at-sign"></span> ' .$company. '</h4>';
$markup .= '</div>';
if($slider == 'yes'){
$markup .= '</div>';
}
echo $markup;
}
?>
Within the staticMarkup function replace:
echo $markup;
with:
return $markup;
This will return the variable where it has been positioned/called as opposed to above all content.
Related
I am trying to figure out a Jupiter theme blog > components > blog-similar-posts.php code. I would like to show Related Posts instead of Recent Posts on the blog pages. What should I change in the following codes?
Here is the original code I have, thanks! I think I couldn't figure out the logistic between the $recent and $related. There might be something I changed wrong during the process
<?php
global $post, $mk_options;
if ($mk_options['enable_single_related_posts'] == 'true' && get_post_meta($post->ID, '_disable_related_posts', true) != 'false') :
$backup = $post;
$tags = wp_get_post_tags($post->ID);
$tagIDs = array();
$related_post_found = false;
$layout = get_post_meta($post->ID, '_layout', true);
$layout = !empty($layout) ? $layout : 'full';
$layout = ($layout == 'default') ? $mk_options['single_layout'] : $layout;
if ($layout == 'full') {
$showposts = 3; /* 4 before */
$width = ($mk_options['grid_width'] / 3 /* 4 before */) - 30;
$height = ($mk_options['grid_width'] / 3 /* 4 before */) - 80;
$column_css = 'three-cols' /* four-cols before */;
}
else {
$showposts = 3;
$width = (($mk_options['content_width'] / 100) * $mk_options['grid_width']) / 3;
$height = ((($mk_options['content_width'] / 100) * $mk_options['grid_width']) / 3) - 40;
$column_css = 'three-cols';
}
if (!function_exists('mk_similar_posts_html')) {
function mk_similar_posts_html($title, $width, $height, $column_css, $query) {
$output = '<section class="blog-similar-posts">';
$output.= '<div class="similar-post-title">' . esc_html( $title ) . '</div>';
$output.= '<ul class="' . esc_attr( $column_css ) . '">';
while ($query->have_posts()) {
$query->the_post();
$output.= '<li><div class="similar-post-holder">';
$output.= '<a class="mk-similiar-thumbnail" href="' . esc_url( get_permalink() ) . '" title="' . the_title_attribute(array('echo' => false)) . '">';
if ( class_exists( 'Jupiter_Donut' ) ) {
$image_src = Mk_Image_Resize::resize_by_id_adaptive( get_post_thumbnail_id(), 'crop', $width, $height, $crop = true, $dummy = true);
$output.= '<img src="' . $image_src['dummy'] . '" ' . $image_src['data-set'] . ' alt="' . the_title_attribute(array('echo' => false)) . '" />';
}
$output.= '<div class="image-hover-overlay"></div></a>';
$output.= '' . get_the_title() . '';
$output.= '</div></li>';
}
$output.= '</ul>';
$output.= '<div class="clearboth"></div></section>';
echo $output;
}
}
if ($tags) {
$tagcount = count($tags);
for ($i = 0; $i < $tagcount; $i++) {
$tagIDs[$i] = $tags[$i]->term_id;
}
$related = new WP_Query(array(
'tag__in' => $tagIDs,
'post__not_in' => array(
$post->ID
) ,
'showposts' => $showposts,
'ignore_sticky_posts' => 1
));
$output = '';
if ($related->have_posts()) {
$related_post_found = true;
mk_similar_posts_html( esc_html__( 'Recommended Posts', 'mk_framework' ) , $width, $height, $column_css, $related);
}
$post = $backup;
}
if (!$related_post_found) {
$recent = new WP_Query(array(
'showposts' => $showposts,
'nopaging' => 0,
'post__not_in' => array(
$post->ID
),
'post_status' => 'publish',
'ignore_sticky_posts' => 1
));
$output = '';
if ($recent->have_posts()) {
$related_post_found = true;
mk_similar_posts_html( esc_html__( 'Recent Posts', 'mk_framework' ) , $width, $height, $column_css, $recent );
}
}
wp_reset_postdata();
echo $output;
endif;
With a form that is displayed via a shortcode, we want to add parameters to the URL and then read it out again in another shortcode. These functionalities are added via a custom plugin.
This works fine on a standard WordPress installation.
However, if we add the plugin to a multisite installation, it does not work. The parameters are added somehow, but an 'site not found' error occurs. Feel free to have a look at http://fortbildungen.mgo-fachverlage.de/, our multisite installation.
Here are parts of our code:
Shortcode that sets the parameters
This is the filter in the sidebar
function add_shortcode_themen() {
$themen = get_terms( array(
'taxonomy' => 'thema', //Custom Taxonomie 'thema'
'hide_empty' => true,
'parent' => 0,
) );
$arten = get_terms( array(
'taxonomy' => 'art', //Custom Taxonomie 'art'
'hide_empty' => true,
'parent' => 0,
) );
$s = '';
$s .= '<div class="fk-sc">';
$s .= '<form action="" method="GET">';
//### Themen
if( $themen ){
$s .= '<h3>Themenauswahl</h3>';
$themen_gefiltert = Fbk_WPQuery::get_ids('thema');
foreach($themen as $wp_term_object){
$id = $wp_term_object->term_id;
$color = get_term_meta( $id, 'fk-farbe', true );
$slug = $wp_term_object->slug;
$name = $wp_term_object->name;
$s .= '<div style="background-color: ' . $color . '">';
$s .= '<input
type="checkbox"
name="filter_thema[]"
id="fk-sc-' . $slug .'"
value="' . $id . '"';
if(!empty($themen_gefiltert) && in_array($id, $themen_gefiltert)){
$s .= ' checked';
}
$s .= '>';
$s .= '<label for="fk-sc-' . $slug .'">' . $name .'</label>';
$s .= '</div>';
}
echo '</select>';
}
//### Arten
if( $arten ){
$s .= '<br />';
$s .= '<h3>Veranstaltungsart</h3>';
$art_gefiltert = Fbk_WPQuery::get_ids('art');
foreach($arten as $wp_term_object){
$id = $wp_term_object->term_id;
$slug = $wp_term_object->slug;
$name = $wp_term_object->name;
$s .= '<div><input
type="checkbox"
name="filter_art[]"
id="fk-sc-' . $slug .'"
value="' . $id . '"';
if(!empty($art_gefiltert) && in_array($id, $art_gefiltert)){
$s .= ' checked';
}
$s .= '>';
$s .= '<label for="fk-sc-' . $slug .'">' . $name .'</label></div>';
}
}
$s .= '<input type="submit" value="Filtern"/>';
$s .= '</form>';
$s .= '</div>';
return $s;
}
add_shortcode( 'fk-filter', 'add_shortcode_themen' );
Shortcode that gets the parameters
This is the content of the page
add_shortcode( 'fk-kalender', 'add_shortcode_kalender' );
function add_shortcode_kalender() {
$query = new WP_Query(array(
'post_type' => 'fortbildung', //Custom Post Type 'fortbildung'
'post_status' => 'publish',
'tax_query' => Fbk_WPQuery::get_tax_query(), //gets the tax-query from URL-PARAMETERS
'orderby' => 'mgofv_fk_date',
'meta_key' => 'mgofv_fk_date',
'order' => 'ASC',
));
$html .= Fbk_SC_HTML_Builder::get_html_fortbildungen($query); //gets the html for displaying the posts
wp_reset_query();
return $html;
}
And the class Fbk_WPQuery
class Fbk_WPQuery {
public function get_tax_query(){
$tax_query = array();
if(isset($_GET['filter_thema']) && isset($_GET['filter_art'])){
$tax_query['relation'] = 'AND';
}
if(isset($_GET['filter_thema'])){
$tax_query[] = Fbk_WPQuery::get_thema();
}
if(isset($_GET['filter_art'])){
$tax_query[] = Fbk_WPQuery::get_art();
}
return $tax_query;
}
public function get_thema(){
if(isset($_GET['filter_thema'])){
var_dump($_GET['filter_thema']);
$selected = $_GET['filter_thema'];
$count = count($selected);
$arr = array();
$arr['relation'] = 'OR';
for($i = 0; $i < $count; $i++){
$arr[] = array(
'taxonomy' => 'thema',
'terms' => $selected[$i],
);
}
}
return $arr;
}
public function get_art(){
if(isset($_GET['filter_art'])){
$selected = $_GET['filter_art'];
$count = count($selected);
$arr = array();
$arr['relation'] = 'OR';
for($i = 0; $i < $count; $i++){
$arr[] = array(
'taxonomy' => 'art',
'terms' => $selected[$i],
'operator' => 'AND'
);
}
}
return $arr;
}
public function get_ids($get_param){
if($get_param == "thema"){
if(isset($_GET['filter_thema'])){
$selected = $_GET['filter_thema'];
$count = count($selected);
$id_arr = array();
for($i = 0; $i < $count; $i++){
$id_arr[] = $selected[$i];
}
}
}
else if($get_param == "art"){
if(isset($_GET['filter_art'])){
$selected = $_GET['filter_art'];
$count = count($selected);
$id_arr = array();
for($i = 0; $i < $count; $i++){
$id_arr[] = $selected[$i];
}
}
}
return $id_arr;
}
}
Thanks for any help :)
try to change
action="" to
action="http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '".
Worked for me
The theme that I have been using for my wp site has related posts shortcode which works, but it doesn't hide the currently viewed post. I had some idea to add a variable before the query to a post so the query sees that post which is currently viewed has that variable set to true and skip it. Here is the code:
<?php
global $post;
$categories = get_the_category();
$ceker=false;
foreach ($categories as $category[0]) {
if ($ceker == false){
$ceker=true;
?>
content etc...
I use this in my own themes and it works. How can I do something similar to these shortcode that this theme uses:
#BLOG LIST...
if(!function_exists('dt_blog_posts')) {
function dt_blog_posts( $atts, $content = null ) {
extract(shortcode_atts(array(
'show_feature_image' => 'true',
'excerpt_length' => 35,
'show_meta' => 'true',
'limit' => -1,
'categories' => '',
'posts_column' => 'one-column', // one-column, one-half-column, one-third-column
), $atts));
global $post;
$meta_set = get_post_meta($post->ID, '_tpl_default_settings', true);
$page_layout = !empty($meta_set['layout']) ? $meta_set['layout'] : 'content-full-width';
$post_layout = $posts_column;
$article_class = "";
$feature_image = "";
$column = ""; $out = "";
//POST LAYOUT CHECK...
if($post_layout == "one-column") {
$article_class = "column dt-sc-one-column blog-fullwidth";
$feature_image = "blog-full";
}
elseif($post_layout == "one-half-column") {
$article_class = "column dt-sc-one-half";
$feature_image = "blog-twocolumn";
$column = 2;
}
elseif($post_layout == "one-third-column") {
$article_class = "column dt-sc-one-third";
$feature_image = "blog-threecolumn";
$column = 3;
}
//PAGE LAYOUT CHECK...
if($page_layout != "content-full-width") {
$article_class = $article_class." with-sidebar";
$feature_image = $feature_image."-sidebar";
}
//POST VALUES....
if($categories == "") $categories = 0;
//PERFORMING QUERY...
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
$args = array('post_type' => 'post', 'paged' => $paged, 'posts_per_page' => $limit, 'cat' => $categories, 'ignore_sticky_posts' => 1);
$wp_query = new WP_Query($args);
$pholder = dt_theme_option('general', 'disable-placeholder-images');
if($wp_query->have_posts()): $i = 1;
while($wp_query->have_posts()): $wp_query->the_post();
$temp_class = $format = "";
if($i == 1) $temp_class = $article_class." first"; else $temp_class = $article_class;
if($i == $column) $i = 1; else $i = $i + 1;
$out .= '<div class="'.$temp_class.'"><!-- Post Starts -->';
$out .= '<article id="post-'.get_the_ID().'" class="'.implode(" ", get_post_class("blog-post", $post->ID)).'">';
if($show_meta != "false"):
$out .= '<div class="post-details"><!-- Post Details Starts -->';
$out .= '<div class="date"><span>'.get_the_date('d').'</span>'.get_the_date('M').'<br />'.get_the_date('Y').'</div>';
$out .= '<div class="post-comments">';
$commtext = "";
if((wp_count_comments($post->ID)->approved) == 0) $commtext = '0';
else $commtext = wp_count_comments($post->ID)->approved;
$out .= ''.$commtext.' <i class="fa fa-comment"></i>';
$out .= '</div>';
$format = get_post_format();
$out .= '<span class="post-icon-format"> </span>';
$out .= '</div><!-- Post Details ends -->';
endif;
$out .= '<div class="post-content"><!-- Post Content Starts -->';
$out .= '<div class="entry-thumb">';
if(is_sticky()):
$out .= '<div class="featured-post">'.__('Featured','iamd_text_domain').'</div>';
endif;
//POST FORMAT STARTS
if( $format === "image" || empty($format) ):
if( has_post_thumbnail() && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail($post->ID, $feature_image, $attr);
$out .= '</a>';
elseif($pholder != "true" && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$out .= '<img src="http://placehold.it/840x340&text='.get_the_title().'" alt="'.get_the_title().'" />';
$out .= '</a>';
endif;
elseif( $format === "gallery" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
$post_meta = is_array($post_meta) ? $post_meta : array();
if( array_key_exists("items", $post_meta) ):
$out .= "<ul class='entry-gallery-post-slider'>";
foreach ( $post_meta['items'] as $item ) { $out .= "<li><img src='{$item}' alt='gal-img' /></li>"; }
$out .= "</ul>";
endif;
elseif( $format === "video" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
$post_meta = is_array($post_meta) ? $post_meta : array();
if( array_key_exists('oembed-url', $post_meta) || array_key_exists('self-hosted-url', $post_meta) ):
if( array_key_exists('oembed-url', $post_meta) ):
$out .= "<div class='dt-video-wrap'>".wp_oembed_get($post_meta['oembed-url']).'</div>';
elseif( array_key_exists('self-hosted-url', $post_meta) ):
$out .= "<div class='dt-video-wrap'>".wp_video_shortcode( array('src' => $post_meta['self-hosted-url']) ).'</div>';
endif;
endif;
elseif( $format === "audio" ):
$post_meta = get_post_meta($post->ID ,'_dt_post_settings', true);
$post_meta = is_array($post_meta) ? $post_meta : array();
if( array_key_exists('oembed-url', $post_meta) || array_key_exists('self-hosted-url', $post_meta) ):
if( array_key_exists('oembed-url', $post_meta) ):
$out .= wp_oembed_get($post_meta['oembed-url']);
elseif( array_key_exists('self-hosted-url', $post_meta) ):
$out .= wp_audio_shortcode( array('src' => $post_meta['self-hosted-url']) );
endif;
endif;
else:
if( has_post_thumbnail() && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$attr = array('title' => get_the_title()); $out .= get_the_post_thumbnail($post->ID, $feature_image, $attr);
$out .= '</a>';
elseif($pholder != "true" && $show_feature_image != 'false'):
$out .= '<a href="'.get_permalink().'" title="'.get_the_title().'">';
$out .= '<img src="http://placehold.it/840x340&text='.get_the_title().'" alt="'.get_the_title().'" />';
$out .= '</a>';
endif;
endif;
//POST FORMAT ENDS
$out .= '</div>';
$out .= '<div class="entry-detail">';
$out .= '<h2>'.get_the_title().'</h2>';
if($excerpt_length != "" || $excerpt_length != 0) $out .= dt_theme_excerpt($excerpt_length);
$out .= '</div>';
if($show_meta != "true"):
$out .= '<div class="post-meta">';
$out .= '<div class="opsirnije">';
$out .= ''.'Opširnije »'.'';
$out .= '<ul>';
$out .= '<li><span class="fa fa-user"></span>'.get_the_author_meta('display_name').'</li>';
$categories = get_the_category();
$thiscats = "";
if($categories) {
foreach($categories as $category) {
$thiscats .= ''.$category->cat_name.', '; }
$thiscats = substr($thiscats,0, (strlen($thiscats)-2));
$out .= '<li><span class="fa fa-thumb-tack"></span>'.$thiscats.'</li>';
}
$out .= get_the_tag_list('<li><span class="fa fa-pencil"></span>', ', ', '</li>');
$out .= '</ul>';
$out .= '</div>';
endif;
$out .= '</div><!-- Post Content Ends -->';
$out .= '</article>';
$out .= '</div><!-- Post Ends -->';
endwhile;
if($wp_query->max_num_pages > 1):
$out .= '<div class="pagination-wrapper">';
if(function_exists("dt_theme_pagination")) $out .= dt_theme_pagination("", $wp_query->max_num_pages, $wp_query);
$out .= '</div>';
endif;
wp_reset_query($wp_query);
else:
$out .= '<h2>'.__('Nothing Found.', 'iamd_text_domain').'</h2>';
$out .= '<p>'.__('Apologies, but no results were found for the requested archive.', 'iamd_text_domain').'</p>';
endif;
return $out;
}
add_shortcode('dt_blog_posts', 'dt_blog_posts');
add_shortcode('dt_sc_blogposts', 'dt_blog_posts');
}
Answer was simple. Just added
'post__not_in' => array( get_the_ID() ))
in array.
Thx all...
I bought and Install "WordPress User Bookmarks (Standalone version)" So the problem is, this plugin have 1 default collection, by default, for each user but I need 3 or more default collections for each user I need to know how can I edit codes to add 3 or more collections by default.
THANKS ALL
Also I Attached API Documents here:
<?php
class wpb_api {
function __construct() {
}
/******************************************
Get first image in a post
******************************************/
function get_first_image($postid) {
$post = get_post($postid);
setup_postdata($post);
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (isset( $matches[1][0])) {
$first_img = $matches[1][0];
}
if(isset($first_img) && !empty($first_img)) {
return $first_img;
}
}
/******************************************
Get thumbnail URL based on post ID
******************************************/
function post_thumb_url( $postid ) {
$encoded = '';
if (get_post_thumbnail_id( $postid ) != '') {
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $postid ), 'large' );
$encoded = urlencode($image[0]);
} elseif ( $this->get_first_image($postid) != '' ) {
$encoded = urlencode( $this->get_first_image($postid) );
} else {
$encoded = urlencode ( wpb_url . 'img/placeholder.jpg' );
}
return $encoded;
}
/******************************************
Get post thumbnail image (size wise)
******************************************/
function post_thumb( $postid, $size=400 ) {
$post_thumb_url = $this->post_thumb_url( $postid );
if (isset($post_thumb_url)) {
$cropped_thumb = wpb_url . "lib/timthumb.php?src=".$post_thumb_url."&w=".$size."&h=".$size."&a=c&q=100";
$img = '<img src="'.$cropped_thumb.'" alt="" />';
return $img;
}
}
/* New collection */
function new_collection($name) {
$user_id = get_current_user_id();
$collections = $this->get_collections($user_id);
$collections[] = array('label' => $name);
update_user_meta($user_id, '_wpb_collections', $collections);
}
/* Remove a collection */
function hard_remove_collection($id){
$user_id = get_current_user_id();
$collections = $this->get_collections($user_id);
$bookmarks = $this->get_bookmarks( $user_id );
// remove bookmarks
foreach($collections[$id] as $k => $arr) {
if ($k != 'label') {
if (isset($bookmarks[$k])){
unset($bookmarks[$k]);
}
}
}
// remove collection
if ($id > 0){
unset($collections[$id]);
}
update_user_meta($user_id, '_wpb_bookmarks', $bookmarks);
update_user_meta($user_id, '_wpb_collections', $collections);
}
/* Soft-Remove a collection */
function soft_remove_collection($id){
$user_id = get_current_user_id();
$collections = $this->get_collections($user_id);
$bookmarks = $this->get_bookmarks( $user_id );
// transfer bookmarks to default collection
foreach($collections[$id] as $k => $arr) {
if ($k != 'label') {
$collections[0][$k] = 1;
}
}
// remove collection
if ($id > 0){
unset($collections[$id]);
}
update_user_meta($user_id, '_wpb_bookmarks', $bookmarks);
update_user_meta($user_id, '_wpb_collections', $collections);
}
/* Get bookmarks by collection */
function get_bookmarks_by_collection($id){
$collections = $this->get_collections( get_current_user_id() );
return $collections[$id];
}
function get_bookmarks_count_by_collection($id){
$collections = $this->get_collections( get_current_user_id() );
if ($id == 0){
if (empty($collections[$id])){
return 0;
} else {
return (int)count($collections[$id]);
}
} else {
return (int)count($collections[$id])-1;
}
}
/* print bookmarks */
function print_bookmarks($coll_id) {
$output = '';
$output .= '<div class="wpb-coll-count">';
$output .= sprintf(__('%s Bookmarks in Collection','wpb'), $this->get_bookmarks_count_by_collection($coll_id));
if ($coll_id != 0) { // default cannot be removed
$output .= ''.__('Remove Collection','wpb').'';
/* To hide a collection */
$output .= '<div class="wpb-coll-remove">';
$output .= __('Choose how do you want to remove this collection. This action cannot be undone!','wpb');
$output .= '<div class="wpb-coll-remove-btns">';
if ($this->get_bookmarks_count_by_collection($coll_id) > 0) {
$output .= ''.__('Remove collection and all bookmarks in it','wpb').'';
$output .= ''.__('Remove collection only','wpb').'';
} else {
$output .= ''.__('Remove collection','wpb').'';
}
$output .= '</div>';
$output .= '</div>';
}
$output .= '</div>';
$bks = $this->get_bookmarks_by_collection( $coll_id );
$results = 0;
if (is_array($bks)){
$bks = array_reverse($bks, true);
foreach($bks as $id => $array) {
if ($id != 'label') {
$results++;
if (get_post_status($id) == 'publish') { // active post
$output .= '<div class="wpb-coll-item">';
$output .= ''.__('Remove','wpb').'';
$output .= '<div class="uci-thumb">'.$this->post_thumb($id, 50).'</div>';
$output .= '<div class="uci-content">';
$output .= '<div class="uci-title">'. get_the_title($id) . '</div>';
$output .= '<div class="uci-url">'.get_permalink($id).'</div>';
$output .= '</div><div class="wpb-clear"></div>';
$output .= '</div><div class="wpb-clear"></div>';
} else {
$output .= '<div class="wpb-coll-item">';
$output .= ''.__('Remove','wpb').'';
$output .= '<div class="uci-thumb"></div>';
$output .= '<div class="uci-content">';
$output .= '<div class="uci-title">'.__('Content Removed','wpb').'</div>';
$output .= '<div class="uci-url"></div>';
$output .= '</div><div class="wpb-clear"></div>';
$output .= '</div><div class="wpb-clear"></div>';
}
}
}
}
if ($results == 0){
$output .= '<div class="wpb-coll-item">';
$output .= __('You did not add any content to this collection yet.','wpb');
$output .= '<div class="wpb-clear"></div></div><div class="wpb-clear"></div>';
}
return $output;
}
/* Get collections for user */
function collection_options($default_collection, $post_id){
$output = '';
$user_id = get_current_user_id();
$collections = $this->get_collections($user_id);
$bookmarks = (array) get_user_meta($user_id, '_wpb_bookmarks', true);
if (isset($bookmarks[$post_id])){
$cur_collection = $bookmarks[$post_id];
} else {
$cur_collection = 0;
}
foreach($collections as $k => $v) {
if (!isset($v['label'])) $v['label'] = $default_collection;
$output .= '<option value="'.$k.'" '.selected($k, $cur_collection, 0).' >'.$v['label'];
$output .= '</option>';
}
return $output;
}
/* Find collection ID */
function collection_id($post_id){
$user_id = get_current_user_id();
$bookmarks = (array) get_user_meta($user_id, '_wpb_bookmarks', true);
if (isset($bookmarks[$post_id])){
return $bookmarks[$post_id];
}
}
/**
Is post bookmarked
**/
function bookmarked($post_id){
$user_id = get_current_user_id();
$bookmarks = (array) get_user_meta($user_id, '_wpb_bookmarks', true);
if (isset($bookmarks[$post_id])){
return true;
}
return false;
}
/* Delete collection */
function delete_collection($collection_id, $user_id) {
$array = $this->get_collections($user_id);
unset($array[$collection_id]);
update_user_meta($user_id, '_wpb_collections', $array);
}
/* Get collections */
function get_collections($user_id) {
return (array)get_user_meta($user_id, '_wpb_collections', true);
}
/* Get bookmarks */
function get_bookmarks($user_id) {
return (array)get_user_meta($user_id, '_wpb_bookmarks', true);
}
/* Count bookmarks */
function bookmarks_count($user_id) {
$bookmarks = (array)get_user_meta($user_id, '_wpb_bookmarks', true);
unset($bookmarks[0]);
if (!empty($bookmarks) ){
return count($bookmarks);
} else {
return 0;
}
}
/* Get current page url */
function get_permalink(){
global $post;
if (is_home()){
$permalink = home_url();
} else {
if (isset($post->ID)){
$permalink = get_permalink($post->ID);
} else {
$permalink = '';
}
}
return $permalink;
}
/**
Display the bookmarks in
organized collections
**/
function bookmarks( $args = array() ){
global $post;
$defaults = array(
'default_collection' => wpb_get_option('default_collection'),
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
/* output */
$output = '';
// logged in
if (is_user_logged_in()){
$output .= '<div class="wpb-coll">';
$output .= '<div class="wpb-coll-list">';
$collections = $this->get_collections( get_current_user_id() );
$active_coll = 0;
foreach($collections as $id => $array) {
if (!isset($array['label'])) { $array['label'] = $default_collection; }
if ($id == $active_coll) { $class = 'active'; } else { $class = ''; }
$output .= '<a href="#collection_'.$id.'" data-collection_id="'.$id.'" class="'.$class.'">';
if ($class == 'active'){
$output .= '<i class="wpb-icon-caret-left"></i>';
$output .= '<span class="wpb-coll-list-count wpb-coll-hide">'.$this->get_bookmarks_count_by_collection($id).'</span>';
} else {
$output .= '<i class="wpb-icon-caret-left wpb-coll-hide"></i>';
$output .= '<span class="wpb-coll-list-count">'.$this->get_bookmarks_count_by_collection($id).'</span>';
}
$output .= $array['label'].'</a>';
}
$output .= '</div>';
$output .= '<div class="wpb-coll-body">';
$output .= '<div class="wpb-coll-body-inner">';
$output .= $this->print_bookmarks($coll_id = 0);
$output .= '</div></div><div class="wpb-clear"></div>';
$output .= '</div>';
// guest
} else {
$output .= '<p>'.sprintf(__('You need to login or register to view and manage your bookmarks.','wpb'),wp_login_url( get_permalink() ), site_url('/wp-login.php?action=register&redirect_to=' . get_permalink())).'</p>';
}
return $output;
}
/**
Bookmark: display the widget that allow
bookmarks
**/
function bookmark( $args = array() ){
global $post;
$defaults = array(
'width' => wpb_get_option('width'),
'align' => wpb_get_option('align'),
'inline' => wpb_get_option('inline'),
'no_top_margin' => wpb_get_option('no_top_margin'),
'no_bottom_margin' => wpb_get_option('no_bottom_margin'),
'pct_gap' => wpb_get_option('pct_gap'),
'px_gap' => wpb_get_option('px_gap'),
'widgetized' => wpb_get_option('widgetized'),
'remove_bookmark' => wpb_get_option('remove_bookmark'),
'dialog_bookmarked' => wpb_get_option('dialog_bookmarked'),
'dialog_unbookmarked' => wpb_get_option('dialog_unbookmarked'),
'default_collection' => wpb_get_option('default_collection'),
'add_to_collection' => wpb_get_option('add_to_collection'),
'new_collection' => wpb_get_option('new_collection'),
'new_collection_placeholder' => wpb_get_option('new_collection_placeholder'),
'add_new_collection' => wpb_get_option('add_new_collection'),
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
/* options */
if (strstr($width, 'px')) { $px = 'px'; } else { $px = '%'; }
if ($px == '%') {
$btn_width = 50 - $pct_gap . $px;
} else {
$btn_width = ($width / 2 ) - $px_gap . $px;
}
if ($widgetized == 1){
$btn_width = '100%';
}
/* output */
$output = '';
// logged in
if (is_user_logged_in()){
if (isset($post->ID)){
$post_id = $post->ID;
} else {
$post_id = null;
}
$output .= '<div class="wpb-bm wpb-bm-nobottommargin-'.$no_bottom_margin.' wpb-bm-notopmargin-'.$no_top_margin.' wpb-bm-inline-'.$inline.' wpb-bm-'.$align.' wpb-bm-widgetized-'.(int)$widgetized.'" style="width:'.$width.' !important;" data-add_new_collection="'.$add_new_collection.'" data-default_collection="'.$default_collection.'" data-new_collection_placeholder="'.$new_collection_placeholder.'" data-dialog_unbookmarked="'.$dialog_unbookmarked.'" data-dialog_bookmarked="'.$dialog_bookmarked.'" data-add_to_collection="'.$add_to_collection.'" data-remove_bookmark="'.$remove_bookmark.'" data-post_id="'.$post_id.'">';
$output .= '<div class="wpb-bm-inner">';
/* collections list */
$output .= '<div class="wpb-bm-list">';
$output .= '<select class="chosen-select-collections" name="wpb_bm_collection" id="wpb_bm_collection" data-placeholder="">';
$output .= $this->collection_options( $default_collection, $post_id );
$output .= '</select>';
$output .= '</div>';
/* action buttons */
$output .= '<div class="wpb-bm-act">';
if ($this->bookmarked($post_id)) {
$output .= '<input type="hidden" name="collection_id" id="collection_id" value="'.$this->collection_id($post_id).'" />';
$output .= '<div class="wpb-bm-btn-contain" style="width:'.$btn_width.' !important;">'.$remove_bookmark.'</div>';
} else {
$output .= '<div class="wpb-bm-btn-contain" style="width:'.$btn_width.' !important;">'.$add_to_collection.'</div>';
}
$output .= '<div class="wpb-bm-btn-contain bm-right" style="width:'.$btn_width.' !important;">'.$new_collection.'</div>';
$output .= '</div><div class="wpb-clear"></div>';
$output .= '</div>';
$output .= '</div>';
if (!$inline) {
$output .= '<div class="wpb-clear"></div>';
}
// guest
} else {
$output .= '<p>'.sprintf(__('You need to login or register to bookmark/favorite this content.','wpb'),wp_login_url( get_permalink() ), site_url('/wp-login.php?action=register&redirect_to=' . get_permalink())).'</p>';
}
return $output;
}
}
$wpb = new wpb_api();
I'm trying to display a "featured products slider" on the Category Page of the WooCommerce shop in such a way that only 'featured' products of the current category (or a specific child category) will be displayed in the slider.
I've placed the code below in the functions.php file of my child-theme.
I tried adding this conditional in archive.php:
if(is_product_category('slug'){echo featured_products_slider_fun($atts, $content);}
I can't figure out how to combine this condition with the function below to essentially show 'featured products' of a certain category'.
===========
function featured_products_slider_func( $atts, $content ) {
extract( shortcode_atts( array(
'num' => 4
), $atts ) );
$return = '';
$first_product_title = "";
$first_product_excerpt = "";
function get_the_popular_excerpt(){
$excerpt = get_the_content();
$excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
$excerpt = strip_shortcodes($excerpt);
$excerpt = strip_tags($excerpt);
$excerpt = substr($excerpt, 0, 190);
$excerpt = substr($excerpt, 0, strripos($excerpt, " "));
$excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
$excerpt = $excerpt.'. view product';
return $excerpt;
}
$post = new WP_Query(array(
'post_status' => 'publish',
'post_type' => 'product',
'meta_key' => '_featured',
'meta_value' => 'yes',
'posts_per_page' => $num
));
$return .= '<div class="featured-slider-outer box clearfix"><div class="featured-slider-inner">';
$return .= '<ul class="products featured-slider">';
$selected_class = " selected";
if ($post ->have_posts()) : while ($post ->have_posts()) : $post ->the_post();
global $product;
if( $selected_class != "" ) {
$first_product_title = get_the_title();
$first_product_excerpt = get_the_popular_excerpt();
}
$return .= '<li class="product' . $selected_class . '">';
$return .= get_the_post_thumbnail($post->ID, "blog-two-column");
if ($price_html = $product->get_price_html()) :
$return .= '<span class="price">';
$return .= $price_html;
$return .= '</span>';
endif;
$return .= "<div class='none'>";
$return .= "<h3 id='infos-title'>" . get_the_title() . "</h3>";
$return .= "<div id='infos-excerpt'>" . get_the_popular_excerpt() . "</div>";
$return .= "</div>";
$return .= '</li>';
$selected_class = "";
endwhile;
$return .= '</ul>';
$return .= '</div>';
$return .= '<div class="featured-slider-right">';
$return .= '<button class="btn-left"></button><button class="btn-right"></button><h2>' . $first_product_title . '</h2>';
$return .= '<div class="description">' . $first_product_excerpt . '</div>';
$return .= '</div>';
$return .= '</div>';
else:
$return = __("No featured products found!", "shopifiq");
endif;
return $return;
}
add_shortcode( 'featured_products_slider', 'featured_products_slider_func' );