I'm writing a code to add the dynamic fields and save them to the database, but when I save it's not getting saved, below is my code, can anyone please tell what am I doing wrong
This is a plugin code where in I have added the form to dynamically add fields and save it data
This is form code:
<?php
/*
Plugin Name: Link Changer
Description: Changes the button link after certain clicks
Version: 1.0
Text Domain: button-link-changer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
add_action( 'admin_menu', 'link_changer_menu' );
$con = mysqli_connect('localhost','aejaz_wp1','Q.gslkbUNCOT2zZUVSw82','aejaz_wp1');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
else{
echo '';
}
global $jal_db_version;
$jal_db_version = '1.0';
function jal_install() {
global $wpdb;
global $jal_db_version;
$table_name = $wpdb->prefix . 'liveshoutbox';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
links varchar(55) DEFAULT '' NOT NULL,
hitsmade mediumint(9) NOT NULL,
hitstocount mediumint(9) NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( 'jal_db_version', $jal_db_version );
}
function jal_install_data() {
global $wpdb;
$welcome_name = 'Mr. WordPress';
$welcome_text = 'Congratulations, you just completed the installation!';
$table_name = $wpdb->prefix . 'liveshoutbox';
$wpdb->insert(
$table_name,
array(
'time' => current_time( 'mysql' ),
'name' => $welcome_name,
'text' => $welcome_text,
)
);
}
register_activation_hook( __FILE__, 'jal_install' );
register_activation_hook( __FILE__, 'jal_install_data' );
function link_changer_menu(){
$page_title = 'Link Changer';
$menu_title = 'Button Link Changer';
$capability = 'manage_options';
$menu_slug = 'Button-Link-Changer';
$function = 'extra_post_info_page';
$icon_url = 'dashicons-media-code';
$position = 6;
add_menu_page( $page_title,
$menu_title,
$capability,
$menu_slug,
$function,
$icon_url,
$position );
add_action( 'admin_init', 'link_register_settings' );
}
function link_register_settings() {
// Let's create and register the Sections.
// - register_setting( $option_group, $option_name, $sanitize_callback );
register_setting('button-link-changer', 'link_options', 'link_options_sanitize');
}
//to save options as array create input fields
function bp_options_sanitize($input){
$input['link_one'] = sanitize_text_field($input['link_one']);
$input['link_two'] = sanitize_text_field($input['link_two']);
$input['link_hits'] = sanitize_text_field($input['link_hits']);
$input['links'] = sanitize_text_field($input['links']);
return $input;
} // end link_options_sanitize
// Let's create the Main Page
function extra_post_info_page(){
#saving plugin options to database from form ?>
<h1>Button Link Changer</h1>
<form method="post" action="options.php">
<?php settings_fields( 'button-link-changer' ); ?>
<?php //do_settings_sections( 'button-link-changer' ); ?>
<?php $link_options = get_option('link_options') ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Link one</th>
<td>
<input type="text" name="link_options[link_one]" value="<?php echo esc_attr($link_options['link_one']); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Link two</th>
<td>
<input type="text" name="link_options[link_two]" value="<?php echo esc_attr($link_options['link_two']) ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Link Hits</th>
<td>
<input type="text" name="link_options[link_hits]" value="<?php echo esc_attr($link_options['link_hits']) ?>" />
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
<form name="add_me" id="add_me">
<table id="dynamic">
<input type="text" name="name[]" placeholder="Enter Your Name" />
<button type="button" name="add" id="add_input">Add</button>
</table>
<input type="button" name="submit" id="submit" value="Submit" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var i = 1;
$('#add_input').click(function() {
i++;
$('#dynamic').append('<tr id="row' + i + '" ><td><input type="text" name="name[]" placeholder="Enter Your Name"/></td><td><button type="button" name="remove" id="' + i + '" class="btn_remove">Remove</button></td></tr>');
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$('#submit').click(function() {
$.ajax({
url: "insert.php",
method: "POST",
data: $('#add_me').serialize(),
success: function(data) {
alert(data);
$('#add_me')[0].reset();
}
});
});
});
</script>
<?php
//fetching data from database
global $wpdb;
$results = $wpdb->get_results( "SELECT option_value FROM $wpdb->options WHERE option_name='link_options'");
if(!empty($results)) {
// output data of each row
$arrayvalues=$results[0]->option_value;
$unserialized_categoriesx = unserialize($arrayvalues);
echo $unserialized_categoriesx['link_one'];
$varlinkone = $unserialized_categoriesx['link_one'];
echo "</br>";
echo $unserialized_categoriesx['link_two'];
$varlinktwo = $unserialized_categoriesx['link_two'];
$unserialized_categoriesx['link_hits'];
$varlinkhits =$unserialized_categoriesx['link_hits'];
}
$hits = 0;
//counting and comparing hits
if ($hits[0]<= $varlinkhits)
{
$buttonlink="$varlinkone";
}
else
{
$buttonlink="$varlinktwo";
}
echo $hits[0];
?>
<a href="<?php echo $_SESSION["button_url"] ?>" >Join Whatsapp Group</a>;
<?php
$_SESSION["button_url"] = $buttonlink;
?>
<?php
}
function link_button_function() {?>
Join Whatsapp Group;
<?php }
add_shortcode('button_link', 'link_button_function');
This is insert.php
<?php
$conn = mysqli_connect("localhost", "root", "", "aejaz_wp1");
$number = count($_POST["name"]);
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO wp_liveshoutbox(links) VALUES('".mysqli_real_escape_string($conn, $_POST["name"][$i])."')";
mysqli_query($conn, $sql);
}
}
echo "Data Inserted Successfully";
}
else
{
echo "Enter Your Name";
}
?>
Related
Actually my data is getting stored in backend but I'm not able to display it in frontend , also i want to add multiple images in post type wordpress plugin
You can follow the code:
//Add meta box in the post or page
add_action( 'add_meta_boxes', 'custom_postpage_meta_box' );
function custom_postpage_meta_box(){
$post_types = array('post');
foreach($post_types as $pt){
add_meta_box('custom_postpage_meta_box',__( 'More Featured Images', 'textdomain'),'custom_postpage_meta_box_func',$pt,'side','low');
}
}
//Load the field in meta screen
function custom_postpage_meta_box_func($post){
$meta_keys = array('second_featured_image');
foreach($meta_keys as $meta_key){
$image_meta_val=get_post_meta( $post->ID, $meta_key, true);
?>
<div class="custom_postpage_wrapper" id="<?php echo $meta_key; ?>_wrapper" style="margin-bottom:20px;">
<img onclick="custom_postpage_add_image('<?php echo $meta_key; ?>');" src="<?php%20echo%20(%24image_meta_val!=''?wp_get_attachment_image_src(%20%24image_meta_val)%5B0%5D:'');%20?>" style="width:100%;cursor:pointer;display: <?php echo ($image_meta_val!=''?'block':'none'); ?>" alt="">
<a class="addimage" style="cursor:pointer;" onclick="custom_postpage_add_image('<?php echo $meta_key; ?>');"><?php _e('Set featured image','textdomain'); ?></a><br>
<a class="removeimage" style="cursor:pointer;display: <?php echo ($image_meta_val!=''?'block':'none'); ?>" onclick="custom_postpage_remove_image('<?php echo $meta_key; ?>');"><?php _e('Remove featured image','textdomain'); ?></a>
<input type="hidden" name="<?php echo $meta_key; ?>" id="<?php echo $meta_key; ?>" value="<?php echo $image_meta_val; ?>">
</div>
<?php } ?> <script>function custom_postpage_add_image(key){
var $wrapper = jQuery('#'+key+'_wrapper');
custom_postimage_uploader = wp.media.frames.file_frame = wp.media({
title: '<?php _e('select image','textdomain'); ?>',
button: {
text: '<?php _e('select image','textdomain'); ?>'
},
multiple: false
});
custom_postpage_uploader.on('select', function() {
var attachment = custom_postpage_uploader.state().get('selection').first().toJSON();
var img_url = attachment['url'];
var img_id = attachment['id'];
$wrapper.find('input#'+key).val(img_id);
$wrapper.find('img').attr('src',img_url);
$wrapper.find('img').show();
$wrapper.find('a.removeimage').show();
});
custom_postpage_uploader.on('open', function(){
var selection = custom_postpage_uploader.state().get('selection');
var selected = $wrapper.find('input#'+key).val();
if(selected){
selection.add(wp.media.attachment(selected));
}
});
custom_postpage_uploader.open();
return false;
}
function custom_postpage_remove_image(key){
var $wrapper = jQuery('#'+key+'_wrapper');
$wrapper.find('input#'+key).val('');
$wrapper.find('img').hide();
$wrapper.find('a.removeimage').hide();
return false;
}</script> <?php wp_nonce_field( 'custom_postpage_meta_box', 'custom_postpage_meta_box_nonce' );
?>
}
//Save the meta box
add_action( 'save_post', 'custom_postimage_meta_box_save' );
function custom_postimage_meta_box_save($post_id){
if ( ! current_user_can( 'edit_posts', $post_id ) ){ return 'You have no permission to edit this post types'; }
if (isset( $_POST['custom_postimage_meta_box_nonce'] ) && wp_verify_nonce($_POST['custom_postimage_meta_box_nonce'],'custom_postimage_meta_box' )){
$meta_keys = array('second_featured_image');
foreach($meta_keys as $meta_key){
if(isset($_POST[$meta_key]) && intval($_POST[$meta_key])!=''){
update_post_meta( $post_id, $meta_key, intval($_POST[$meta_key]));
}else{
update_post_meta( $post_id, $meta_key, '');
}
}
}
}
For more details please read the article https://yourblogcoach.com/upload-multiple-featured-images-in-a-post-or-page/
Thank you
I want a user to be able to search for a job based on typing in multiple searchbar components,but in my code it can search based on one searchbar. For this I am using two variables search and search2, it can work only on search variable.
html:
<form action="search.php" method="GET">
<input type="text" id="" class="form-control searchBar" placeholder="Designation">
<input type="text" id="" class="form-control searchBar" placeholder="City" />
<button id="searchBtn" type="button" class="btn btn-info btn-flat">Go!</button>
</form>
javascript:
<script type="text/javascript">
$("#searchBtn").on("click", function(e) {
e.preventDefault();
var searchResult = $(".searchBar ").val();
var filter = "searchBar";
if(searchResult != "" ) {
$("#pagination").twbsPagination('destroy');
Search(searchResult, filter);
} else {
$("#pagination").twbsPagination('destroy');
Pagination();
}
});
</script>
<script type="text/javascript">
function Search(val, filter) {
$("#pagination").twbsPagination({
totalPages: <?php echo $total_pages; ?>,
visible: 5,
onPageClick: function (e, page) {
e.preventDefault();
val = encodeURIComponent(val);
$("#target-content").html("loading....");
//$("#target-content").load("search.php?page="+page+"&search="+val+"&filter="+filter);
$("#target-content").load("search.php?page="+page+"&search="+val+"&search2="+val+"&filter="+filter);
}
});
}
</script>
my search.php page:
<?php
session_start();
require_once("db.php");
$limit = 4;
if(isset($_GET["page"]))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$start_from = ($page-1) * $limit;
if(isset($_GET['filter']) && $_GET['filter']=='searchBar')
{
$search = $_GET['search'];
$search2 = $_GET['search2'];
$sql = "SELECT * FROM job_post INNER JOIN company ON job_post.id_company=company.id_company WHERE jobtitle LIKE '%$search%' OR city LIKE '%$search2%' LIMIT $start_from, $limit";
}
?>
i have two input field one for jobtitle and one for city,and based on this i want related output, eg: jobtile='software devloper' and city= 'delhi',my database show only result of software devloper on city delhi.
search.php:
if(isset($_GET['filter']) && $_GET['filter']=='searchBar')
{
$search = $_GET['search'];
$search2 = $_GET['search2'];
$sql = "SELECT * FROM job_post INNER JOIN company ON job_post.id_company=company.id_company WHERE jobtitle LIKE '%$search%' OR city LIKE '%$search2%' LIMIT $start_from, $limit";
}
else if(isset($_GET['filter']) && $_GET['filter']=='experience')
{
$sql = "SELECT * FROM job_post WHERE experience >='$_GET[search]' LIMIT $start_from, $limit";
}
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$sql1 = "SELECT * FROM company WHERE id_company='$row[id_company]'";
$result1 = $conn->query($sql1);
if($result1->num_rows > 0)
{
while($row1 = $result1->fetch_assoc())
{
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row['jobtitle']; ?> <span class="attachment-heading pull-right">$<?php echo $row['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> |\ <?php echo $row1['city']; ?> | Experience <?php echo $row['experience']; ?> Years</strong></div>
</div>
</div>
</div>
<?php
}
}
}
}
}
$conn->close();
?>
I want when I add a product to the cart and reload the same page, but the problem did not this product.
The controller
public function detail()
{
$data=array('title' =>'Ecommerce Online | Detail Product',
'username' => $this->session->userdata('id'),
'categories' => $this->categories_model->get_categories(),
'details' => $this->categories_model->get_details($this->uri->segment(3)),
'isi' =>'member/detail');
$this->load->view('template_home/wrapper',$data);
}
function addtocart()
{
if($this->cart_model->validate_add_cart_item() == TRUE){
if($this->input->post('ajax') != '1'){
redirect('member/detail/'); // this problem
}else{
echo 'true';
}
}
}
I add my models
function validate_add_cart_item()
{
$id = $this->input->post('product_id');
$cty = $this->input->post('quantity');
$this->db->where('productID', $id);
$query = $this->db->get('product', 1);
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $cty,
'price' => $row->price,
'name' => $row->productName
);
$this->cart->insert($data);
return TRUE;
}
}else{
return FALSE;
}
}
I add my view
<?php foreach ($details as $s) { ?>
<div class="col-md-5">
<div class="box text-center">
<img src="<?php echo base_url('upload/'.$s->photo); ?>" width="150px" height="150px">
<br><?php echo $s->productName; ?>
<br><strong>Rp. <?php echo $s->price; ?></strong>
<br>
<?php echo form_open('member/add'); ?>
<fieldset>
<label>Quantity</label>
<?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
<?php echo form_hidden('product_id', $s->productID); ?>
<?php echo form_submit('add', 'Add'); ?>
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
<?php } ?>
Jquery script
<script type="text/javascript">
$(document).ready(function() {
/*place jQuery actions here*/
var link = "<?php echo site_url('member/detail')?>/"; // Url to your application (including index.php/)
$(".detail-product").submit(function(){
var id = $(this).find('input[name=product_id]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "member/add", { product_id: id, quantity: qty, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "member/detail", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
});
return false; // Stop the browser of loading the page defined
});
});
</script>
This is problem url: http://localhost/scientificwriting/member/detail/ and productid can not be invoked. Do I need to replace the IF statement on my controller and my jquery?
Please help me thanks
i did some coding to group the product attributes on frontend and show their groups names above theme like this:
attgroup 1
attribute 1
attribute 2
...
attgroup 2
attribute 3
attribute 4
...
I added /app/code/local/Mage/Catalog/Block/Product/View/Attributesgroups.php with the following code:
<?php
class Mage_Catalog_Block_Product_View_Attributesgroups extends Mage_Core_Block_Template
{
protected $_product = null;
function getProduct()
{
if (!$this->_product) {
$this->_product = Mage::registry('product');
}
return $this->_product;
}
public function getAdditionalData(array $excludeAttr = array())
{
$data = array();
$product = $this->getProduct();
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
$value = $attribute->getFrontend()->getValue($product);
// TODO this is temporary skipping eco taxes
if (is_string($value)) {
if (strlen($value) && $product->hasData($attribute->getAttributeCode())) {
if ($attribute->getFrontendInput() == 'price') {
$value = Mage::app()->getStore()->convertPrice($value,true);
} elseif (!$attribute->getIsHtmlAllowedOnFront()) {
$value = $this->htmlEscape($value);
}
$group = 0;
if( $tmp = $attribute->getData('attribute_group_id') ) {
$group = $tmp;
}
$data[$group]['items'][ $attribute->getAttributeCode()] = array(
'label' => $attribute->getFrontend()->getLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
$data[$group]['attrid'] = $attribute->getId();
}
}
}
}
// Noch Titel lesen
foreach( $data AS $groupId => &$group ) {
$groupModel = Mage::getModel('eav/entity_attribute_group')->load( $groupId );
$group['title'] = $groupModel->getAttributeGroupName();
}
return $data;
}
}
Then, I created the /app/design/frontend/MY_TEMPLATE/default/template/catalog/product/view/attributesgroups.phtml file with the following content:
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct()
?>
<?php if($_additionalgroup = $this->getAdditionalData()): ?>
<div class="box-collateral box-additional">
<h2><?php echo $this->__('Additional Information') ?></h2>
<?php $i=0; foreach ($_additionalgroup as $_additional): $i++; ?>
<h3><?php echo $this->__( $_additional['title'] )?></h3>
<table class="data-table" id="product-attribute-specs-table-<?php echo $i?>">
<col width="25%" />
<col />
<tbody>
<?php foreach ($_additional['items'] as $_data): ?>
<tr>
<th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table-<?php echo $i?>')</script>
<?php endforeach; ?>
</div>
<?php endif;?>
Last step was to modify /app/design/frontend/default/YOUR_TEMPLATE/layout/catalog.xml in line 223, and replaced
<block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
with
<block type="catalog/product_view_attributesgroups" name="product.attributes" as="additional" template="catalog/product/view/attributesgroups.phtml">
i did this but nothing is changed on product attribute tap on frontend product page.
im using magento 1.9.1 ce and custom template
First try to simple way
foreach($product->getAttributes() as $att){
$group_id = $att->getData('attribute_group_id');
$group = Mage::getModel('eav/entity_attribute_group')->load($group_id); var_dump($group);
}
or please try to below code....
Get attribute set ID programmatically..
$sDefaultAttributeSetId = Mage::getSingleton('eav/config')
->getEntityType(Mage_Catalog_Model_Product::ENTITY)
->getDefaultAttributeSetId();
Get group name programmatically..
$attributeSetId = 10;
$groups = Mage::getModel('eav/entity_attribute_group')
->getResourceCollection()
->setAttributeSetFilter($attributeSetId)
->setSortOrder()
->load();
$attributeCodes = array();
foreach ($groups as $group) {
echo $groupName = $group->getAttributeGroupName();
$groupId = $group->getAttributeGroupId();
}
I've found several articles on this but nothing that fits my circumstance. I have these radio buttons and drop down menu from which I need to post a selection using ajax in json dataType. Simply put, what do I put in the "WHAT GOES HERE" spot?
Thanks in advance!
<script>
$(function() {
$('#driver').click(function(){
$.ajax({
url:'_resources/_helpers/grader-test.php',
type: "POST",
data:{ /*WHAT GOES HERE?????*/ },//<---WHAT GOES HERE??
dataType: "json",
success: function(result){
$('#jsonstuff').html(result);
console.log(result[0].AVG);
$('#grade').html(result[0].AVG);
}
});
});
});
</script>
<td>
Select:
<select id="extension">
<option value="empty"></option>
<? foreach ($sql as $row){
echo '<option value = "' . $row['extension'] . '">' . $row["tech_fname"] . ' ' . $row["tech_lname"] . ' - ' . $row['extension'] . '</option>';
?>
</select>
</td>
<td>
As Reviewer<input type="radio" class="as_type" name="as_type" value="reviewer"/><br />
As Reviewed<input type="radio" class="as_type" name="as_type" value="reviewed"/>
<input type="button" id="driver" value="Submit" />
</td>
<td id="grade"></td>
And here is grader-test.php:
$ext = $_POST['extension'];// 2752;//
$type = $_POST['as_type'];// "reviewer";//
switch($type){
case "reviewer":
$dbh = new PDO('mysql:host=;dbname=', '', '');
$sql = "SELECT AVG(grade_average) AS AVG from call_reviews WHERE reviewer_ext = :ext";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ext',$ext);
$stmt->execute();
$average = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($average);
break;
case "reviewed":
$dbh = new PDO('mysql:host=;dbname=', '', '');
$sql = "SELECT AVG(grade_average) AS AVG from call_reviews WHERE reviewed_ext = :ext";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ext',$ext);
$stmt->execute();
$average = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($average);
break;
default:
echo "select something";
}