I am new to Yii2 and have been trying to work out how to hide/show certain fields on the form based on a dropDownList selection with client-side validation.
Basically I have a model and form view that collects information relating to 'candidates' and I wish to apply the following logic:
Only display the fields 'assigned_to' and 'phone' if the dropDownList selection for 'qualification_id' = 2.
The fields 'assigned_to' and 'phone' are required if 'qualification_id' = 2 (else optional)
My code is as follows, albeit not working as I need it to. The client-side validation is not working (i.e.'assigned_to' and 'phone' are not required when qualification_id = 2). I have not been able to work out how to hide/show the fields dynamically based on the 'qualification_id' selection. I assume some javascript is required for this.
Any assistance would be greatly appreciated!
MODEL:
namespace frontend\models;
use Yii;
/**
* This is the model class for table "candidate".
*
* #property int $candidate_id
* #property string $name
* #property int $qualification_id
* #property string $assigned_to
* #property string $phone
public static function tableName()
{
return 'candidate';
}
public function rules()
{
return [
[['candidate_id', 'qualification_id', 'name'], 'required']
[['candidate_id', 'qualification_id'], 'integer'],
[['name', 'assigned_to’, 'phone’], 'string'],
[['assigned_to', 'phone'],'required','when'=>function($model){
return ($model->qualification_id == 2);
},
'whenClient'=>"function(attribute, value){
return $('#qualification_id').val() == 2;
}"],
VIEW (form):
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\QualificationType;
/* #var $this yii\web\View */
/* #var $model frontend\models\Candidate */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="candidate-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'qualification_id')->dropDownList(
ArrayHelper::map(QualificationType::find()->all(),'qualification_id','qualification'),
[
'prompt'=>'Select...',
'id' => 'review_type_id',
'onchange' => 'changeQualification()'
]
) ?>
<?= $form->field($model, 'assigned_to')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'phone')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<<JS
function changeQualification() {
if ($('#qualification_id').val() == 2) {
$('#assigned_to').show();
$('#name).show();
} else {
$('#assigned_to).hide();
$('#name).hide();
}
}
JS;
$this->registerJs($script);
?>
Please try like this
In view
<div class="candidate-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'qualification_id')->dropDownList(
ArrayHelper::map(QualificationType::find()->all(),'qualification_id','qualification'),
['prompt'=>'Select...', 'id' => 'qualification_id', 'onchange' => 'changeQualificationType()']
) ?>
<?= $form->field($model, 'assigned_to)->textInput(['id' => 'assigned_to_Input', 'maxlength' => true]) ?>
<?= $form->field($model, 'phone')->textInput(['id' => 'phone_input', 'maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<<JS
function changeQualificationType() {
if ($('#qualification_id').val() == 2) {
$('#assigned_to_input').closest('.form-group').show();
$('#phone_input').closest('.form-group').show();
} else {
$('#assigned_to_input').closest('.form-group').hide();
$('#phone_input').closest('.form-group').hide();
}
}
JS;
$this->registerJs($script);
In Model
public function rules()
{
return [
[['candidate_id', 'qualification_id', 'name'], 'required']
[['candidate_id', 'qualification_id'], 'integer'],
[['name', 'assignedTo, 'phone’], 'string'],
[['assignedTo', 'phone'],'required','when'=>function($model){
return ($model->qualification_id == 2);
},
'whenClient'=>"function(attribute, value){
return $('#qualification_id').val() == 2;
}"],
Don't forget to set custom id in ActiveFormField. All of field id should be matched with functions of Jquery and Model.
The most frustrating thing is that this code was working then suddenly it startet returning an entire page of HTML rather than just the HTML code from the template below.
I'm calling an ajax function and passing it an object that looks like this (result of console.log(data)):
Here is my ajax function:
function mapResults (data) {
//console.log(data);
$.ajax({
type: 'post',
url: wp_ajax.wp_url,
data: {action: 'marker_in_viewport', resultsArray: data},
success: function(result) {
$('#map-results').html(result);
},
error: function(result) {
console.warn(result);
}
});
}
Here is the PHP code that handles the request:
<?php
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
function marker_in_viewport() {
$locationResults = $_POST['resultsArray'];
$posts = get_posts(array(
'post_type' => 'accommodation',
'post__in' => $locationResults,
));
?>
<?php
//require result template
//require_once ('map-results.php');
if( $posts ) { ?>
<?php foreach( $posts as $post ) {
$id = $post->ID;
$title = get_the_title($id);
$location = get_field('location', $id);
$permalink = get_permalink( $id );
$rooms_available_from = get_field('rooms_available_from', $id);
$gallery = get_field('gallery', $id);
?>
<div class="col-md-4 accom-results-cont pb-3">
<?php if ($gallery) : ?>
<a href="<?= $permalink; ?>" title="Learn more about <?= $title; ?>">
<div class="accom-results-img-cont">
<img class="img-fluid" src="<?= $gallery['url']; ?>" alt="An image of <?= $title; ?>" >
</div>
<?php endif; ?>
<div class="accom-results-data-cont pr-3 pt-3">
<?php if ( $title ) : ?>
<p class="results-title"><b><?= $title ?></b></p>
<?php endif; ?>
</div>
</a>
</div>
<?php } ?>
<?php } ?>
<?php wp_die(); ?>
<?php } ?>
And in my page template I have the following div where I want the results to be populated:
<div id="map-results"class="row py-5"></div>
Any ideas what I have done wrong?
I revised your code. try the below code.
function mapResults (data) {
$.ajax({
type: 'post',
dataType : "json",
url: wp_ajax.wp_url,
data: {action: 'marker_in_viewport', resultsArray: data},
success: function(result) {
$('#map-results').html(result.data.html);
},error: function(result) {
console.warn(result);
}
});
}
You can use ob_start() and ob_get_clean().
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
function marker_in_viewport() {
$locationResults = $_POST['resultsArray'];
$posts = get_posts(array(
'post_type' => 'accommodation',
'post__in' => $locationResults
));
ob_start();
if( $posts ) { foreach( $posts as $post ) {
$id = $post->ID;
$title = get_the_title($id);
$location = get_field('location', $id);
$permalink = get_permalink( $id );
$gallery = get_field('gallery', $id);
$rooms_available_from = get_field('rooms_available_from', $id);
?>
<div class="col-md-4 accom-results-cont pb-3">
<a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
<?php if ( $gallery ) : ?>
<div class="accom-results-img-cont">
<img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
</div>
<?php endif; ?>
<div class="accom-results-data-cont pr-3 pt-3">
<?php if ( $title ) : ?>
<p class="results-title"><b><?php echo $title; ?></b></p>
<?php endif; ?>
</div>
</a>
</div>
<?php } }
$html = ob_get_clean();
wp_send_json_success(array(
'html' => $html
));
}
USEFUL LINKS
ob_start()
ob_get_clean()
wp_send_json_success()
Finally got this working after about a week of trying!!
Here is my AJAX Function inside js/script.js
$.ajax({
type: 'post',
//dataType: 'json',
url: map_ajax_obj.ajaxurl,
data: {action: 'marker_in_viewport', resultsArray: data, nonce: map_ajax_obj.nonce},
success: function(result) {
//console.log(result);
$('#map-results').html(result);
},
error: function(result) {
console.warn(result);
}
});
Inside my functions.php file I have enqueued and localised my wp-admin.php like this
function load_req_scripts()
{
wp_register_script( 'custom-js-script', get_template_directory_uri() . '/js/script.js', array( 'jquery'), '', true);
wp_enqueue_script( 'custom-js-script' );
wp_localize_script(
'custom-js-script', //I think this is a dependancy on the above script though not entirely sure
'map_ajax_obj',
array (
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax_nonce')
)
);
}
add_action( 'wp_enqueue_scripts', 'load_req_scripts' );
require_once('ajax/accommodation-ajax.php'); //where to handle and return the data to the ajax call
here is the function in my accommodation-ajax.php file
<?php
function marker_in_viewport() {
$locationResults = $_POST['resultsArray'];
if (!empty($locationResults)) {
$posts = get_posts(array(
'post_type' => 'accommodation',
'post__in' => $locationResults
));
if( $posts ) {
foreach( $posts as $post ) {
$id = $post->ID;
$title = get_the_title($id);
$location = get_field('location', $id);
$permalink = get_permalink( $id );
$gallery = get_field('gallery', $id);
$rooms_available_from = get_field('rooms_available_from', $id);
?>
<div class="col-md-4 accom-results-cont pb-3">
<a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
<?php if ( $gallery ) : ?>
<div class="accom-results-img-cont">
<img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
</div>
<?php endif; ?>
<div class="accom-results-data-cont pr-3 pt-3">
<?php if ( $title ) : ?>
<p class="results-title"><b><?php echo $title; ?></b></p>
<?php endif; ?>
</div>
</a>
</div>
<?php } //end for each
} //end if posts
} //end if not empty
else {
echo "No results found please search again!";
}
wp_die();
}
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
As to why this now works compared to what I posted above I have no idea!! Could it be the NONCE? though I'm not using it to authenticate in the PHP function. Anyway hope this helps someone or my future self next time I'm banging my head against the wall with wordpress ajax calls.
UPDATE So this stopped working for me again then I realised that it was working when logged in as admin and not workign for logged out and all other users. Because this is a membership site I wanted to block anyone that wasn't an admin form the admin area. Didn't realise that this function was also blocking access to the admin-ajax.php file too. This was redirecting to the Homepage hence why the AJAX call was returning the entire page HTML.
SO I needed to update my function to include:
&& ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX )
to the following:
//block users from admin if not admin
function blockusers_wps_init() {
if ( is_admin() && ! current_user_can( 'administrator' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}
add_action( 'init', 'blockusers_wps_init' );
Don’t use wp_die() it’s returning html, use just die()
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>
i am developing a web application using yii2 .i did a thumbs up and thumbs down buttons. it just insert the user and what the person choose up /down into a table . but i don't think i am going about it the right way because after the user clicks up or down it refreshes. i want it to insert without refreshing.
this is the view
<?php $form = ActiveForm::begin(['id' => "contact-form",
'enableClientValidation' => false,
]);
?>
<input type="hidden" class="form-control" value="up" required="true" name="Thumbs[rate]" id="topic" placeholder="topic">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
<button type="submit" id="save" name="save">enter</button>
<?php ActiveForm::end(); ?>
<?php $form = ActiveForm::begin(['id' => "contact-form",
'enableClientValidation' => false,
]);
?>
<input type="hidden" class="form-control" hidden="true" value="down" required="true" name="Thumbs[rate]" id="topic" placeholder="topic">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
<?php ActiveForm::end(); ?>
if you notice i seem to have kept the value of up and down in a input with type hidden. just want to know of a better way to do it.
this is my controller function
public function actionBlog()
{
$thumbs= new Thumbs();
$thumbs->user=Yii::$app->user->identity->email;
$thumbs->topic_id = '1';
if ($thumbs->load(Yii::$app->request->post()) && $thumbs->validate()) {
$thumbs->load($_POST);
$thumbs->save();
return $this->refresh();
}
return $this->render('blog');
}
i also tried to used ajax but it seems not to be working well
You can use Pjax for this.
Here is a simple example that you should be able to apply to your problem. I have included some comments for clarity, but I would heavily advise checking out this tutorial for further information and some extended examples.
View (vote.php):
<?php
use yii\widgets\Pjax;
use yii\helpers\Html;
use common\models\Thumbs;
?>
<?php Pjax::begin(['enablePushState' => false]); ?>
<?= Html::a('', ['site/upvote'], ['class' => 'btn btn-lg btn-warning glyphicon glyphicon-arrow-up']) ?>
<?= Html::a('', ['site/downvote'], ['class' => 'btn btn-lg btn-primary glyphicon glyphicon-arrow-down']) ?>
<h1><?= Thumbs::find()->where(['=', 'post_id', '1'])->one()->votes ?></h1>
<?php Pjax::end(); ?>
SiteController:
public function actionVote()
{
return $this->render('vote');
}
public function actionUpvote()
{
// find the thumbs record for the related post
$thumbsRecord = Thumbs::find()->where(['=', 'post_id', '1'])->one();
// increment the thumbs count
$thumbsRecord->votes += 1;
// ensure change persists to db
$thumbsRecord->save();
// return value to the view
return $this->render('vote', [
'votes' => $thumbsRecord->votes,
]);
}
/**
* Similar functionality to actionUpvote
*/
public function actionDownvote()
{
$thumbsRecord = Thumbs::find()->where(['=', 'post_id', '1'])->one();
$thumbsRecord->votes -= 1;
$thumbsRecord->save();
return $this->render('vote', [
'votes' => $thumbsRecord->votes,
]);
}
The model is just a table that contains the following fields:
id (int, primary key)
post_id (int)
votes (int, default 0)