How to add owl carousel to front page - javascript
I'm using a pre made theme for my site. I would like to add an owl carousel to the top of my front page that displays the most popular posts from the last month on my site. The pre made theme already comes with owl carousel. So my question is how can I add the carousel to my front page now? I found the owl carousel widget in the plugins file so I tried adding the widget to my front page but I don't think I added it right because nothing changed. Does anyone have any suggestions for how I could achieve this?
here are my full theme files if needed - https://www.dropbox.com/s/624p2sdn2i0jsqf/novablogshare.zip?dl=0
my custom front-page.php
<?php
get_header();
the_widget("owl_Widget"); //trying to call the owl carousel widget but it is not working
?>
<script>
var now=2; // when click start in page 2
jQuery(document).on('click', '#load_more_btn', function () {
jQuery.ajax({
type: "POST",
url: "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
data: {
action: 'my_load_more_function', // the name of the function in functions.php
paged: now, // set the page to get the ajax request
posts_per_page: 15 //number of post to get (use 1 for testing)
},
success: function (data) {
if(data!=0){
jQuery("#ajax").append(data); // put the content into ajax container
now=now+1; // add 1 to next page
}else{
jQuery("#load_more_btn").hide();
}
},
error: function (errorThrown) {
alert(errorThrown); // only for debuggin
}
});
});
</script>
<section id="ajax"><!-- i have to change div to section, maybe a extra div declare -->
<?php
$the_query = new WP_Query( [
'posts_per_page' => 15, // i use 1 for testing
'orderby' => 'post_date',
'order' => 'DESC',
'paged' => get_query_var('paged', 1) //page number 1 on load
] );
if ($the_query->have_posts()) {
$i = 0;
$j = 0;
while ($the_query->have_posts()) {
$the_query->the_post();
if ( $i % 5 === 0 ) { // Large post: on the first iteration and every 7th post after... ?>
<div class="row">
<article <?php post_class( 'col-sm-12 col-md-12' ); ?>>
<div class="large-front-container">
<?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?>
</div>
<div class="front-page-date"><?php echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'); ?></div>
<div class="front-page-post-title"><?php the_title(); ?></div>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'includes/front-shop-the-post' ); ?>
<?php get_template_part( 'includes/share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
</div>
<?php } else { // Small posts ?>
<?php if($j % 2 === 0){ echo '<div class="row">';} ?>
<article <?php post_class( 'col-sm-6 col-md-6' ); ?>>
<div class="two-front-container">
<?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?>
<div>
<div class="front-page-date"><?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?></div>
<div class="front-page-post-title"><?php the_title(); ?></div>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'includes/front-shop-the-post' ); ?>
<?php get_template_part( 'includes/share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
<?php $j++; if($j % 2 === 0){ echo '</div>';}?>
<?php
}
$i++;
}?>
<?php
}?>
</section>
<button id="load_more_btn">Load More Posts</button> <!-- button out of ajax container for load content and button displayed at the bottom -->
<?php
get_footer();
functions for my front-page
add_action('wp_ajax_my_load_more_function', 'my_load_more_function');
add_action('wp_ajax_nopriv_my_load_more_function', 'my_load_more_function');
function my_load_more_function() {
$query = new WP_Query( [
'posts_per_page' => $_POST["posts_per_page"],
'orderby' => 'post_date',
'order' => 'DESC',
'paged' => get_query_var('paged', $_POST["paged"])
] );
if ($query->have_posts()) {
$i = 0;
$j = 0;
while ($query->have_posts()) {
$query->the_post();
if ( $i % 5 === 0 ) { // Large post: on the first iteration and every 7th post after... ?>
<div class="row">
<article <?php post_class( 'col-sm-12 col-md-12' ); ?>>
<div class="large-front-container">
<?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?>
</div>
<div class="front-page-date"><?php echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'); ?></div>
<div class="front-page-post-title"><?php the_title(); ?></div>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'includes/front-shop-the-post' ); ?>
<?php get_template_part( 'includes/share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
</div>
<?php } else { // Small posts ?>
<?php if($j % 2 === 0) echo '<div class="row">'; ?>
<article <?php post_class( 'col-sm-6 col-md-6' ); ?>>
<div class="two-front-container">
<?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?>
<div>
<div class="front-page-date"><?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?></div>
<div class="front-page-post-title"><?php the_title(); ?></div>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'includes/front-shop-the-post' ); ?>
<?php get_template_part( 'includes/share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
<?php $j++; if($j % 2 === 0) echo '</div>'; ?>
<?php
}
$i++;
}
wp_reset_query();
}else{
return 0;
}
exit;
}
owl-carousel.php (located in plugins folder)
<?php
/*
Plugin Name: Owl Carousel
Description: A simple plugin to include an Owl Carousel in any post
Author: Pierre JEHAN
Version: 0.5.3
Author URI: http://www.pierre-jehan.com
Licence: GPL2
*/
add_theme_support('post-thumbnails');
add_action('init', 'owlcarousel_init');
add_action('wp_print_scripts', 'owl_register_scripts');
add_action('wp_print_styles', 'owl_register_styles');
add_action('widgets_init', 'owl_widgets_init');
add_action('manage_edit-owl-carousel_columns', 'owl_columnfilter');
add_action('manage_posts_custom_column', 'owl_column');
add_action('admin_menu', 'owl_carousel_menu');
add_action('admin_enqueue_scripts', 'owl_carousel_admin_register_scripts');
if (filter_var(get_option('owl_carousel_wordpress_gallery', false), FILTER_VALIDATE_BOOLEAN)) {
add_filter('post_gallery', 'owl_carousel_post_gallery', 10, 2);
}
// Add functions to create a new attachments fields
add_filter("attachment_fields_to_edit", "owl_carousel_attachment_fields_to_edit", null, 2);
add_filter("attachment_fields_to_save", "owl_carousel_attachment_fields_to_save", null, 2);
/**
* Initilize the plugin
*/
function owlcarousel_init() {
$labels = array(
'name' => __('Owl Carousel', 'owl-carousel-domain'),
'singular_name' => __('Carousel Slide', 'owl-carousel-domain'),
'add_new' => __('Add New Slide', 'owl-carousel-domain'),
'add_new_item' => __('Add New Carousel Slide', 'owl-carousel-domain'),
'edit_item' => __('Edit Carousel Slide', 'owl-carousel-domain'),
'new_item' => __('Add New Carousel Slide', 'owl-carousel-domain'),
'view_item' => __('View Slide', 'owl-carousel-domain'),
'search_items' => __('Search Carousel', 'owl-carousel-domain'),
'not_found' => __('No carousel slides found', 'owl-carousel-domain'),
'not_found_in_trash' => __('No carousel slides found in trash', 'owl-carousel-domain'),
);
register_post_type('owl-carousel', array(
'public' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'label' => 'Owl Carousel',
'menu_icon' => plugins_url('/owl-carousel/images/owl-logo-16.png'),
'labels' => $labels,
'capability_type' => 'post',
'supports' => array(
'title',
'editor',
'thumbnail'
)
));
$taxonomy_labels = array(
'name' => __('Carousels', 'owl-carousel-domain'),
'singular_name' => __('Carousel', 'owl-carousel-domain'),
'search_items' => __('Search Carousels', 'owl-carousel-domain'),
'popular_items' => __('Popular Carousels', 'owl-carousel-domain'),
'all_items' => __('All Carousels', 'owl-carousel-domain'),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __('Edit Carousel', 'owl-carousel-domain'),
'update_item' => __('Update Carousel', 'owl-carousel-domain'),
'add_new_item' => __('Add New Carousel', 'owl-carousel-domain'),
'new_item_name' => __('New Carousel Name', 'owl-carousel-domain'),
'separate_items_with_commas' => __('Separate carousels with commas', 'owl-carousel-domain'),
'add_or_remove_items' => __('Add or remove carousels', 'owl-carousel-domain'),
'choose_from_most_used' => __('Choose from the most used carousels', 'owl-carousel-domain'),
'not_found' => __('No carousels found.', 'owl-carousel-domain'),
'menu_name' => __('Carousels', 'owl-carousel-domain'),
);
register_taxonomy('Carousel', 'owl-carousel', array(
'labels' => $taxonomy_labels,
'rewrite' => array('slug' => 'carousel'),
'hierarchical' => true,
'show_admin_column' => true,
));
add_image_size('owl_widget', 180, 100, true);
add_image_size('owl_function', 600, 280, true);
add_shortcode('owl-carousel', 'owl_function');
add_filter("mce_external_plugins", "owl_register_tinymce_plugin");
add_filter('mce_buttons', 'owl_add_tinymce_button');
// Add Wordpress Gallery option
add_option('owl_carousel_wordpress_gallery', 'off');
add_option('owl_carousel_orderby', 'post_date');
}
function owl_carousel_menu() {
add_submenu_page('edit.php?post_type=owl-carousel', __('Parameters', 'owl-carousel-domain'), __('Parameters', 'owl-carousel-domain'), 'manage_options', 'owl-carousel-parameters', 'submenu_parameters');
}
function submenu_parameters() {
$isWordpressGallery = (filter_var(get_option('owl_carousel_wordpress_gallery', false), FILTER_VALIDATE_BOOLEAN)) ? 'checked' : '';
$orderBy = get_option('owl_carousel_orderby', 'post_date');
$orderByOptions = array('post_date', 'title');
echo '<div class="wrap owl_carousel_page">';
echo '<?php update_option("owl_carousel_wordpress_gallery", $_POST["wordpress_gallery"]); ?>';
echo '<h2>' . __('Owl Carousel parameters', 'owl-carousel-domain') . '</h2>';
echo '<form action="' . plugin_dir_url(__FILE__) . 'save_parameter.php" method="POST" id="owlcarouselparameterform">';
echo '<h3>' . __('Wordpress Gallery', 'owl-carousel-domain') . '</h3>';
echo '<input type="checkbox" name="wordpress_gallery" ' . $isWordpressGallery . ' />';
echo '<label>' . __('Use Owl Carousel with Wordpress Gallery', 'owl-carousel-domain') . '</label>';
echo '<br />';
echo '<label>' . __('Order Owl Carousel elements by ', 'owl-carousel-domain') . '</label>';
echo '<select name="orderby" />';
foreach ($orderByOptions as $option) {
echo '<option value="' . $option . '" ' . (($option == $orderBy) ? 'selected="selected"' : '') . '>' . $option . '</option>';
}
echo '</select>';
echo '<br />';
echo '<br />';
echo '<input type="submit" class="button-primary owl-carousel-save-parameter-btn" value="' . __('Save changes', 'owl-carousel-domain') . '" />';
echo '<span class="spinner"></span>';
echo '</form>';
echo '</div>';
}
/**
* List of JavaScript / CSS files for admin
*/
function owl_carousel_admin_register_scripts() {
wp_register_style('owl.carousel.admin.styles', plugin_dir_url(__FILE__) . 'css/admin_styles.css');
wp_enqueue_style('owl.carousel.admin.styles');
wp_register_script('owl.carousel.admin.script', plugin_dir_url(__FILE__) . 'js/admin_script.js');
wp_enqueue_script('owl.carousel.admin.script');
}
/**
* List of JavaScript files
*/
function owl_register_scripts() {
wp_register_script('js.owl.carousel', plugins_url('/owl-carousel/js/owl.carousel.js'));
wp_register_script('js.owl.carousel.script', plugins_url('/owl-carousel/js/script.js'));
wp_enqueue_script('jquery');
wp_enqueue_script('js.owl.carousel');
wp_enqueue_script('js.owl.carousel.script');
}
/**
* List of CSS files
*/
function owl_register_styles() {
wp_register_style('style.owl.carousel', plugins_url('/owl-carousel/css/owl.carousel.css'));
wp_register_style('style.owl.carousel.theme', plugins_url('/owl-carousel/css/owl.theme.css'));
wp_register_style('style.owl.carousel.transitions', plugins_url('/owl-carousel/css/owl.transitions.css'));
wp_register_style('style.owl.carousel.styles', plugins_url('/owl-carousel/css/styles.css'));
wp_enqueue_style('style.owl.carousel');
wp_enqueue_style('style.owl.carousel.theme');
wp_enqueue_style('style.owl.carousel.transitions');
wp_enqueue_style('style.owl.carousel.styles');
}
function owl_register_tinymce_plugin($plugin_array) {
$plugin_array['owl_button'] = plugins_url('/owl-carousel/js/owl-tinymce-plugin.js');
return $plugin_array;
}
function owl_add_tinymce_button($buttons) {
$buttons[] = "owl_button";
return $buttons;
}
/*
* Initialize Owl Widget
*/
function owl_widgets_init() {
register_widget("owl_Widget");
}
class owl_Widget extends WP_Widget {
public function __construct() {
parent::__construct('owl_Widget', 'Owl Carousel', array('description' => __('A Owl Carousel Widget', 'text_domain')));
}
public function form($instance) {
if (isset($instance['title'])) {
$title = $instance['title'];
} else {
$title = __('Widget Carousel', 'text_domain');
}
if (isset($instance['category'])) {
$carousel = $instance['category'];
} else {
$carousel = 'Uncategorized';
}
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('category'); ?>"><?php _e('Carousel:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('category'); ?>" name="<?php echo $this->get_field_name('category'); ?>" type="text" value="<?php echo esc_attr($carousel); ?>" />
</p>
<?php
}
public function update($new_instance, $old_instance) {
$instance = array();
$instance['title'] = strip_tags($new_instance['title']);
$instance['category'] = strip_tags($new_instance['category']);
return $instance;
}
public function widget($args, $instance) {
extract($args);
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
if (!empty($title))
echo $before_title . $title . $after_title;
echo owl_function(array(category => $instance['category'], singleItem => "true", autoPlay => "true", pagination => "false"));
echo $after_widget;
}
}
/**
* Add custom column filters in administration
* #param array $columns
*/
function owl_columnfilter($columns) {
$thumb = array('thumbnail' => 'Image');
$columns = array_slice($columns, 0, 2) + $thumb + array_slice($columns, 2, null);
return $columns;
}
/**
* Add custom column contents in administration
* #param string $columnName
*/
function owl_column($columnName) {
global $post;
if ($columnName == 'thumbnail') {
echo edit_post_link(get_the_post_thumbnail($post->ID, 'thumbnail'), null, null, $post->ID);
}
}
/**
* Adding our images custom fields to the $form_fields array
* #param array $form_fields
* #param object $post
* #return array
*/
function owl_carousel_attachment_fields_to_edit($form_fields, $post) {
// add our custom field to the $form_fields array
// input type="text" name/id="attachments[$attachment->ID][custom1]"
$form_fields["owlurl"] = array(
"label" => __("Owl Carousel URL"),
"input" => "text",
"value" => get_post_meta($post->ID, "_owlurl", true)
);
return $form_fields;
}
/**
* Save images custom fields
* #param array $post
* #param array $attachment
* #return array
*/
function owl_carousel_attachment_fields_to_save($post, $attachment) {
if (isset($attachment['owlurl'])) {
update_post_meta($post['ID'], '_owlurl', $attachment['owlurl']);
}
return $post;
}
/**
* Plugin main function
* #param type $atts Owl parameters
* #param type $content
* #return string Owl HTML code
*/
function owl_function($atts, $content = null) {
extract(shortcode_atts(array(
'category' => 'Uncategoryzed'
), $atts));
$data_attr = "";
foreach ($atts as $key => $value) {
if ($key != "category") {
$data_attr .= ' data-' . $key . '="' . $value . '" ';
}
}
$lazyLoad = array_key_exists("lazyload", $atts) && $atts["lazyload"] == true;
$args = array(
'post_type' => 'owl-carousel',
'orderby' => get_option('owl_carousel_orderby', 'post_date'),
'order' => 'asc',
'tax_query' => array(
array(
'taxonomy' => 'Carousel',
'field' => 'slug',
'terms' => $atts['category']
)
),
'nopaging' => true
);
$result = '<div id="owl-carousel-' . rand() . '" class="owl-carousel owl-carousel-' . sanitize_title($atts['category']) . '" ' . $data_attr . '>';
$loop = new WP_Query($args);
while ($loop->have_posts()) {
$loop->the_post();
$img_src = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), get_post_type());
$meta_link = get_post_meta(get_post_thumbnail_id(get_the_ID()), '_owlurl', true);
$result .= '<div class="item">';
if ($img_src[0]) {
$result .= '<div>';
if (!empty($meta_link)) {
$result .= '<a href="' . $meta_link . '">';
}
if ($lazyLoad) {
$result .= '<img class="lazyOwl" title="' . get_the_title() . '" data-src="' . $img_src[0] . '" alt="' . get_the_title() . '"/>';
} else {
$result .= '<img title="' . get_the_title() . '" src="' . $img_src[0] . '" alt="' . get_the_title() . '"/>';
}
if (!empty($meta_link)) {
$result .= '</a>';
}
// Add image overlay with hook
$slide_title = get_the_title();
$slide_content = get_the_content();
$img_overlay = '<div class="owl-carousel-item-imgoverlay">';
$img_overlay .= '<div class="owl-carousel-item-imgtitle">' . $slide_title . '</div>';
$img_overlay .= '<div class="owl-carousel-item-imgcontent">' . wpautop($slide_content) . '</div>';
$img_overlay .= '</div>';
$result .= apply_filters('owlcarousel_img_overlay', $img_overlay, $slide_title, $slide_content, $meta_link);
$result .= '</div>';
} else {
$result .= '<div class="owl-carousel-item-text">' . get_the_content() . '</div>';
}
$result .= '</div>';
}
$result .= '</div>';
/* Restore original Post Data */
wp_reset_postdata();
return $result;
}
/**
* Owl Carousel for Wordpress image gallery
* #param string $output Gallery output
* #param array $attr Parameters
* #return string Owl HTML code
*/
function owl_carousel_post_gallery($output, $attr) {
global $post;
if (isset($attr['orderby'])) {
$attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
if (!$attr['orderby'])
unset($attr['orderby']);
}
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
$id = intval($id);
if ('RAND' == $order)
$orderby = 'none';
if (!empty($include)) {
$include = preg_replace('/[^0-9,]+/', '', $include);
$_attachments = get_posts(array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));
$attachments = array();
foreach ($_attachments as $key => $val) {
$attachments[$val->ID] = $_attachments[$key];
}
}
if (empty($attachments))
return '';
// Add item number if not defined
if (!isset($attr['items'])) {
$attr['items'] = '1';
}
$data_attr = "";
foreach ($attr as $key => $value) {
if ($key != "category") {
$data_attr .= ' data-' . $key . '="' . $value . '" ';
}
}
$output .= '<div id="owl-carousel-' . rand() . '" class="owl-carousel" ' . $data_attr . '>';
foreach ($attachments as $id => $attachment) {
$img = wp_get_attachment_image_src($id, 'full');
$meta_link = get_post_meta($id, '_owlurl', true);
$title = $attachment->post_title;
$output .= "<div class=\"item\">";
if (!empty($meta_link)) {
$output .= "<a href=\"" . $meta_link . "\">";
}
$output .= "<img src=\"{$img[0]}\" width=\"{$img[1]}\" height=\"{$img[2]}\" alt=\"$title\" />\n";
if (!empty($meta_link)) {
$output .= "</a>";
}
$output .= "</div>";
}
$output .= "</div>";
return $output;
}
what I'm trying to get the carousel to look like (whowhatwear.com)
Would I want my code to look something like this?
<div id="slider">
<?php
$carousel_cat = get_theme_mod('carousel_setting','1');
$carousel_count = get_theme_mod('count_setting','4');
$month = date('m');
$year = date('Y');
$new_query = new WP_Query( array('posts_per_page' => $carousel_count, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC','monthnum'=>$month,'year'=>$year ));
?>
<?php if ( $new_query->have_posts() ) : ?>
<?php while ( $new_query->have_posts() ) : $new_query->the_post(); ?>
<div class="item">
<?php the_post_thumbnail('popular-posts'); ?>
<h2><a class="popular-category"
<?php
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo '' . esc_html( $categories[0]->name ) . '';
}
?></a></h2>
<p>
<a class="popular-excerpt" href="<?php the_permalink(); ?>"><?php echo get_the_excerpt(); ?></a>
</p>
</div>
<?php endwhile; wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e(); ?></p>
<?php endif; ?>
</div>
#user6738171 I believe you do not need to the_widget("owl_Widget"); Just build the html you would like to show(using php) and then call the carousel with JQuery like so:
jQuery(document).ready(function($){
$(".homepage-slides").owlCarousel({
items: 1,
nav: true,
dots: false,
autoplay: true,
loop: true
});
});
Please read documentation for the correct structure of carousel items https://github.com/OwlCarousel2/OwlCarousel2. If you need help for building the carousel let me know. :-)
Something like this:
<?php
?>
<div class="homepage-slides">
<div>
<?php the_post_thumbnail('thumbnail', array('class' => 'thumbnail')); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
</div>
</div>
<?php
And the jquery from above. Inside the loop of course
Try this code it loops through the posts with the custom query you provided and puts them out accordingly. The only thing you should have to do is calculate how many posts you want to show and edit the carousel count.
<?php
$month = date('m');
$year = date('Y');
$new_query = new WP_Query( array('posts_per_page' => $carousel_count, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC','monthnum'=>$month,'year'=>$year ));
?>
<?php if ( $new_query->have_posts() ) : ?>
<div class="homepage-slides">
<?php while ( $new_query->have_posts() ) : $new_query->the_post(); ?>
<div>
<?php the_post_thumbnail('thumbnail', array('class' => 'thumbnail')); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
</div>
<?php endwhile; wp_reset_postdata(); ?>
</div>
<?php else : ?>
<p><?php _e(); ?></p>
<?php endif; ?>
<script>
jQuery(document).ready(function($){
$(".homepage-slides").owlCarousel({
items: 4,
nav: true,
dots: false,
autoplay: true,
loop: true
});
});
</script>
Related
Search query with filter
Thanks to the help of stack overflow I was able to make my filter work(Ajax filter for wordpress) but now I want to add a search input that search the titles of my posts (a custom post type called 'Contratistas'). So I have a few questions: My form for my filter has POST, but the search (i've seen examples) always has GET, so, should I have two separete forms? If so, is there a way for submiting my search without a button? this is my code: <form id="searchform" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <input type="text" class="search-field mb-3" name="s" placeholder="Search" value="<?php echo get_search_query(); ?>"> <input type="submit" value="Search" class="mb-3"> </form> <form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter"> <div class="titulo mb-3"> <h3>Región</h3> </div> <?php if( $terms = get_terms( array( 'taxonomy' => 'region', 'orderby' => 'name' ) ) ) : echo '<select name="filtroRegion"><option value="">Seleccione una región</option>'; foreach ( $terms as $term ) : echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option endforeach; echo '</select>'; endif; ?> <div class="titulo my-3"> <h3>Industrias</h3> </div> <?php if( $terms = get_terms( array( 'taxonomy' => 'industria', 'orderby' => 'name' ) ) ) : echo '<select name="filtroIndustria"><option value="">Seleccione una industria</option>'; foreach ( $terms as $term ) : echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option endforeach; echo '</select>'; endif; ?> <button class="my-3 filtrar">Filtrar</button> <button>Limpiar filtros</button> <input type="hidden" name="action" value="myfilter"> </form> As you can see i have two buttons but i only want the last one ('Filtrar') I have no idea how to implement the search with the filters so that i can put my results in the same fashion as the one i get from the dropdowns. Here is my filter: $args = array( 'orderby' => 'date', // we will sort posts by date 'order' => $_POST['date'], // ASC or DESC 'post_per_page' => -1, 'post_type' => 'contratista' ); if (!empty($_POST['filtroRegion']) || !empty($_POST['filtroIndustria'])) { $args['tax_query'] = array(); if (!empty($_POST['filtroRegion'])) { $args['tax_query'][] = array( 'taxonomy' => 'region', 'terms' => $_POST['filtroRegion'] ); } if (!empty($_POST['filtroIndustria'])) { $args['tax_query'][] = array( 'taxonomy' => 'industria', 'terms' => $_POST['filtroIndustria'] ); } if (count($args['tax_query']) > 1) { $args['tax_query']['relation'] = 'AND'; } } $query = new WP_Query($args); And my JQuery: jQuery(function($) { $('#filter').submit(function() { var filter = $('#filter'); $.ajax({ url: filter.attr('action'), data: $('#filter :input').filter(function(index, element) { return $(element).val() != ''; }).serialize(), // form data type: filter.attr('method'), // POST beforeSend: function(xhr) { filter.find('.filtrar').text('Procesando...'); // changing the button label }, success: function(data) { filter.find('.filtrar').text('Filtrar'); // changing the button label back $('#response').html(data); // insert data } }); return false; } } Any help or guidance will be very appreciated. Thanks
I got it! Here's my working code in case somebody else needs it! The answer was VERY simple! I only had to add this: 's' => $_POST['s'] Here is my function function misha_filter_function(){ $args = array( 'orderby' => 'date', // we will sort posts by date 'order' => $_POST['date'], // ASC or DESC 'post_per_page' => -1, 'post_type' => 'contratista', 's' => $_POST['s'], ); //Same code as before: if( !empty($_POST['filtroRegion']) || !empty($_POST['filtroIndustria']) ){ $args['tax_query'] = array(); if(!empty($_POST['filtroRegion']) ){ $args['tax_query'][] = array( 'taxonomy' => 'region', 'terms' => $_POST['filtroRegion'] ); } } $query = new WP_Query( $args ); //my post And my form: <form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter"> <h3>Buscar</h3> <input type="text" class="search-field mb-3" name="s" placeholder="Busqueda por nombre" value="<?php echo get_search_query(); ?>"> <div class="titulo mb-3"> <h3>Región</h3> </div> <?php if( $terms = get_terms( array( 'taxonomy' => 'region', 'orderby' => 'name' ) ) ) : echo '<select name="filtroRegion"><option value="">Seleccione una región</option>'; foreach ( $terms as $term ) : echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option endforeach; echo '</select>'; endif; ?>
How can I create a filterable portfolio in PHP (wordpress)?
I am currently working on my own personal portfolio website. I've made a custom post type using Pods to create portfolio items and i want to use the wordpress tags as the filter. I've successfully received the portfolio items and the filters. But how can i make them clickable/filterable ? Everything I've found includes portfolio plugins etc. But I don't want to use that, is just want to create my own simple filterable portfolio. Can someone help me out ? Here is the code: Filters: $tags = get_tags(); $html = '<div class="post_tags centered-content"> Alles'; foreach ( $tags as $tag ) { $tag_link = get_tag_link( $tag->term_id ); $html .= "<a href='#{$tag->slug}' title='{$tag->name} filter' class='button outline {$tag->slug}'>"; $html .= "{$tag->name}</a>"; } $html .= '</div>'; echo $html; Portfolio items: function getPortfolio(){ global $post; $portfolioargs = array( 'posts_per_page' => 999, 'orderby' => 'date', 'order' => 'DESC', 'post_type' => 'portfolio', 'post_status' => 'publish', 'suppress_filters' => false ); $portfolioitems = get_posts($portfolioargs); foreach ($portfolioitems as $portfolioitem) { $feat_image = wp_get_attachment_image_src( get_post_thumbnail_id($portfolioitem->ID), 'full' ); $tags = wp_get_post_tags($portfolioitem->ID); echo '<div class="card portfolio">'; echo '<a href="'. get_the_permalink($portfolioitem->ID) .'">'; echo '<figure>'; echo '<img src="'. pods_image_url($feat_image, 'card') .'"/>'; echo '</figure>'; echo '</a>'; echo '<div class="card-title-wrapper">'; echo '<h3>'. $portfolioitem->post_title .'</h3>'; echo '<span class="card-subtitle mdi mdi-tag-outline mdi-15px">'; foreach ( $tags as $tag ) { echo $tag->name . ', '; } echo '</span>'; echo '</div>'; echo '<div class="card-content">'; echo '<p>'. $portfolioitem->post_content .'</p>'; echo '</div>'; echo '<div class="card-actions">'; echo 'Lees meer'; echo 'Bekijk website'; echo '</div>'; echo '</div>'; } } Check the screenshot here
In my opinion the best way to make these tags work as a filter is "AJAX". here i have written your "tags" code to work as a javascript filter . hope it helps. at first let rewrite your code to show tags , i add a line (created an input to send it with AJAX): $tags = get_tags(); $html = '<div class="post_tags centered-content"> <input type='hidden' name='tag_filter' value=''> Alles'; foreach ( $tags as $tag ) { $tag_link = get_tag_link( $tag->term_id ); $html .= "<a title='{$tag->name} filter' class='button outline filterBtn {$tag->slug}'>"; $html .= "{$tag->name}</a>"; } $html .= '</div>'; echo $html; then we will have our javascript (jquery) to send the selected tag values: $('.filterBtn').click(function(){ var selected_tag = $(this).text(); $('input[name="tag_filter"]').val(selected_tag); $.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', data: { action: 'data_fetch', filter: $('input[name="tag_filter"]').val()}, success: function (data) { $('#yourResultDIV').html(data); } }); }) the next part is our PHP code to produce result base on our selected filter: (in functions.php) add_action('wp_ajax_data_fetch' , 'resultsLoad'); add_action('wp_ajax_nopriv_data_fetch','resultsLoad'); function resultsLoad(){ $filter = $_POST['filter']; global $post; $portfolioargs = array( 'posts_per_page' => 999, 'orderby' => 'date', 'order' => 'DESC', 'post_type' => 'portfolio', 'post_status' => 'publish', 'tag' => $filter ); $portfolioitems = get_posts($portfolioargs); foreach ($portfolioitems as $portfolioitem) { $feat_image = wp_get_attachment_image_src( get_post_thumbnail_id($portfolioitem->ID), 'full' ); $tags = wp_get_post_tags($portfolioitem->ID); echo '<div class="card portfolio">'; echo '<a href="'. get_the_permalink($portfolioitem->ID) .'">'; echo '<figure>'; echo '<img src="'. pods_image_url($feat_image, 'card') .'"/>'; echo '</figure>'; echo '</a>'; echo '<div class="card-title-wrapper">'; echo '<h3>'. $portfolioitem->post_title .'</h3>'; echo '<span class="card-subtitle mdi mdi-tag-outline mdi-15px">'; foreach ( $tags as $tag ) { echo $tag->name . ', '; } echo '</span>'; echo '</div>'; echo '<div class="card-content">'; echo '<p>'. $portfolioitem->post_content .'</p>'; echo '</div>'; echo '<div class="card-actions">'; echo 'Lees meer'; echo 'Bekijk website'; echo '</div>'; echo '</div>'; } die(); }
Display widget from post on front page
In each of my posts I place a shop the post widget in them. The shop the post widget plugin php is provided down below. With this plugin you then only have to place a short short code in your post html. (the shop widget site gives you this code after you generate the widget) An example short code you would place into post html - [show_shopthepost_widget id="2371382"] What the widget would look like - What I want to happen is to have the shop the post widget appear on my front page under the post title and excerpt. I tried to do this by adding in echo do_shortcode(). But that did not work. Does anyone have any solutions? I'm stumped, and would appreciate any help. *I will have a different widget ID for each post, since each post will have a different shop the post widget. so my front page post preview would look like this - here is the plugin code (the site I use for the widget has many other shopping widgets such as boutique and lookbook, which is why you'll see a few other widgets besides the shop the post widget, which is what I'm working with) <?php /* Plugin Name: rewardStyle Widget Plugin URI: http://www.rewardstyle.com Description: The rewardStyle plugin allows bloggers to use rewardStyle widgets on their WordPress blog Author: rewardStyle Author URI: http://www.rewardstyle.com Version: 1.53 */ require 'plugin-updates/plugin-update-checker.php'; $ExampleUpdateChecker = new PluginUpdateChecker_1_5( 'http://www.rewardstyle.com/assets/info.json', __FILE__, 'rewardstyle-widgets', 1 ); /** * Add these to the KSES 'Allowed Post Tags' global * var. Keeps these tags from being removed in the * save/update process. */ $GLOBALS['allowedposttags']['iframe'] = array( 'id' => TRUE, 'class' => TRUE, 'title' => TRUE, 'style' => TRUE, 'align' => TRUE, 'frameborder' => TRUE, 'height' => TRUE, 'longdesc' => TRUE, 'marginheight' => TRUE, 'marginwidth' => TRUE, 'name' => TRUE, 'scrolling' => TRUE, 'src' => TRUE, 'width' => TRUE ); $GLOBALS['allowedposttags']['script'] = array( 'id' => TRUE, 'class' => TRUE, 'src' => TRUE, 'type' => TRUE, 'name' => TRUE ); /** * Add these to the Tiny MCE whitelist of acceptable Tags. * This keeps the values available when loading the page, * and when switching from Visual/Text Tabs */ function unfilter_iframe($initArray) { if (isset($initArray['extended_valid_elements'])) { $initArray['extended_valid_elements'] .= ",+iframe[id|class|title|style|align|frameborder|height|longdesc|marginheight|marginwidth|name|scrolling|src|width]"; } else { $initArray['extended_valid_elements'] = "+iframe[id|class|title|style|align|frameborder|height|longdesc|marginheight|marginwidth|name|scrolling|src|width]"; } return $initArray; } function unfilter_script($initArray) { if (isset($initArray['extended_valid_elements'])) { $initArray['extended_valid_elements'] .= ",+script[id|class|src|type|name]"; } else { $initArray['extended_valid_elements'] = "+script[id|class|src|type|name]"; } return $initArray; } add_filter('tiny_mce_before_init', 'unfilter_iframe'); add_filter('tiny_mce_before_init', 'unfilter_script'); // Add shortcode support to completely bypass the iframe filter add_shortcode( 'show_rs_widget', 'rs_show_widget'); function rs_show_widget($atts, $content = null) { extract(shortcode_atts(array( 'wid' => '', 'blog' => '', 'product_ids' => '', 'rows' => '', 'cols' => '', 'brand' => '', 'price' => '', 'hover' => '' ), $atts)); $h = $rows * 120; $w = ($cols * 110) + 50; $magic_num = 0; $how_tall = '120'; $prod_box = 'show'; if ($brand == 1) { $magic_num++; } if ($price == 1) { $magic_num++; } if ($hover == 1) { $magic_num = 0; $prod_box = 'hover-info'; } if ($magic_num == 1) { $how_tall = '162'; } else if ($magic_num == 2) { $how_tall = '195'; } $out = "<div style='width: ".$w."px; height: ".$how_tall."px; margin: 0px auto; background:white;'> <iframe frameborder='0' width='".$w."px' height='".$how_tall."px' scrolling='no' src='http://currentlyobsessed.me/api/v1/get_widget?wid=".$wid."&blog=".$blog."&product_ids=".$product_ids."&rows=".$rows."&cols=".$cols."&brand=".$brand."&price=".$price."&hover=".$hover."'></iframe> </div>"; return $out; } function ms_show_widget($atts) { extract(shortcode_atts(array( 'id' => '0', 'image_id' => '0', 'width' => '0', 'height' => '0', 'adblock' => 'Disable your ad blocking software to view this content.', 'enableJs' => 'JavaScript is currently disabled in this browser. Reactivate it to view this content.' ), $atts)); $out = '<div class="moneyspot-widget" data-widget-id="'.$id.'"> <script type="text/javascript" language="javascript"> !function(d,s,id){ var e, p = /^http:/.test(d.location) ? \'http\' : \'https\'; if(!d.getElementById(id)) { e = d.createElement(s); e.id = id; e.src = p + \'://widgets.rewardstyle.com/js/widget.js\'; d.body.appendChild(e); } if(typeof(window.__moneyspot) === \'object\') { if(document.readyState === \'complete\') { window.__moneyspot.init(); } } }(document, \'script\', \'moneyspot-script\'); </script> <div class="rs-adblock"> <img src="//images.rewardstyle.com/img?v=2.11&ms='.$id.'&aspect" onerror="this.parentNode.innerHTML=\'Turn off your ad blocker to view content\'" /> <noscript>'.$enableJs.'</noscript> </div> </div>'; return $out; } add_shortcode('show_ms_widget', 'ms_show_widget'); function ltk_show_widget($atts) { extract(shortcode_atts(array( 'user_id' => '0', 'rows' => '1', 'cols' => '6', 'show_frame' => 'true', 'padding' => '0' ), $atts)); $out = '<div class="ltkwidget-widget" data-rows="'.$rows.'" data-cols="'.$cols.'" data-show-frame="'.$show_frame.'" data-user-id="'.$user_id.'" data-padding="'.$padding.'"> <script type="text/javascript" language="javascript"> !function(d,s,id){ var e, p = /^http:/.test(d.location) ? \'http\' : \'https\'; if(!d.getElementById(id)) { e = d.createElement(s); e.id = id; e.src = p + \'://widgets.rewardstyle.com/js/ltkwidget.js\'; d.body.appendChild(e); } }(document, \'script\', \'ltkwidget-script\'); if(typeof(window.__ltkwidget) === \'object\'){ if (document.readyState === \'complete\') { __ltkwidget.init(); } } </script> <div class="rs-adblock"> <img src="//assets.rewardstyle.com/images/search/350.gif" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" /> <noscript>'.$enableJs.'</noscript> </div> </div>'; return $out; } add_shortcode('show_ltk_widget', 'ltk_show_widget'); function ltk_widget_version_two($atts) { extract(shortcode_atts(array( 'app_id' => '0', 'user_id' => '0', 'rows' => '1', 'cols' => '6', 'show_frame' => 'true', 'padding' => '0' ), $atts)); $out = '<div id="ltkwidget-version-two'.$app_id.'" data-appid="'.$app_id.'" class="ltkwidget-version-two"> <script>var rsLTKLoadApp="0",rsLTKPassedAppID="'.$app_id.'";</script> <script type="text/javascript" src="//widgets-static.rewardstyle.com/widgets2_0/client/pub/ltkwidget/ltkwidget.js"></script> <div widget-dashboard-settings="" data-appid="'.$app_id.'" data-userid="'.$user_id.'" data-rows="'.$rows.'" data-cols="'.$cols.'" data-showframe="'.$show_frame.'" data-padding="'.$padding.'"> <div class="rs-ltkwidget-container"> <div ui-view=""></div> </div> </div> </div>'; return $out; } add_shortcode('show_ltk_widget_version_two', 'ltk_widget_version_two'); function lookbook_show_widget($atts) { extract(shortcode_atts(array( 'id' => '0', 'adblock' => 'Turn off your ad blocker to view content', 'enableJs' => 'Turn on your JavaScript to view content' ), $atts)); $out = '<div class="lookbook-widget" data-widget-id="'.$id.'"> <script type="text/javascript" language="javascript"> !function(d,s,id){ var e, p = /^http:/.test(d.location) ? \'http\' : \'https\'; if(!d.getElementById(id)) { e = d.createElement(s); e.id = id; e.src = p + \'://widgets.rewardstyle.com/js/lookbook.js\'; d.body.appendChild(e); } if(typeof(window.__lookbook) === \'object\') if(d.readyState === \'complete\') { window.__lookbook.init(); } }(document, \'script\', \'lookbook-script\'); </script> <div class="rs-adblock"> <img src="//assets.rewardstyle.com/images/search/350.gif" style="width:15px;height:15px;" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" /> <noscript>'.$enableJs.'</noscript> </div> </div>'; return $out; } add_shortcode('show_lookbook_widget', 'lookbook_show_widget'); function shopthepost_show_widget($atts) { extract(shortcode_atts(array( 'id' => '0', 'adblock' => 'Turn off your ad blocker to view content', 'enableJs' => 'Turn on your JavaScript to view content' ), $atts)); $out = '<div class="shopthepost-widget" data-widget-id="'.$id.'"> <script type="text/javascript" language="javascript"> !function(d,s,id){ var e, p = /^http:/.test(d.location) ? \'http\' : \'https\'; if(!d.getElementById(id)) { e = d.createElement(s); e.id = id; e.src = p + \'://widgets.rewardstyle.com/js/shopthepost.js\'; d.body.appendChild(e); } if(typeof window.__stp === \'object\') if(d.readyState === \'complete\') { window.__stp.init(); } }(document, \'script\', \'shopthepost-script\'); </script> <div class="rs-adblock"> <img src="//assets.rewardstyle.com/images/search/350.gif" style="width:15px;height:15px;" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" /> <noscript>'.$enableJs.'</noscript> </div> </div>'; return $out; } add_shortcode('show_shopthepost_widget', 'shopthepost_show_widget'); function boutique_show_widget($atts) { extract(shortcode_atts(array( 'id' => '0', 'adblock' => 'Turn off your ad blocker to view content', 'enableJs' => 'Turn on your JavaScript to view content' ), $atts)); $out = '<div class="boutique-widget" data-widget-id="'.$id.'"> <script type="text/javascript" language="javascript"> !function(d,s,id){ var e, p = /^http:/.test(d.location) ? \'http\' : \'https\'; if(!d.getElementById(id)) { e = d.createElement(s); e.id = id; e.src = p + \'://widgets.rewardstyle.com/js/boutique.js\'; d.body.appendChild(e); } if(typeof window.__boutique === \'object\') if(d.readyState === \'complete\') { window.__boutique.init(); } }(document, \'script\', \'boutique-script\'); </script> <div class="rs-adblock"> <img src="//assets.rewardstyle.com/images/search/350.gif" style="width:15px;height:15px;" onerror="this.parentNode.innerHTML=\''.$adblock.'\'" /> <noscript>'.$enableJs.'</noscript> </div> </div>'; return $out; } add_shortcode('show_boutique_widget', 'boutique_show_widget'); add_filter('widget_text', 'do_shortcode'); add_filter('the_excerpt', 'do_shortcode'); ?> and then my front-page.php <?php /* * Template Name: */ get_header(); get_template_part ('inc/carousel'); $the_query = new WP_Query( [ 'posts_per_page' => 14, 'paged' => get_query_var('paged', 1) ] ); if ( $the_query->have_posts() ) { ?> <div id="ajax"> <?php $i = 0; while ( $the_query->have_posts() ) { $the_query->the_post(); if ( $i % 7 === 0 ) { // Large post: on the first iteration and every 7th post after... ?> <article <?php post_class( 'col-sm-12 col-md-12' ); ?>> <div class="large-front-container"> <?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?> </div> <h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p> <div class="front-post-info"> <a class="moretext" href="<?php the_permalink(); ?>">Read more</a> <?php get_template_part ('front-page-shop'); ?> <?php get_template_part( 'share-buttons' ); ?> <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div> <?php echo do_shortcode("show_shopthepost_widget"); ?> </article><?php } else { // Small posts ?> <article <?php post_class( 'col-sm-6 col-md-4' ); ?>> <div class="front-thumbnail-image"><?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?></div> <a class="front-page-post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p> <a class="moretext" href="<?php the_permalink(); ?>">Read more</a> <?php get_template_part ('front-page-shop'); ?> <?php get_template_part( 'share-buttons' ); ?> <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div> <?php echo do_shortcode("show_shopthepost_widget"); ?> </article> <?php } $i++; }?> </div> <?php if(get_query_var('paged') < $the_query->max_num_pages) { load_more_button(); } } elseif (!get_query_var('paged') || get_query_var('paged') == '1') { echo '<p>Sorry, no posts matched your criteria.</p>'; } wp_reset_postdata(); get_footer(); updated front-page.php <?php /* * Template Name: */ get_header(); get_template_part ('inc/carousel'); $the_query = new WP_Query( [ 'posts_per_page' => 14, 'paged' => get_query_var('paged', 1) ] ); if ( $the_query->have_posts() ) { ?> <div id="ajax"> <?php $i = 0; while ( $the_query->have_posts() ) { $the_query->the_post(); if ( $i % 7 === 0 ) { // Large post: on the first iteration and every 7th post after... ?> <article <?php post_class( 'col-sm-12 col-md-12' ); ?>> <div class="large-front-container"> <?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?> </div> <h2><a class="post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p> <div class="front-post-info"> <a class="moretext" href="<?php the_permalink(); ?>">Read more</a> <?php get_template_part ('front-page-shop'); ?> <?php get_template_part( 'share-buttons' ); ?> <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div> <?php echo do_shortcode("show_shopthepost_widget"); ?> <?php if (shortcode_exists('show_shopthepost_widget')) { // Get the value of the custom field defined in the editor $widgetId = get_post_meta(get_the_ID(), 'shortcode_id', true); // Check if a value is set if (!empty($widgetId)) { $shortcode = '[show_shopthepost_widget id="'.$widgetId.'"]'; } else { // or use a default widget $shortcode = '[show_shopthepost_widget id="12345_some_id"]'; } do_shortcode($shortcode); } ?> </article><?php } else { // Small posts ?> <article <?php post_class( 'col-sm-6 col-md-4' ); ?>> <div class="front-thumbnail-image"><?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?></div> <a class="front-page-post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p> <a class="moretext" href="<?php the_permalink(); ?>">Read more</a> <?php get_template_part ('front-page-shop'); ?> <?php get_template_part( 'share-buttons' ); ?> <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div> <?php if (shortcode_exists('show_shopthepost_widget')) { // Get the value of the custom field defined in the editor $widgetId = get_post_meta(get_the_ID(), 'shortcode_id', true); // Check if a value is set if (!empty($widgetId)) { $shortcode = '[show_shopthepost_widget id="'.$widgetId.'"]'; } else { // or use a default widget $shortcode = '[show_shopthepost_widget id="12345_some_id"]'; } do_shortcode($shortcode); } ?> </article> <?php } $i++; }?> </div> <?php if(get_query_var('paged') < $the_query->max_num_pages) { load_more_button(); } } elseif (!get_query_var('paged') || get_query_var('paged') == '1') { echo '<p>Sorry, no posts matched your criteria.</p>'; } wp_reset_postdata(); get_footer();
Actually, do_shortcode() is exactly what you need, except you need to input the entire shortcode as is, without altering it (ie removing the []) This should display the widget above just fine: echo do_shortcode('[show_shopthepost_widget id="2371382"]'); Also, I would suggest wrapping it in a shortcode_exists() check, otherwise it will spit out the shortcode on the page if the plugin is disabled or unavailable for any reason. Note that this function requires the shortcode to be passed without the []. if (shortcode_exists('show_shopthepost_widget')) { echo do_shortcode('[show_shopthepost_widget id="2371382"]'); } The Wordpress Stack Exchange site might have more answers for you if you're ever stuck with WP. Hope this helps! edit Dynamic solution If you need to display a different shortcode on each page, you can modify the above code to use custom fields to display any widget you associate with a page, or display a default widget if you didn't set any. In the content editor To do so, you need to edit your pages in your site's wp-admin and add a custom field to them with the ID of the widget you want to appear on the page, and name it something sensible like shortcode_id. In your theme You need to modify the logic to get the post meta with the shortcode_id key associated with your current page, and create the shortcode to display accordingly. Also, you can set a default widget that will appear if you don't set any for a page. if (shortcode_exists('show_shopthepost_widget')) { // Get the value of the custom field defined in the editor $widgetId = get_post_meta(get_the_ID(), 'shortcode_id', true); // Check if a value is set if (!empty($widgetId)) { $shortcode = '[show_shopthepost_widget id="'.$widgetId.'"]'; } else { // or use a default widget $shortcode = '[show_shopthepost_widget id="12345_some_id"]'; } echo do_shortcode($shortcode); }
A do_shortcode must be similar to <?php do_shortcode("[show_shopthepost_widget]"); ?> - your code doesn't have []
Can you remove wordpress post tags with js/php after certain date (ACF date time picker)?
So my website lists upcoming film screenings in my area. I'm using the ACF date time picker to only show posts/film screenings that are in the future in the wordpress loop. I have tags filtering the results dynamically using ajax (thanks to https://www.bobz.co/ajax-filter-posts-tag/) except there are tags that aren't relevant to the results because they belong to posts that are older than the current date (past screenings). *For example on the website, the 'animated film festival' is still coming up with the other tags. I don't know if it's possible to delete a posts tags with PHP (within the post template while it loops through other posts) - and to delete the posts tags if the ACF date time field for that post is older than the current date. I haven't found much luck googling this and I am a bit of a noob so... This is my site: http://pigcine.pamrosel.com/ This is what I'm doing in my functions.php file at the moment: // Get all tags and display function tags_filter() { $tax = 'post_tag'; $terms = get_terms( $tax ); $count = count( $terms ); if ( $count > 0 ): ?> <div class="post-tags"> <?php foreach ( $terms as $term ) { $term_link = get_term_link( $term, $tax ); echo '' . $term->name . ' '; } ?> </div> <?php endif; } // Script for getting posts function ajax_filter_get_posts( $taxonomy ) { // Verify nonce if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce($_POST['afp_nonce'], 'afp_nonce' ) ) die('Permission denied'); $taxonomy = $_POST['taxonomy']; // WP Query $args = array( 'tag' => $taxonomy, 'post_type' => 'post', 'posts_per_page' => -1, 'meta_key' => 'datetime', 'orderby' => array( 'datetime' => 'ASC' ), ); // If taxonomy is not set, remove key from array and get all posts if( !$taxonomy ) { unset( $args['tag'] ); } $query = new WP_Query( $args ); if ( $query->have_posts() ) : while($query->have_posts()) : $query>the_post(); $today = date('Y-m-d H:i:s', strtotime('+9 hours')); $event_date = get_field('datetime'); if (strtotime($today) <= strtotime($event_date)) { ?> <div class="sl"> <div class="sl_closed"> <div class="col-2-8"><div class="modulepad"> <p><?php the_field('datetime'); ?></p> </div></div> <div class="col-3-8"><div class="modulepad"> <p><?php the_title(); ?><br> <?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["directors"]); ?> </p> </div></div> <div class="col-3-8"><div class="modulepad"> <p><?php the_field('location_name'); ?><br> <?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["countries"]) . " "; echo $movie["released"] . " "; echo implode(", ", $movie["runtime"]); ?> </p> </div></div> </div><!--SL_CLOSED--> <?php } endwhile; ?> <?php else: ?> <h2>No posts found</h2> <?php endif; die(); } add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts'); add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
Change date format advanced custom fields wordpress
Hi I am working with advanced custom fields with wordpress and im trying to fix the date to show : 24/01/201 instead of 01/24/2013 I have been looking at the ACF site but I can't seem to find why it is doing this. please find attached my code :) <?php // start query $query_args = array( // number of featured items to show 'posts_per_page' => '-1', 'post_type' => 'product', ); $args = array( 'meta_key' => 'time_&_date', 'orderby' => 'meta_value_num', 'order' => 'DESC' ); $the_query = new WP_Query( $args ); while ( $the_query->have_posts() ) : $the_query->the_post(); $date = DateTime::createFromFormat('Ymd', get_field('time_&_date')); echo $date->format('M d, Y'); endwhile; // start loop $wp_query = new WP_Query($query_args); if ($wp_query->have_posts()) { echo '<ul class="eventslist">'; echo '</br>'; echo '</br>'; // start while while($wp_query->have_posts()) : $wp_query->the_post(); $_product = new jigoshop_product(get_the_ID()); echo '<li>'; // Event container echo '<a href="'.get_permalink().'">'; // Event title echo '<div class="loop_title lightlinksnounderline"> <span>•</span>' . the_title('','',false); echo '</a>'; echo '</div>'; echo '<h3 class="field_title_loop">Date & Time: '; the_field('time_&_date'); echo '</h3>'; echo '<div class="cart_button">' ; do_action('jigoshop_after_shop_loop_item', $post, $_product ); echo '</div>'; echo '</li>'; echo '<div class="price_cart">' ; do_action('jigoshop_after_shop_loop_item_title', $post, $_product); echo '</div>'; echo '</br>'; echo '<div class="cart_line">'; echo '</div>'; // end while endwhile; echo '</ul>'; // end loop // reset query wp_reset_query(); } ?>
shouldn't your $date->format be (d M Y) for this?