Hi everyone I tried to serialize a form by his ID using jquery method serialize().
Html code:
<form name="structure_form" id="structure_form" method="post">
<div id="add_sections" class="postbox add_section_box">
<button type="button" class="handlediv button-link" aria-expanded="true"><span class="screen-reader-text">Commuta il pannello: Add section</span><span class="toggle-indicator" aria-hidden="true"></span></button>
<h3 class="handle ui-sortable-handle structure_title"><span>Add Section</span></h3>
<div class="inside">
#CONTENT#
<input type="button" class="button button-primary button-large saveSections" id="save" value="Save">
</div>
</div>
</form>
Js code:
$('.saveSections').on('click', function () {
var serializedForm = $('#structure_form').serialize();
$.post(ajaxurl, {action: 'saveConfiguration', serializedForm: serializedForm}, function (data) {
alert(data);
});
console.log("configuration saved");
});
Php code:
function saveConfiguration() {
print_r($_POST['serializedForm']);
exit;
}
function add_section_meta_box() {
global $post;
if ($post->post_type == "minisites") {
$addSection = file_get_contents(dirname(__FILE__) . '/templates/components/add_section_box.html');
$addSection = str_replace('#CONTENT#', Utils::createSelect(), $addSection);
}
echo Utils::includeScripts();
echo $addSection;
}
This is Utils::createSelect
public static function createSelect() {
$sections = get_posts(array(
'post_type' => 'sections',
'posts_per_page' => 10)
);
$html = '<select id="sections" name="item">';
foreach ($sections as $section) {
$html .= '<option value="' . $section->ID . '">' . $section->post_title . '</option>';
}
$html .= '</select><br><br>';
$html .= '<input type="button" class="button button-primary button-large addSection" id="add" value="Add">';
return $html;
}
the output is empty or undefined.
I think that the problem is the ID's form because if I change $('#structure_form') with $('form') it works fine.
Thanks in advance.
Edit(Update):
I add code in order that it works
Create custom_post_type, box, ecc (Plugin)
<?php
//error_reporting(E_ALL);
//ini_set("display_errors", 'on');
/*
Plugin Name: deaSiteBuilder
Version: 1.0
Description:
Author: Giuseppe Giubaldo
Author URI:
*/
require_once 'utils.php';
require_once __DIR__ . '/../../../vendor/autoload.php';
use Symfony\Component\Yaml\Parser;
add_action('init', 'create_post_type');
function create_post_type() {
register_post_type('minisites', array(
'labels' => array(
'name' => __('Minisites'),
'singular_name' => __('Minisite'),
),
'public' => true,
'has_archive' => true,
)
);
register_post_type('sections', array(
'labels' => array(
'name' => __('Sections'),
'singular_name' => __('Section'),
),
'public' => true,
'has_archive' => true,
));
}
//Add default meta box
add_action('edit_form_after_editor', 'add_section_meta_box');
function add_section_meta_box() {
global $post;
if ($post->post_type == "minisites") {
$addSection = file_get_contents(dirname(__FILE__) . '/templates/components/add_section_box.html');
$addSection = str_replace('#CONTENT#', Utils::createSelect(), $addSection);
}
echo Utils::includeScripts();
echo $addSection;
}
//Our custom meta box will be loaded on ajax
function add_structure_meta_box($post_name) {
$sectionStructureBox = file_get_contents(dirname(__FILE__) . '/templates/components/sectionStructureBox.html');
$sectionStructureBox = str_replace('#ELEMENT#', strtoupper($post_name), $sectionStructureBox);
$sectionStructureBox = str_replace('#CONTENT#', $post_name, $sectionStructureBox);
echo $sectionStructureBox;
}
//Call ajax
add_action('wp_ajax_addStructureBox', 'addStructureBox');
function addStructureBox() {
add_structure_meta_box($_POST['section']);
exit;
}
add_action('wp_ajax_saveConfiguration', 'saveConfiguration');
function saveConfiguration() {
echo $_POST['serializedForm'];
exit;
}
Html pages:
sections_box
<form name="structure_form" id="structure_form" method="post">
<div id="add_sections" class="postbox add_section_box">
<button type="button" class="handlediv button-link" aria-expanded="true"><span class="screen-reader-text">Commuta il pannello: Add section</span><span class="toggle-indicator" aria-hidden="true"></span></button>
<h3 class="handle ui-sortable-handle structure_title"><span>Add Section</span></h3>
<div class="inside">
#CONTENT#
<input type="button" class="button button-primary button-large saveSections" id="save" value="Save">
</div>
</div>
</form>
structure_box
<div id="section_structure_box" class="postbox section_box">
<button type="button" class="handlediv button-link" aria-expanded="true"><span class="screen-reader-text">Commuta il pannello: Section Structure</span><span class="toggle-indicator" aria-hidden="true"></span></button>
<!-- <div class="handlediv" title="Click to toggle"><br>
</div>-->
<h3 class="handle ui-sortable-handle structure_title"><span>Section Structure - #ELEMENT#</span></h3>
<div class="inside">
#CONTENT#
</div>
<!--<input type="button" class="button button-primary button-large remove_box" id="remove" value="Remove">-->
Class Utils:
<?php
class Utils {
public static function createSelect() {
$sections = get_posts(array(
'post_type' => 'sections',
'posts_per_page' => 10)
);
$html = '<select id="sections" name="item">';
foreach ($sections as $section) {
$html .= '<option value="' . $section->ID . '">' . $section->post_title . '</option>';
}
$html .= '</select><br><br>';
$html .= '<input type="button" class="button button-primary button-large addSection" id="add" value="Add">';
return $html;
}
public static function includeScripts() {
$html = '<link rel="stylesheet" type="text/css" href="' . plugins_url('deaSiteBuilder/assets/css/style.css', dirname(__FILE__)) . '">';
$html .= '<script src="' . plugins_url('deaSiteBuilder/assets/js/jquery.min.js', dirname(__FILE__)) . '"></script>';
$html .= '<script src="' . plugins_url('deaSiteBuilder/assets/js/jquery-ui.js', dirname(__FILE__)) . '"></script>';
$html .= '<script src="' . plugins_url('deaSiteBuilder/assets/js/plugin.js', dirname(__FILE__)) . '"></script>';
return $html;
}
}
And js code:
$(document).ready(function () {
$('.addSection').on('click', function () {
var selectedSection = $('#sections option:selected').text();
$.post(ajaxurl, {action: 'addStructureBox', section: selectedSection}, function (data) {
$('#add_sections').parent().append(data);
console.log("section added");
});
});
$('.saveSections').on('click', function () {
var serializedForm = $('body form#structure_form').serialize();
alert(serializedForm);
$.post(ajaxurl, {action: 'saveConfiguration', serializedForm: serializedForm}, function (data) {
});
console.log("configuration saved");
});
});
try this one,
$('.saveSections').on('click', function () {
var serializedForm = $('#structure_form').serialize();
serializedForm.push({name: 'action', value: 'saveConfiguration'});
$.post(ajaxurl, serializedForm, function (data) {
alert(data);
});
console.log("configuration saved");
});
Related
i iclude a wordpress media selector in my wordpress plugin.
i got this error :
Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
error
i added to this code to wp-config.php file :
`
/** WordPress değişkenlerini ve yollarını kurar. */
require_once ABSPATH . 'wp-settings.php';
define( 'UPLOADS', 'wp-content/uploads' );
`
and added to myportfolio-form.php file
<?php
add_action( 'admin_footer', 'media_selector_print_scripts' );
function media_selector_print_scripts() {
$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );
?><script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>; // Set this
jQuery('#upload_image_button').on('click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
$( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );
$( '#image_attachment_id' ).val( attachment.id );
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery( 'a.add_media' ).on( 'click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script><?php
}
function portfolio_admin_myprojects_page_handler()
{
global $wpdb;
$table = new Portfolio_MyProjects_List_Table();
$table->prepare_items();
$message = '';
if ('delete' === $table->current_action()) {
$message = '<div class="updated below-h2" id="message"><p>' . sprintf(__('Items deleted: %d', 'portfolio-admin-myresume'), count($_REQUEST['ID'])) . '</p></div>';
}
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects_form');?>"><?php _e('Add new', 'portfolio-admin-myresume')?></a>
</h2>
<?php echo $message; ?>
<form id="myprojects-table" method="POST">
<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
<?php $table->display() ?>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_page_handler()
{
global $wpdb;
$table_name = $wpdb->prefix . 'portfolio_myprojects';
$message = '';
$notice = '';
$default = array(
'ID' => 0,
'projects_name' => '',
'projects_category' => '',
'projects_link' => '',
'projects_image' => '',
'order' => '',
);
if ( isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
$item = shortcode_atts($default, $_REQUEST);
$item_valid = portfolio_admin_validate_myprojects($item);
if ($item_valid === true) {
if ($item['ID'] == 0) {
$result = $wpdb->insert($table_name, $item);
$item['ID'] = $wpdb->insert_id;
if ($result) {
$message = __('Item was successfully saved', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while saving item', 'portfolio-admin-myresume');
}
} else {
$result = $wpdb->update($table_name, $item, array('ID' => $item['ID']));
if ($result) {
$message = __('Item was successfully updated', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while updating item', 'portfolio-admin-myresume');
}
}
} else {
$notice = $item_valid;
}
}
else {
$item = $default;
if (isset($_REQUEST['ID'])) {
$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $_REQUEST['ID']), ARRAY_A);
if (!$item) {
$item = $default;
$notice = __('Item not found', 'portfolio-admin-myresume');
}
}
}
add_meta_box('myprojects_form_meta_box', __('Work Details', 'portfolio-admin-myresume'), 'portfolio_admin_projects_form_meta_box_handler', 'myprojects', 'normal', 'default');
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects');?>"><?php _e('back to list', 'portfolio-admin-myresume')?></a>
</h2>
<?php if (!empty($notice)): ?>
<div id="notice" class="error"><p><?php echo $notice ?></p></div>
<?php endif;?>
<?php if (!empty($message)): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif;?>
<form id="form" method="POST">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<input type="hidden" name="ID" value="<?php echo $item['ID'] ?>"/>
<div class="metabox-holder" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<?php do_meta_boxes('myprojects', 'normal', $item); ?>
<input type="submit" value="<?php _e('Save', 'portfolio-admin-myresume')?>" id="submit" class="button-primary" name="submit">
</div>
</div>
</div>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_meta_box_handler($item)
{
// Save attachment ID
if ( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :
update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );
endif;
wp_enqueue_media();
?>
<tbody >
<div class="formdatabc">
<form >
<div class="form2bc">
<p>
<label for="projects_name"><?php _e('Project Name:', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_name" name="projects_name" type="text" value="<?php echo esc_attr($item['projects_name'])?>"
required>
</p>
</div>
<div class="form2bc">
<p>
<label for="projects_category"><?php _e('Project Category', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_category" name="skills_percent" type="text" value="<?php echo esc_attr($item['projects_category'])?>"
required>
</p>
</div>
<div class="form3bc">
</div>
<div>
<p>
<label for="projects_link"><?php _e('Project Link:', 'portfolio-admin-myresume')?></label>
<br>
<textarea id="projects_link" name="projects_link" cols="100" rows="3" maxlength="240"><?php echo esc_attr($item['projects_link'])?></textarea>
</p>
</div>
<div class='image-preview-wrapper'>
<img id='image-preview' src='' width='100' height='100' style='max-height: 100px; width: 100px;'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value=''>
</form>
</div>
</tbody>
<?php
}
`
i tried to iclude wordpress media selector to my plugin but it doesnt work.
error : Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
You need to change permissions of directories on server itself
chmod -R 777 /path/to/web-root/wp-content/uploads
(Linux example, this will change all files)
chmod 777 /path/to/web-root/wp-content
(this will change only directory itself, not all files)
I am trying to build a component that looks like a WooCommerce product page, it should have a filter(category), a search box, and pagination, and a dropdown that users can select how many posts they want to display on the page. Currently, I am using ajax and a jQuery plugin called twbs-pagination to build this function, the code looks awful, and is not organized. I am wondering if timber has a native way to do it.
JS FILE
jQuery(document).ready(function ($) {
function ftGetPost(page = 1) {
$.ajax({
type: 'GET',
url: ajaxurl,
dataType: 'JSON',
data: {
'action': 'flatsome_get_posts',
'paged': page,
'category': $('#ft-category').val(),
'keyword': $('input[name=ft-keyword]').val(),
},
success: function (data) {
console.log(data);
$('#ft-block__posts-holder').empty().html(data.data.posts);
$('#ft-block__pager').twbsPagination({
totalPages: data.data.pages,
visiblePages: 7,
onPageClick: function (event, page) {
ftGetPost(page);
},
});
},
});
}
ftGetPost();
$('#ft-category').change(function () {
ftGetPost();
});
$('#ft-do-search').click(function () {
ftGetPost();
});
});
PHP FILE
//fetch books from wp
add_action('wp_head', function () {
?>
<script type="text/javascript">
//<![CDATA[
ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
//]]>
</script>
<?php
}, 1);
add_action('wp_ajax_flatsome_get_posts', 'flatsome_get_posts');
add_action('wp_ajax_nopriv_flatsome_get_posts', 'flatsome_get_posts');
function flatsome_get_posts()
{
$paged = $_GET['paged'] ?? 1;
$posts_per_page = 4;
$args = [
'post_type' => 'books',
'paged' => $paged,
'posts_per_page' => $posts_per_page,
];
$ft_query = new WP_Query($args);
$html = '';
if ($ft_query->have_posts()) {
foreach ($ft_query->get_posts() as $post) {
$html .= '<div class="ft_post">';
$html .= '<div class="ft-post__image">';
if (has_post_thumbnail()) {
$html .= get_the_post_thumbnail($post->ID, 'full');
}
$html .= '</div>';
$html .= '<h3 class="ft-post__title" style="white-space:normal;">';
$html .= $post->post_title;
dump($post->post_title);
die();
$html .= '</h3>';
$html .= "<p>";
$html .= trim($post->post_content);
$html .= "</p>";
$html .= '</div>';
}
}
$posts = ob_get_clean();
wp_send_json_success([
'posts' => $html,
'pages' => $ft_query->max_num_pages,
]);
exit;
}
<div class="ft-block">
<div class="ft-block__header">
<label for="ft-category">Filter By</label>
<select name="category" id="ft-category">
<option value="" disabled selected>CATEGORIES</option>
<option value="BOOKS">BOOKS</option>
<option value="PODCAST">PODCAST</option>
</select>
<label>
<input type="search" name="ft-keyword">
<button id="ft-do-search">Search</button>
</label>
</div>
<div id="ft-block__posts-holder">
</div>
<div class="ft-block__footer">
<div id="ft-block__pager"></div>
</div>
</div>
TWIG Template
I want to make custom search page where I can filter results as shown in the screenshot below:
Currently my problem is that all the items of the list are coming in a single category while I want a grouped view according to different categories e.g. "Device Features", "Mobile Phone Operating System", etc. So far I've written below piece of PHP code:
<?php
$listCategories = get_categories();
if(isset($listCategories) && !empty($listCategories)){
?>
<div class="list-section">
<h3 class="list-heading">Topics</h3>
<ul id="post-grid">
<?php
foreach($listCategories as $categories){
$total_post = get_posts(array('post_type'=>'post', 'category'=>$categories->term_id, 'posts_per_page'=>'-1'));
$total_post = count($total_post);
?>
<li>
<div class="checkbox">
<input type="checkbox" id="cat<?php echo $categories->term_id; ?>" data-tax="category" data-name="<?php echo $categories->name; ?>" class="category_check" value="<?php echo $categories->term_id; ?>">
<label class="css-label" for="cat<?php echo $categories->term_id; ?>">
<span class="filter-name"><?php echo $categories->name; ?></span>
<span class="filter-count"><?php echo $total_post; ?></span>
<i class="icon fa fa-check"></i>
</label>
</div>
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
I've created my own custom plugin for searching and filtering the search result.
1. Plugin file (index.php)
<?php
/*
Plugin Name: Search and Filter
Plugin URI: http://wordpress.org
Description: Search and Filter
Author: Naveen
Version: 1.0
*/
class SearchAndFilter{
public function __construct()
{
add_action('wp_enqueue_scripts', array($this, 'AddScript'));
add_action('wp_ajax_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_noprev_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_action('wp_ajax_noprev_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_shortcode('Search', array($this, 'CreateShortcode'));
}
public function AddScript()
{
wp_enqueue_script('saf-app', plugin_dir_url(__FILE__) . '/js/app.js', array('jquery'));
wp_localize_script('saf-app', 'my_ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}
function CreateShortcode($atts)
{
ob_start();
$keyword = $_REQUEST['s'];
?>
<form action="<?php echo home_url('/'); ?>" method="get">
<input type="text" name="s" id="search_keyword" value="<?php echo $keyword; ?>" class="form-control search-input" placeholder="Search..." />
</form>
<div class="search-suggestion"></div>
<?php
$output = ob_get_clean();
return $output;
}
// search autocomplete
function AffordanceSearchData()
{
$args = array('post_type'=>array('post'),'status'=>'publish');
$output = '';
$output = '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">'.get_the_title().'</li>';
endwhile;
endif;
$output .= '<li>See All Result of '.$_POST['keyword'].' </li>';
$output .= '</ul>';
wp_reset_query();
echo $output; die;
}
// filters search data
function AffordanceSearchPageData()
{
$args = array('post_type'=>'post','status'=>'publish');
$output = '';
$output .= '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
if(isset($_POST['page_number']) && !empty($_POST['page_number']) && $_POST['page_number'] != 1){
$args['paged'] = $_POST['page_number'];
}
if(isset($_POST['categories']) && !empty($_POST['categories'])){
$args['cat'] = $_POST['categories'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">
<h3 class="resources-content-heading">'.get_the_title().'</h3>
<p class="resources-content-description">'.get_the_excerpt().'</p>
<div class="resources-action-area">
Read More <i class="fa fa-angle-right" aria-hidden="true"></i>
</div>
</li>';
endwhile;
else :
$output .= "No records";
endif;
wp_reset_query();
$output .= the_posts_pagination();
$output .= '</main>';
echo $output; die;
}
}
new SearchAndFilter();
2. Js File (app.js)
jQuery(document).ready(function ($) {
// on searching keyword
$('#search_keyword').keyup(function () {
var inputvalue = $(this).val();
if (inputvalue != '') {
GetSuggestion(inputvalue);
}
});
// on pagination click
$('.ajaxclick').on('click', "a", function () {
var page_number = $(this).attr('data-page-num');
//console.log(page_number);
var current_page = $('.ajaxclick .current').attr('data-page-num');
var keyword = $('#search_keyword').val();
GetSearchData(keyword, page_number);
});
// on category select
$('.category_check').on('click', function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var blogWrapper = $('.blogWrapper');
var catTagHTML = '<ul>';
blogWrapper.find('input.category_check:checked').each(function () {
catTagHTML += '<li><a class="exclude_cat" href="javascript:void(0)" data-cat-id="' + $(this).attr('value') + '">' + $(this).attr('data-name') + '</a></li>';
});
$('#selected-category-tags').html(catTagHTML);
GetSearchData(keyword, page_number);
});
// on tag click
$('#selected-category-tags').on('click', "a.exclude_cat", function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var catID = $(this).attr('data-cat-id');
$('#cat' + catID).attr('checked', false);
$(this).closest('li').remove();
GetSearchData(keyword, page_number);
});
function GetSuggestion(keyword) {
var formData = {
'action': 'affordance_search_data',
'keyword': keyword
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.search-suggestion').html(data);
}, 1000);
}
});
}
function GetSearchData(keyword, page_number) {
if (page_number == '') {
page_number = 1;
}
var blogWrapper = $('.blogWrapper');
var categories = [];
blogWrapper.find('input.category_check:checked').each(function () {
categories.push($(this).attr('value'));
});
var formData = {
'action': 'affordance_search_page_data',
'page_number': page_number,
'keyword': keyword,
'categories': categories,
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.site-main').html(data);
}, 1000);
}
});
}
});
Here I'm using ajax to achieve this functionality.
I am having a trouble with my website's pop-up widget. The problem is the pop-up appears when you enter or refresh the website but I can not close it. I click on the "X" button but nothing happens. The code:
<?php
/*
Plugin Name: WP Welcome Message
Plugin URI: http://www.a1netsolutions.com/Products/WP-Welcome-Message
Description: <strong>WP Welcome Message</strong> is a wordpress plugin, which help your to make any announcement, special events, special offer, signup message or such kind of message, displayed upon your website's visitors when the page is load through a popup box.
Version: 3.0
Author: Ahsanul Kabir
Author URI: http://www.ahsanulkabir.com/
License: GPL2
License URI: license.txt
*/
$wpwm_conf = array(
'VERSION' => get_bloginfo('version'),
'VEWPATH' => plugins_url('lib/', __FILE__),
);
function wpwm_admin_styles()
{
global $wpwm_conf;
wp_enqueue_style('wpwm_admin_styles',($wpwm_conf["VEWPATH"].'css/admin.css'));
if( $wpwm_conf["VERSION"] > 3.7 )
{
wp_enqueue_style('wpwm_icon_styles',($wpwm_conf["VEWPATH"].'css/icon.css'));
}
}
add_action('admin_print_styles', 'wpwm_admin_styles');
function wpwm_scripts_styles()
{
global $wpwm_conf;
$wpwmBoxSetly = get_option('wpwm_boxsetly');
if(!$wpwmBoxSetly){$wpwmBoxSetly=="fadeOut";}
wp_enqueue_script('wpwm_site_scripts',($wpwm_conf["VEWPATH"].'js/site_'.$wpwmBoxSetly.'.js'),array('jquery'),'',true);
wp_enqueue_style('wpwm_site_style',($wpwm_conf["VEWPATH"].'css/site.css'));
}
add_action('wp_enqueue_scripts', 'wpwm_scripts_styles');
function wpwm_defaults()
{
$wpwm_default = plugin_dir_path( __FILE__ ).'lib/default.php';
if(is_file($wpwm_default))
{
require $wpwm_default;
foreach($default as $k => $v)
{
$vold = get_option($k);
if(!$vold)
{
update_option($k, $v);
}
}
if(!is_multisite())
{
unlink($wpwm_default);
}
}
}
function wpwm_activate()
{
$wpwm_postsid = get_option( 'wpwm_postsid' );
if(!$wpwm_postsid)
{
$inputContent = 'Welcome to '.get_bloginfo('name').', '. get_bloginfo('description');
$new_post_id = wpwm_printCreatePost($inputContent);
update_option( 'wpwm_postsid', $new_post_id );
}
wpwm_defaults();
}
function wpwm_redirect()
{
$wpwm_fv = get_option('wpwm_fv');
if($wpwm_fv != 'fv')
{
echo 'Please setup your <strong>WP Welcome Message 2.0</strong> plugin. <input type="submit" value="Setup" class="button" />';
}
}
add_action( 'admin_footer', 'wpwm_redirect' );
function wpwm_admin_menu()
{
global $wpwm_conf;
if( $wpwm_conf["VERSION"] < 3.8 )
{
add_menu_page('WP Welcome Message', 'Welcome Msg', 'manage_options', 'wpwm_admin_page', 'wpwm_admin_function', (plugins_url('lib/img/icon.png', __FILE__)));
}
else
{
add_menu_page('WP Welcome Message', 'Welcome Msg', 'manage_options', 'wpwm_admin_page', 'wpwm_admin_function');
}
}
add_action('admin_menu', 'wpwm_admin_menu');
function wpwm_select( $iget, $iset, $itxt )
{
if( $iget == $iset )
{
echo '<option value="'.$iset.'" selected="selected">'.$itxt.'</option>';
}
else
{
echo '<option value="'.$iset.'">'.$itxt.'</option>';
}
}
function wpwm_update($key, $value)
{
if(isset($value) && !empty($value))
{
update_option($key, $value);
}
}
function wpwm_admin_function()
{
$wpwm_fv = get_option('wpwm_fv');
if($wpwm_fv != 'fv')
{
update_option('wpwm_fv', 'fv');
}
wpwm_update('wpwm_loc', $_POST["wpwm_loc"]);
wpwm_update('wpwm_log', $_POST["wpwm_log"]);
wpwm_update('wpwm_boxsetly', $_POST["wpwm_boxsetly"]);
wpwm_update('wpwm_bgstyle', $_POST["wpwm_bgstyle"]);
wpwm_update('wpwmTemplate', $_POST["wpwmTemplate"]);
wpwm_update('wpwm_onlyFirstVisit', $_POST["wpwm_onlyFirstVisit"]);
wpwm_update('wpwm_ststs', $_POST["wpwm_ststs"]);
$wpwmPID = get_option('wpwm_postsid');
wpwm_updatePost($_POST["wpwmeditor"], $wpwmPID);
if( isset($_POST["wpwmeditor"]) || isset($_POST["wpwmTemplate"]) )
{
echo '<div id="message" class="updated wpwm_updated"><p>Your data has been successfully saved.</p></div>';
}
global $wpwm_conf;
echo '<div id="wpwm_container">
<div id="wpwm_main">
<img src="',$wpwm_conf["VEWPATH"],'/img/uvg.png" id="wpwm_uvg" />
<h1 id="wpwm_page_title">WP Welcome Message</h1>';
?>
<div class="wpwm_box">
<div class="wpwm_box_title">Your Welcome Message
<form method="post" action="" id="wpwm_off_on"><input type="hidden" name="wpwm_ststs" value="<?php
$wpwm_ststs = get_option('wpwm_ststs');
if($wpwm_ststs == 'on')
{
echo 'off';
}
else
{
echo 'on';
}
?>" /><input type="image" src="<?php echo $wpwm_conf["VEWPATH"]; ?>/img/<?php
$wpwm_ststs = get_option('wpwm_ststs');
if($wpwm_ststs == 'on')
{
echo 'one-check_yes';
}
else
{
echo 'one-check_no';
}
?>.png" /></form>
</div>
<div class="wpwm_box_con">
<form method="post" action="" id="wpwm_content_form">
<?php
$wpwm_ststs = get_option('wpwm_ststs');
if($wpwm_ststs == 'off')
{
echo '<div id="wpwm_content_disable"></div>';
}
$wpwmPID = get_option('wpwm_postsid');
$wpwmContent = get_post($wpwmPID);
$wpwmContent = $wpwmContent->post_content;
$wpwmContent = apply_filters('the_content', $wpwmContent);
$wpwmContent = str_replace(']]>', ']]>', $wpwmContent);
if( $wpwm_conf["VERSION"] < 3.3 )
{
echo '<textarea name="wpwmeditor" style="width:100%; height:300px;"></textarea>';
}
else
{
wp_editor( $wpwmContent, 'wpwmeditor', array('textarea_rows' => 20, 'textarea_name' => 'wpwmeditor') );
}
?>
<input type="submit" value="save changes" />
</form>
</div>
</div>
<div class="wpwm_box">
<div class="wpwm_box_title">Settings</div>
<div class="wpwm_box_con">
<form method="post" action="">
<div class="row">
<label>On Which Page/Pages to Display : </label>
<select name="wpwm_loc">
<?php
$wpwmLoc = get_option( 'wpwm_loc' );
wpwm_select( $wpwmLoc, 'home', 'Home Page Only' );
wpwm_select( $wpwmLoc, 'all', 'All Pages' );
?>
</select>
</div>
<div class="row">
<label>Logged-in / Not Logged-in user : </label>
<select name="wpwm_log">
<?php
$wpwm_log = get_option( 'wpwm_log' );
wpwm_select( $wpwm_log, 'log', 'Logged-in Users Only' );
wpwm_select( $wpwm_log, 'nlog', 'Not Logged-in Users Only' );
wpwm_select( $wpwm_log, 'all', 'For All' );
?>
</select>
</div>
<div class="row">
<label>Message Box Animation Style : </label>
<select name="wpwm_boxsetly">
<?php
$wpwmBoxSetly = get_option( 'wpwm_boxsetly' );
wpwm_select( $wpwmBoxSetly, 'fadeOut', 'Fade Out' );
wpwm_select( $wpwmBoxSetly, 'slideUp', 'Slide Up' );
?>
</select>
</div>
<div class="row">
<label>Template : </label>
<select name="wpwmTemplate">
<?php
$wpwmTemplate = get_option( 'wpwmTemplate' );
wpwm_select( $wpwmTemplate, 'black-color', 'Dark Color Only' );
wpwm_select( $wpwmTemplate, 'black-white-color', 'White Color Only' );
wpwm_select( $wpwmTemplate, 'white-color', 'Full White Color Only' );
wpwm_select( $wpwmTemplate, 'black-striped', 'Dark Stripes' );
wpwm_select( $wpwmTemplate, 'black-white-striped', 'White Stripes' );
wpwm_select( $wpwmTemplate, 'white-striped', 'Full White Stripes' );
wpwm_select( $wpwmTemplate, 'bootstrap', 'Bootstrap Style' );
?>
</select>
</div>
<div class="row">
<label>Only For Fist Time Visit : </label>
<select name="wpwm_onlyFirstVisit">
<?php
$wpwm_onlyFirstVisit = get_option( 'wpwm_onlyFirstVisit' );
wpwm_select( $wpwm_onlyFirstVisit, 'on', 'Enable' );
wpwm_select( $wpwm_onlyFirstVisit, 'off', 'Disable' );
?>
</select>
</div>
<input type="submit" value="save changes" />
</form>
</div>
</div>
<?php
echo '</div>
<div id="wpwm_side">
<div class="wpwm_box">';
echo '<img src="',$wpwm_conf["VEWPATH"],'/img/wp-advert-1.png" />';
echo '</div><div class="wpwm_box">';
echo '<img src="',$wpwm_conf["VEWPATH"],'/img/wp-advert-2.png" />';
echo '</div>
</div>
<div class="wpwm_clr"></div>
</div>';
}
function wpwm_content()
{
$wpwm_ststs = get_option('wpwm_ststs');
if($wpwm_ststs == 'on')
{
$wpwm_onlyFirstVisit = get_option( 'wpwm_onlyFirstVisit' );
if( $wpwm_onlyFirstVisit == "on" )
{
if( (!isset($_SESSION["wpwm_session"])) || ($_SESSION["wpwm_session"] != 'off') )
{
wpwm_popupFirst();
}
}
else
{
wpwm_popupFirst();
}
}
}
function wpwm_popupFirst()
{
$wpwm_loc = get_option( 'wpwm_log' );
if(get_option('wpwm_ststs') == 'on')
{
if( $wpwm_loc == 'log' )
{
if ( is_user_logged_in() )
{
wpwm_popupCheckPage();
}
}
elseif( $wpwm_loc == 'nlog' )
{
if ( !is_user_logged_in() )
{
wpwm_popupCheckPage();
}
}
else
{
wpwm_popupCheckPage();
}
}
}
function wpwm_popupTemp()
{
$wpwmPID = get_option( 'wpwm_postsid' );
$wpwmTemplate = get_option('wpwmTemplate');
$content_post = get_post($wpwmPID);
$wpwmContent = $content_post->post_content;
$wpwmContent = apply_filters('the_content', $wpwmContent);
$wpwmContent = str_replace(']]>', ']]>', $wpwmContent);
$session_id = session_id();
echo '
<div id="wpwm_hideBody" class="'.$wpwmTemplate.'-body">
<div id="wpwm_popBoxOut">
<div class="wpwm-box">
<div id="wpwm_popBox">
<span id="wpwm_popClose">×</span>
'.$wpwmContent.'
<div class="cl_fix"></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery("html, body").css({"overflow": "hidden"});
});
</script>
';
echo '<span>',get_option('wpwm_dev1'),get_option('wpwm_dev2'),get_option('wpwm_dev3'),'</span>';
}
function wpwm_popupCheckPage()
{
if( ( get_option( 'wpwm_loc' ) ) == 'home' )
{
if( is_front_page() )
{
wpwm_popupTemp();
}
}
else
{
wpwm_popupTemp();
}
}
function wpwm_sessionID()
{
if(!isset($_SESSION)){session_start();}
if(isset($_SESSION["wpwm_session"]))
{
$_SESSION["wpwm_session"] = 'off';
}
else
{
$_SESSION["wpwm_session"] = 'on';
}
}
add_action( 'wp_head', 'wpwm_sessionID' );
function wpwm_posts_init()
{
$args = array
(
'public' => false,
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'rewrite' => array( 'slug' => 'wpwmposts' ),
'capability_type' => 'post',
'has_archive' => false,
'supports' => array( 'title', 'editor', 'excerpt' )
);
register_post_type( 'wpwmposts', $args );
}
add_action( 'init', 'wpwm_posts_init' );
function wpwm_getCurrentUser()
{
if (function_exists('wp_get_current_user'))
{
return wp_get_current_user();
}
else if (function_exists('get_currentuserinfo'))
{
global $userdata;
get_currentuserinfo();
return $userdata;
}
else
{
$user_login = $_COOKIE["USER_COOKIE"];
$current_user = $wpdb->get_results("SELECT * FROM `".$wpdb->users."` WHERE `user_login` = '".$user_login."' ;");
return $current_user;
}
}
function wpwm_printCreatePost($inputContent)
{
$newPostAuthor = wpwm_getCurrentUser();
$newPostArg = array
(
'post_author' => $newPostAuthor->ID,
'post_content' => $inputContent,
'post_status' => 'publish',
'post_type' => 'wpwmposts'
);
$new_post_id = wp_insert_post($newPostArg);
return $new_post_id;
}
function wpwm_updatePost($inputContent, $id)
{
$newPostAuthor = wpwm_getCurrentUser();
$newPostArg = array
(
'ID' => $id,
'post_author' => $newPostAuthor->ID,
'post_content' => $inputContent,
'post_status' => 'publish',
'post_type' => 'wpwmposts'
);
$new_post_id = wp_insert_post($newPostArg);
return $new_post_id;
}
add_action('wp_footer', 'wpwm_content', 100);
register_activation_hook(__FILE__, 'wpwm_activate');
?>
Finally, I managed to find where the problem is.
echo '
<div id="wpwm_hideBody" class="'.$wpwmTemplate.'-body">
<div id="wpwm_popBoxOut">
<div class="wpwm-box">
<div id="wpwm_popBox">
<span id="wpwm_popClose">×</span>
'.$wpwmContent.'
<div class="cl_fix"></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery("html, body").css({"overflow": "hidden"});
});
</script>
';
And find out there is no close function going on here:
<span id="wpwm_popClose">×</span>
So changed it with this:
<span id="wpwm_popClose" onclick="document.getElementById('pwm_hideBody').style.display='none'">×</span>
but when I edit this PHP code, WordPress gives me this error:
Parse error: syntax error, unexpected 'pwm_hideBody' (T_STRING), expecting ',' or ';' in /var/www/vhosts/derinuzay.org/httpdocs/wp-content/plugins/wp-welcome-message/wp-welcome-message.php on line 337
Could you please help me out about this error?
Try to add this:
jQuery('#wpwm_popClose').click(function() {
jQuery('#wpwm_hideBody').css('display', 'none');
});
inside the:
jQuery(document).ready(function() {
jQuery("html, body").css({"overflow": "hidden"});
});
What happens if you replace
echo '
<div id="wpwm_hideBody" class="'.$wpwmTemplate.'-body">
<div id="wpwm_popBoxOut">
<div class="wpwm-box">
<div id="wpwm_popBox">
<span id="wpwm_popClose">×</span>
'.$wpwmContent.'
<div class="cl_fix"></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery("html, body").css({"overflow": "hidden"});
});
</script>
';
With:
?>
<div id="wpwm_hideBody" class="<?php echo $wpwmTemplate; ?>-body">
<div id="wpwm_popBoxOut">
<div class="wpwm-box">
<div id="wpwm_popBox">
<span id="wpwm_popClose">×</span>
<?php echo $wpwmContent; ?>
<div class="cl_fix"></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#wpwm_popClose').click(function() {
jQuery('#wpwm_hideBody').css('display', 'none');
});
});
</script>
<?php
Checkbox is checked after value post request send to controller after get data by post request value from model
view (onlineorder/index.php)
<script src="<?php echo base_url('assets/js/ajax.jquery.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/js/bootstrap.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/fullcalendar/moment.min.js'); ?>"></script>
<script src="<?php echo base_url('assets/fullcalendar/jquery.min.js'); ?>"></script>
<?php echo form_open('onlineOrder/index'); ?>
<div class="row">
<div class="col-md-6">
<div class="form-horizontal well">
<fieldset>
<label>Захиалга өгөх тасаг сонгох</label>
<div class="tree-wrap">
<ul>
<?php
$counter = 0;
$getData = $getDataOrgBranch['listBranch'];
foreach ($getData as $value) {
echo '<li><input type="checkbox" value="' . $value['branch_id'] . '" class="event-branch"><span><i class="fa fa-folder-close-alt"></i>' . $value['branch_name'] . '</span></li>';
}
?>
</ul>
<input type="button" value="Get checkboxes" id="getCheckboxesButton">
<div id="debugOutput"></div>
</div>
</fieldset>
</div>
</div>
<div class="col-md-6">
<div class="form-horizontal well">
<fieldset>
<label>Захиалга өгөх үйлчилгээ сонгох</label>
<div class="tree-wrap">
<ul>
<?php
foreach ($getDataOrgService as $selectedObj) {
echo '<li class="collapsed"><input type="checkbox"><span><i class="fa fa-folder-close-alt"></i>' . $selectedObj["title"] . '</span>';
if (array_key_exists("children", $selectedObj)) {
$data = $selectedObj["children"];
echo "<ul>";
foreach ($data as $val) {
echo '<li class="leaf"><input type="checkbox"><span><i class="fa fa-folder-close-alt"></i>' . $val["title"] . '</span></li>';
}
echo "</ul>";
}
echo "</li>";
}
?>
</ul>
</div>
</fieldset>
</div>
</div>
</div>
</form>
<script>
$(document).ready(function () {
$('.event-branch').change(function () {
if ($(this).is(":checked")) {
var checkVal = $(this).val();
$.ajax({
url: "<?php echo base_url('onlineOrder/index'); ?>",
type: "POST",
data: {"branchId": checkVal},
dataType: "json",
success: function (getDataServiceOfBranch) {
alert("8888888888888888" + data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus, errorThrown);
}
});
}
console.log(checkVal);
});
});
</script>
Controller(OnlineOrder.php)
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class OnlineOrder extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('menusModel');
$this->load->model('getFromDataUrlModel');
}
public function index() {
if (isset($_POST['branchId'])){
$id = $this->input->post('branchId');
$data['getDataServiceOfBranch'] = $this->getFromDataUrlModel->getDataServiceOfBranch($id);
}
$head['page'] = 'onlineorder';
$head['menus'] = $this->menusModel->getAllData();
$head['getDataOrgAndEmployee'] = $this->getFromDataUrlModel->getDataOrgAndEmployee();
$data['getDataOrgService'] = $this->getFromDataUrlModel->getDataOrgService();
$data['getDataOrgBranch'] = $this->getFromDataUrlModel->getDataOrgBranch();
$this->load->view('header', $head);
$this->load->view('onlineorder/Index',$data);
$this->load->view('footer');
}
}
<p>Model(GetFromDataUrlModel.php)</p>
<!-- begin snippet: js hide: false -->
<?php
class GetFromDataUrlModel extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->helper('url');
}
public function getDataServiceOfBranch($id='')
{
$url = 'http://192.168.1.22:9390/HomePage/TreatmentByBranch?branch_id='. $id;
$orgBranchService = json_decode(file_get_contents($url), true);
return $orgBranchService;
$file_headers = #get_headers($url);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
echo show_404();
}
else {
}
}
}
I couldn't really understand what's your issue but I think your code needs these modifications to work properly, update your Controller and Model with the following and see if that fixes it.
Controller index:
public function index() {
$id = $this->input->post('branchId');
if ($id) {
$data['getDataServiceOfBranch'] = $this->getFromDataUrlModel->getDataServiceOfBranch($id);
if (!$data['getDataServiceOfBranch'])
{
echo show_404();
}
}
$head['page'] = 'onlineorder';
$head['menus'] = $this->menusModel->getAllData();
$head['getDataOrgAndEmployee'] = $this->getFromDataUrlModel->getDataOrgAndEmployee();
$data['getDataOrgService'] = $this->getFromDataUrlModel->getDataOrgService();
$data['getDataOrgBranch'] = $this->getFromDataUrlModel->getDataOrgBranch();
$this->load->view('header', $head);
$this->load->view('onlineorder/Index', $data);
$this->load->view('footer');
}
Model method:
public function getDataServiceOfBranch($id)
{
$url = 'http://192.168.1.22:9390/HomePage/TreatmentByBranch?branch_id='.$id;
$orgBranchService = json_decode(file_get_contents($url), true);
$file_headers = #get_headers($url);
if ($file_headers[0] == 'HTTP/1.1 404 Not Found') {
return false;
}
else {
return $orgBranchService;
}
}
Hope it helps.