Import CSV code with insert post and post meta tables? - wordpress

I have created one plugin import.php
<?php
function fileupload_process() {
ini_set('memory_limit', '64M');
set_time_limit(0);
$uploadfiles = $_FILES['uploadfiles'];
//echo 'ddd';
// exit;
if (is_array($uploadfiles)) {
//echo 'ram';
//print_r($uploadfiles);
echo $uploadfiles['name'];
// foreach ($uploadfiles as $key => $value) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploaded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
if (($handle = fopen($filetmp, "r")) !== FALSE) {
$flag = true;
$songs = explode("\n",file_get_contents($filetmp));
$count = count( $songs );
unset($songs);
echo "Total item count: " . $count . "<BR />";
// typical entry: If You Have To Ask,Red Hot Chili Peppers,0:03:37, Rock & Alternative,1991,on
// using a generous 1000 length - will lowering this actually impact performance in terms of memory allocation?
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// Skip the first entry in the csv containing colmn info
if($flag) {
$flag = false;
echo "<BR />";
$count--;
continue;
}
// insert the current post and relevant info into the database
$currently_processed = process_custom_post($data);
$count--;
}
echo "Done!";
fclose($handle);
}
unlink($filetmp); // delete the temp csv file
}
}
}
} // END: file_upload_process()
function process_custom_post($song) {
global $wpdb;
// Prepare and insert the custom post
$track = (array_key_exists(0, $song) && $song[0] != "" ? $song[0] : 'N/A');
$custom_post = array();
$custom_post['post_type'] = 'songs';
$custom_post['post_status'] = 'publish';
$custom_post['post_title'] = $track;
$post_id = wp_insert_post( $custom_post );
// Prepare and insert the custom post meta
$meta_keys = array();
$meta_keys['artist_name'] = (array_key_exists(1, $song) && $song[1] != "" ? $song[1] : 'N/A');
$meta_keys['song_length'] = (array_key_exists(2, $song) && $song[2] != "" ? $song[2] : 'N/A');
$meta_keys['song_genre'] = (array_key_exists(3, $song) && $song[3] != "" ? $song[3] : 'N/A');
$meta_keys['song_year'] = (array_key_exists(4, $song) && $song[4] != "" ? $song[4] : 'N/A');
$meta_keys['song_month'] = (array_key_exists(5, $song) && $song[5] != "" ? $song[5] : 'N/A');
$meta_keys['sample_playlist'] = (array_key_exists(6, $song) && $song[6] != "" ? $song[6] : '');
$custom_fields = array();
$place_holders = array();
$query_string = "INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value) VALUES ";
foreach($meta_keys as $key => $value) {
array_push($custom_fields, $post_id, $key, $value);
$place_holders[] = "('%d', '%s', '%s')";
}
$query_string .= implode(', ', $place_holders);
$wpdb->query( $wpdb->prepare("$query_string ", $custom_fields));
return true;
}// END: process_custom_post()
function import_page () {
//HTML for the import page + the file upload form
if (isset($_POST['uploadfile'])) {
fileupload_process();
}
}
In main.php I do customize the code:
<?php
/*
Plugin Name: csv ram
Plugin URI: http://www.newdreamdatasystems.com
Description: csv ram
Version: 2.0
Author: RAM KUMAR
Author URI: http://www.newdreamdatasystems.com
*/
define('SAVEQUERIES', true);
define( 'MY_PLUGIN_ROOT' , dirname(__FILE__) );
include_once( MY_PLUGIN_ROOT . '/import.php');
$ram = import_page();
add_action('admin_menu', 'register_my_custom_submenu_page');
function register_my_custom_submenu_page() {
add_submenu_page( 'tools.php', 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-custom-submenu-page', 'my_custom_submenu_page_callback' );
}
function my_custom_submenu_page_callback() {
$html= <<<RAM
<form action="{$ram}" method="post" enctype="multipart/form-data" name="form1" id="form1" onSubmit="">
<label>upload file<input type="file" name="uploadfiles" id="uploadfiles" /></label>
<label><input type="submit" name="uploadfile" id="uploadfile" value="Submit" /></label>
</form>
RAM;
echo $html;
}
But I have one error:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\wordpress\wp-content\plugins\try\import.php on line 13..?
How to fix this?

Three main problems:
The function import_page() should be run inside the callback:
function my_custom_submenu_page_callback() {
import_page();
/* etc */
}
Action <form action=""> should be empty, so it goes back to the same plugin page, /wp-admin/tools.php?page=my-custom-submenu-page.
The file field should allow for multiple uploads so this will work foreach ($uploadfiles as $key => $value) and remove the error you're seeing.
<input type="file" name="uploadfiles[]" id="uploadfiles" multiple />
Thinking better, you may not need the multiple attribute, but then adjust the rest of the logic.
But after this adjustments, there are still a bunch of notices and warnings, like Array to string conversion, Undefined index: name and fopen(): Filename cannot be empty.
All this is easily fixed with careful debugging, this is how I found the 3 problems above:
Add printf( '<pre>%s</pre>', print_r( $INSPECT_VAR, true ) ); to go inspecting the problematic variables.

Related

How to generate zip file after woocommerce_email_attachments Woocommerce hook

What i want to do is create pdf (pdf's) on woocommerce_email_attachments hook, then create zip file with these pdf's, and then on thankyou page locate button to download this zip. To generate zip I used woocommerce_before_thankyou hook but this is too late. So I tried
woocommerce_order_status_on-hold,
woocommerce_order_status_processing
But these hooks seems not firing, maybe they work on transitions in admin order page. Also I tried woocommerce_payment_complete with test paypal account - not created zip also.
Or maybe these hooks fire before woocommerce_email_attachments and there is no pdf yet to create zip? So can you suggest hook after sending wc email but before woocommerce_before_thankyou ?
Code which I use to generate pdf's:
add_filter('woocommerce_email_attachments', 'attach_order_notice', 10, 3);
function attach_order_notice($attachments, $email_id, $order)
{
// check if all variables properly set
if (!is_object($order) || !isset($email_id)) {
return $attachments;
}
// Skip User emails
if (get_class($order) == 'WP_User') {
return $attachments;
}
// do not process low stock notifications, user emails etc!
if (in_array($email_id, array('no_stock', 'low_stock', 'backorder', 'customer_new_account', 'customer_reset_password'))) {
return $attachments;
}
// final check on order object
if (!($order instanceof \WC_Order || is_subclass_of($order, '\WC_Abstract_Order'))) {
return $attachments;
}
// if ($email_id == 'customer_on_hold_order') {
$order_items = $order->get_items(['line_item']);
$date = $order->get_date_created()->date('h-i-s,j-m-y');
foreach ($order_items as $product) {
$html = render_template(locate_template('pdf/certificate/certificate.php'), ['order' => $order, 'order_product' => $product]);
$html = utf8_decode(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$options = new Dompdf\Options([
'tempDir' => get_template_directory() . '/certificate',
'fontDir' => get_template_directory() . '/assets/fonts/',
'chroot' => get_template_directory(),
'defaultFont' => 'Montserrat',
'isRemoteEnabled' => true,
'isHtml5ParserEnabled' => true
]);
$dompdf = new Dompdf\Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$data = $dompdf->output();
$pdf_path = get_template_directory() . "/certificate/product-{$product->get_product_id()}({$date}).pdf";
file_put_contents($pdf_path, $data);
$attachments[] = $pdf_path;
}
// }
return $attachments;
}
Code which I use to create zip:
add_action('woocommerce_before_thankyou', 'custom_make_thank_page');
function custom_make_thank_page($order_id)
{
$order = wc_get_order($order_id);
$order_items = $order->get_items(['line_item']);
$date = $order->get_date_created()->date('h-i-s,j-m-y');
$total_quantity = array_sum(array_map(function ($product) {
return $product->get_quantity();
}, $order_items));
//Zip
$zip = new ZipArchive();
$file = TMP_PATH . '/pdf/zip/certificates-' . $order->get_id() . '.zip';
if ($zip->open($file, ZipArchive::CREATE) === TRUE) {
foreach ($order_items as $item) {
$file_pdf = get_template_directory() . "/certificate/product-{$item->get_product_id()}({$date}).pdf";
if (file_exists($file_pdf)) {
$zip->addFile($file_pdf, "/certificate/product-{$item->get_product_id()}({$date}).pdf");
}
}
$zip->close();
}
?>
<?php if (!$order->has_status('failed')) : ?>
<a href="<?php echo TMP_URL . '/pdf/zip/certificates-' . $order->get_id() . '.zip'; ?>" class="button button-thank-page"><span>Download certificate</span>
</a> // Here downloading not works, works only after reloading page
</div>
<?php endif; ?>
<?php
}

Wordpress backend form returns JSON

I developed a small one-file plugin for a wordpress site. It's just adds an upload form for a file that POSTs to itself and then does some stuff with the file's contents once submitted.
It works fine on the staging environment, but on the live server there is a strange problem. Once I submit the form with the file the server does not bring me back to the same page but instead returns the following JSON:
{"success":false,"message":"Please enter a message."}
I am at loss what could be causing this. Has anybody come across such a problem?
The (simplified plugin):
function show_upload_form() {
if ($_FILES['userfile']) {
echo "<p>file received</p>";
$file = fopen($_FILES['userfile']['tmp_name'], "r");
$data = [];
while (!feof($file)) {
$data[] = fgetcsv($file,null,';');
}
foreach ($data as $line) {
$pid = $line[0];
if (isset($line[1])) {
$price = trim(str_replace(',', '.', $line[1]));
} else {
$price = "";
}
if (isset($line[2])) {
$title = trim(iconv("ISO-8859-1", "UTF-8", $line[2]));
} else {
$title = "";
}
global $wpdb;
$product_ids = $wpdb->get_results($wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s'", $pid));
foreach ($product_ids as $product_id) {
$elem = $product_id->post_id;
if ($price != "") {
update_post_meta($elem, '_price', $price);
update_post_meta($elem, '_sale_price', $price);
update_post_meta($elem, '_regular_price', $price);
}
if ($title != "") {
wp_update_post(array(
'ID' => $elem,
'post_title' => $title,
));
}
}
echo "<p>Produkt #".$pid;
if ($price != "") {
echo " - new price: ".$price."€";
}
if ($title != "") {
echo "- new title: ".$title;
}
}
} else {
echo "<form method=\"post\" enctype=\"multipart/form-data\">";
echo "<label for=\"file\">Select a file:</label>";
echo "<input type=\"file\" name=\"userfile\" id=\"file\">";
echo "<br /><br />";
echo "<button>Upload File</button>";
echo "<form>";
}
}
I appreciate any input.
Try something like this
<form action="<?=admin_url( 'admin-post.php' ) ?>" method="POST">
<input type="hidden" name="action" value="my_custom_plugin_action"/>
<input type="submit" value="SEND"/>
</form>
add_action( 'admin_post_nopriv_my_custom_plugin_action',array( "class_that_owns_that_function", 'show_upload_form' ) );
public function show_upload_form()
{
//Here write your code
}
Problem disappeared after deactivating and individually reactivating all the plugins for the second or third time. Guess this one will remain a mystery ...

How to add a custom attribute?

How to add a custom attribute in the field Contact Form 7 without javascript ?
For example, there is such a field on the page:
<input type="text" name="name" class="form-control" id="name-1" data-attr="custom" data-msg="Текст 1">
Question: is it possible to set these custom attributes (data-attr, data-msg) of fields in the admin panel?
Find the name of your field.
[text* text-21]
If the name of your field name="text-21", like in my example, add this code to functions.php file.
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="text-21"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
Note, it will add those attributes to all forms elements where the name is text-21, if you want prevent it then give your form element some unique name [text* unique-name]
And change the code to
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="unique-name"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
Here is a generic solution that doesn't involve hardcoding the field name and the attributes
add_filter( 'wpcf7_form_tag', function ( $tag ) {
$datas = [];
foreach ( (array)$tag['options'] as $option ) {
if ( strpos( $option, 'data-' ) === 0 ) {
$option = explode( ':', $option, 2 );
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if ( ! empty( $datas ) ) {
$id = uniqid('tmp-wpcf');
$tag['options'][] = "class:$id";
add_filter( 'wpcf7_form_elements', function ($content) use ($id, $datas) {
return str_replace($id, $name, str_replace($id.'"', '"'. wpcf7_format_atts($datas), $content));
});
}
return $tag;
} );
It works on all data attributes so you can use it like this
[text* my-name data-foo:bar data-biz:baz placeholder "Blabla"]
Output: <input type="text" name="my-name" data-foo="bar" data-biz="baz" placeholder="Blabla">
Since wpcf7 doesn't provide a way to hook into options directly the solutions uses a trick and temporary adds a uniquely generated class to the field that is then replaced in a later filter with the added attributes
If you need it to work with more than just data attributes you can whitelist some more attributes by replacing this line
if ( strpos( $option, 'data-' ) === 0 ) {
to something like the following
if ( preg_match( '/^(data-|pattern|my-custom-attribute)/', $option ) ) {
Note: wpcf7_format_atts will not output empty attributes, so make sure you give a value to your attributes
Multiple attributes can be added also. eg
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="your-email-homepage"' );
$content = substr_replace( $content, ' aria-describedby="emailHelp" ', $str_pos, 0 );
$str_pos2 = strpos( $content, 'name="your-fname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="fnameHelp" ', $str_pos2, 0 );
$str_pos3 = strpos( $content, 'name="your-lname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="lnameHelp" ', $str_pos3, 0 );
return $content;
}
Extending on from Tofandel's solution, for the benefit of those who got 99% of the way there, but suffered validation issues - I've resolved that in my case and would like to offer an extended solution that gets as far as Tofandel's (putting the attribute into the form proper) but also successfully validates on submission.
add_filter('wpcf7_form_tag', function($tag) {
$data = [];
foreach ((array)$tag['options'] as $option) {
if (strpos( $option, 'autocomplete') === 0) {
$option = explode(':', $option, 2);
$data[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if(!empty($data)) {
add_filter('wpcf7_form_elements', function ($content) use ($tag, $data) {
$data_attrs = wpcf7_format_atts($data);
$name = $tag['name'];
$content_plus_data_attrs = str_replace("name=\"$name\"", "name=\"$name\" " . $data_attrs, $content);
return $content_plus_data_attrs;
});
}
return $tag;
} );
Rather than changing the tag ID to a random value only to replace it with the "real" value later, we just reference the real value in the first place, replacing the relevant part of the content in the wpcf7_form_elements filter (in my case, autocomplete, but as Tofandel's example shows, this can be extended to any data attribute you'd like).
I propose a solution from the one given by Tofandel without JS (CF7) error and to authorize the use of an attribute without value:
/**
* Add custom attributes on inputs
* Put "data-my-attribute" to use it, with or without value
*
* #param array $tag
*
* #return array
*/
function cf7AddCustomAttributes($tag) {
$datas = [];
foreach ((array) $tag['options'] as $option) {
if (strpos($option, 'data-') === 0 || strpos($option, 'id:') === 0) {
$option = explode(':', $option, 2);
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if (!empty($datas)) {
$id = $tag['name'];
if (array_key_exists('id', $datas)) {
$id = $datas['id'];
} else {
$tag['options'][] = "id:$id";
}
add_filter('wpcf7_form_elements', function ($content) use ($id, $datas) {
$attributesHtml = '';
$idHtml = "id=\"$id\"";
foreach ($datas as $key => $value) {
$attributesHtml .= " $key";
if (is_string($value) && strlen($value) > 0) {
$attributesHtml .= "=\"$value\"";
}
}
return str_replace($idHtml, "$idHtml $attributesHtml ", $content);
});
}
return $tag;
}
add_filter('wpcf7_form_tag', 'cf7AddCustomAttributes');
I use this simple method for setting attribute
[checkbox optName use_label_element "optName"]
<script>
document.querySelector(".optName").setAttribute("onchange","myscript");
</script>

Parse error: syntax error, unexpected end of file in___

My site's theme has been working fine for a few days when suddendly without any coding changes I now am getting this error:
Parse error: syntax error, unexpected end of file in /home/henrysst/public_html/wp-content/themes/bettycommerce/includes/pro_framework/admin.php on line 812
I have made no changes to the theme, and it was working fine before (Apart from Revolution slider not working)
here is that line that is pulling up the error:
}
add_action('upfw_admin_header_links','upfw_default_header_links');
Here is also the link to the site, if its of any help: http://henrysstuff.co.uk/
Thank you in advance for any help you can provide.
FULL CODE:
<?php
/******
** Pro Bones Framework Version
*************************************/
define('UPTHEMES_VER', '1.0.0');
/******
** Theme init hook
*************************************/
function upfw_theme_init(){
do_action('upfw_theme_init');
}
/******
** Admin init hook
*************************************/
function upfw_admin_init(){
do_action('upfw_admin_init');
}
/******
** Initialization adds hooks to
** two places: theme and admin
*************************************/
function upfw_init(){
if( is_admin() ):
add_action('after_setup_theme','upfw_admin_init');
else:
add_action('after_setup_theme','upfw_theme_init');
endif;
}
add_action('after_setup_theme','upfw_init',1);
/******
** Set up theme data
*************************************/
function upfw_generate_theme_data(){
$get_up_theme = get_theme_data(TEMPLATEPATH .'/style.css');
$theme_title = $get_up_theme['Title'];
$theme_shortname = strtolower(preg_replace('/ /', '_', $theme_title));
$theme_version = $get_up_theme['Version'];
$theme_template = $get_up_theme['Template'];
define('UPTHEMES_NAME', $theme_title);
define('TEMPLATENAME', $theme_title);
define('UPTHEMES_SHORT_NAME', $theme_shortname);
define('UPTHEMES_THEME_VER', $theme_version);
if( file_exists(TEMPLATEPATH.'/includes/pro_framework/admin.php') ):
define( 'THEME_PATH' , TEMPLATEPATH );
define( 'THEME_DIR' , get_template_directory_uri() );
elseif( file_exists(STYLESHEETPATH.'/includes/pro_framework/admin.php') ):
define( 'THEME_PATH' , STYLESHEETPATH );
define( 'THEME_DIR' , get_stylesheet_directory_uri() );
endif;
// Detect child theme info
if(STYLESHEETPATH != TEMPLATEPATH):
$get_up_theme = get_theme_data(STYLESHEETPATH .'/style.css');
$theme_title = $get_up_theme['Title'];
$theme_shortname = strtolower(preg_replace('/ /', '_', $theme_title));
$theme_version = $get_up_theme['Version'];
$theme_template = $get_up_theme['Template'];
define('CHILD_NAME', $theme_title);
define('CHILD_SHORT_NAME', $theme_shortname);
define('CHILD_THEME_VER', $theme_version);
define('CHILD_PATH', STYLESHEETPATH);
endif;
}
add_action('upfw_admin_init','upfw_generate_theme_data',1);
add_action('upfw_theme_init','upfw_generate_theme_data',1);
/******
** Upload error msg
*************************************/
function upfw_upload_error(){
$uploads_dir = wp_upload_dir();
$error = $uploads_dir['error'];
echo '<div id="message" class="error"><p>' . $error . '</p></div>';
return false;
}
/******
** Upload folder permissions
** error msg
*************************************/
function upfw_permissions_error(){
echo '<div id="message" class="error"><p>' . __('It looks like your uploads folder does not have proper permissions. Please set your uploads folder, typically located at [wp-install]/wp-content/uploads/, to 775 or greater.', MOJO_TEXTDOMAIN) . '</p></div>';
return false;
}
/******
** Upload folder created
** success msg
*************************************/
function upfw_uploads_folder_created(){
$uploads_dir = wp_upload_dir();
$base_upload_dir = $uploads_dir['basedir']."/upfw";
echo '<div id="message" class="update-nag">' . __('Pro Affiliate Framework uploads folder created successfully! Your new folder is located at '.$base_upload_dir.'.', MOJO_TEXTDOMAIN) . '</div>';
return false;
}
/******
** Set the uploads directory
** for media from themes
*************************************/
function upfw_set_uploads_dir(){
$uploads_dir = wp_upload_dir();
if( $uploads_dir['error'] )
add_action( 'admin_notices', 'upfw_upload_error', 1, 1 );
else{
$base_upload_dir = $uploads_dir['basedir']."/upfw";
$base_upload_url = $uploads_dir['baseurl']."/upfw";
if(!is_dir($base_upload_dir) ){
if( !is_writeable( $uploads_dir['basedir'] ) )
add_action( 'admin_notices', 'upfw_permissions_error', 1, 1 );
else{
$oldumask = umask(0);
#mkdir($base_upload_dir, 0775);
umask($oldumask);
if( is_writeable( $base_upload_dir ) )
add_action( 'admin_notices', 'upfw_uploads_folder_created',1 , 1 );
}
}
}
if($base_upload_dir)
define('UPFW_UPLOADS_DIR',$base_upload_dir, true);
if($base_upload_url)
define('UPFW_UPLOADS_URL',$base_upload_url, true);
}
add_action('upfw_theme_init','upfw_set_uploads_dir',2);
add_action('upfw_admin_init','upfw_set_uploads_dir',2);
/******
** Gentlemen, start your engines
*************************************/
function upfw_engines_init(){
require_once('library/options/options.php');
require_once('library/widgets/dashboard.php');
if( !defined('DISABLE_LAYOUT_ENGINE') )
require_once('library/engines/layout-engine.php');
if( !defined('DISABLE_STYLE_ENGINE') )
require_once('library/engines/style-engine.php');
if(function_exists('upfw_dbwidget_setup'))
add_action('wp_dashboard_setup', 'upfw_dbwidget_setup' );
if(function_exists('default_theme_layouts'))
add_action('init','default_theme_layouts',1);
}
add_action('upfw_theme_init','upfw_engines_init',10);
add_action('upfw_admin_init','upfw_engines_init',10);
/******
** Conditional to test if we're on
** an Pro Affiliate Framework page
*************************************/
function is_upthemes_page(){
if(is_admin()):
if(isset($_REQUEST['page']))$page = $_REQUEST['page'];
if(!empty($page)):
if( $page =='proframework' || $page=='proframework-buy' || $page =='proframework-docs' ):
return true;
else:
return false;
endif;
endif;
endif;
}
/******
** Add CSS and Javascript includes
*************************************/
function upfw_queue_scripts_styles(){
$upthemes = THEME_DIR.'/includes/pro_framework/';
wp_enqueue_style('up_framework',$upthemes."css/pro_framework.css");
//Check if theme-options/style.css exists and load it
if(file_exists(THEME_PATH ."/theme-options/style.css")):
wp_enqueue_style('theme_options',THEME_DIR."/theme-options/style.css");
endif;
wp_enqueue_style('farbtastic');
wp_enqueue_script('jquery.history',
$upthemes."js/jquery.history.js",
array('jquery'));
wp_enqueue_script('jquery.color',
$upthemes."js/jquery.color.js",
array('jquery'));
wp_enqueue_script('ajaxupload',
$upthemes."js/ajaxupload.js",
array('jquery'));
wp_enqueue_script('upfw',
$upthemes . "js/pro_framework.js",
array('farbtastic','jquery.history','ajaxupload'));
/* For Typography Engine */
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-widget');
wp_enqueue_script('jquery-ui-mouse');
wp_enqueue_script('jquery-ui-slider', get_bloginfo('template_directory').'/includes/pro_framework/js/jquery.ui.slider.js', array('jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-mouse'));
wp_enqueue_style('up-slider', get_bloginfo('template_directory').'/includes/pro_framework/css/ui-themes/smoothness/style.css');
}
if( is_admin() && is_upthemes_page() ):
add_action('upfw_theme_init','upfw_queue_scripts_styles',40);
add_action('upfw_admin_init','upfw_queue_scripts_styles',40);
endif;
/******
** Show gallery images
*************************************/
function show_gallery_images(){
global $wpdb;
$theme = THEME_DIR;
$path = UPFW_UPLOADS_DIR."/";
$dir_handle = #opendir($path) or die("Unable to open folder. Please make sure your uploads folder exists and has permissions of 775 or greater.");
while (false !== ($file = readdir($dir_handle))):
if($file == "index.php") continue;
if($file == ".") continue;
if($file == "..") continue;
if($file == "list.php") continue;
if($file == "Thumbs.db") continue;
$list .= '<a class="preview" href="'. UPFW_UPLOADS_URL . "/". $file . '"><img src="' . UPFW_UPLOADS_URL . "/" . $file . '" /></a>';
endwhile;
$list .= '<div class="clear"></div>';
echo $list;
closedir($dir_handle);
die();
}
/**
* Get current template context
*
* Returns a string containing the context of the
* current page template. This string is useful for several
* purposes, including applying an ID to the HTML
* body tag, and adding a contextual $name to calls
* to get_header(), get_footer(), get_sidebar(),
* and get_template_part_file(), in order to
* facilitate Child Themes overriding default Theme
* template part files.
*
* #param none
* #return string current page template context
*/
function upfw_get_template_context() {
$context = 'index';
if ( is_front_page() ) {
// Front Page
$context = 'front-page';
} else if ( is_date() ) {
// Date Archive Index
$context = 'date';
} else if ( is_author() ) {
// Author Archive Index
$context = 'author';
} else if ( is_category() ) {
// Category Archive Index
$context = 'category';
} else if ( is_tag() ) {
// Tag Archive Index
$context = 'tag';
} else if ( is_tax() ) {
// Taxonomy Archive Index
$context = 'taxonomy';
} else if ( is_archive() ) {
// Archive Index
$context = 'archive';
} else if ( is_search() ) {
// Search Results Page
$context = 'search';
} else if ( is_404() ) {
// Error 404 Page
$context = '404';
} else if ( is_attachment() ) {
// Attachment Page
$context = 'attachment';
} else if ( is_single() ) {
// Single Blog Post
$context = 'single';
} else if ( is_page() ) {
// Static Page
$context = 'page';
} else if ( is_home() ) {
// Blog Posts Index
$context = 'home';
}
return $context;
}
add_action('wp_ajax_show_gallery_images','show_gallery_images');
/******
** Create Framework Options Pages
*************************************/
function upfw_create_options_tabs(){
// Discover Options Files and Create Tabs Array
if( is_admin() ):
$path = THEME_PATH."/theme-options/";
$directory = #opendir($path) or wp_die("Cannot open theme-options folder in the ".UPTHEMES_NAME." folder.");
while (false !== ($file = readdir($directory))) {
if(!preg_match('/_/', $file)) continue;
if(preg_match('/_notes/', $file)) continue;
if(preg_match('/.DS/', $file)) continue;
//Take the extension off
$file = explode('.php', $file);
//Separate the ordinal
$file = explode('_', $file[0]);
$order = $file[1];
//Define the shortname
$shortname = $file[0];
//Define the title
$file = explode('-', $shortname);
$title = '';
foreach ($file as $part):
$title .= $part." ";
endforeach;
$title = ucwords($title);
//Add tab to array
global $up_tabs;
$up_tabs[$order] = array(trim($title) => $shortname);
$title = '';
}
closedir($directory);
//Sort tab order
global $up_tabs;
ksort($up_tabs);
endif;
}
add_action('upfw_admin_init','upfw_create_options_tabs',50);
/******
** Install default theme options
** if not already set
*************************************/
function upfw_set_defaults(){
if( ! get_option( 'up_themes_'.UPTHEMES_SHORT_NAME) && ( ! isset( $_GET['page'] ) || 'proframework' != $_GET['page'] ) ) :
//Redirect to options page where defaults will automatically be set
header('Location: '.get_bloginfo('url').'/wp-admin/admin.php?page=proframework');
exit;
endif;
}
add_action('upfw_theme_activation', 'upfw_set_defaults',2);
/******
** Set up global theme options
*************************************/
function upfw_setup_theme_options(){
$up_options_db = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
global $up_options;
//Check if options are stored properly
if( isset($up_options_db) && is_array($up_options_db) ):
add_action('upfw_theme_init','upfw_setup_theme_options',100);
add_action('upfw_admin_init','upfw_setup_theme_options',100);
/******
** Bootstrap static framework pages
*************************************/
function upthemes_admin_home() {require_once('home.php');}
function upthemes_admin_docs(){require_once('docs.php');}
/******
** Activate Pro Affiliate Framework admin
*************************************/
function upfw_upthemes_admin() {
$name = __('My Options', MOJO_TEXTDOMAIN);
$theme_options_icon = apply_filters('theme_options_icon',THEME_DIR.'/includes/pro_framework/images/upfw_ico_up_16x16.png');
add_menu_page($name, $name, 'edit_theme_options', 'proframework', 'upthemes_admin_home', $theme_options_icon, 59);
//Create tabbed pages from array
global $up_tabs;
if( is_array( $up_tabs ) ):
foreach ($up_tabs as $tab):
foreach($tab as $title => $shortname):
add_submenu_page('proframework', $title, $title, 'edit_theme_options', 'proframework#/'.$shortname, 'upthemes_admin_'.$shortname);
endforeach;
endforeach;
endif;
//Static subpages
// add_submenu_page('proframework', __('Documentation', MOJO_TEXTDOMAIN), __('Documentation', MOJO_TEXTDOMAIN), 'edit_theme_options', 'proframework-docs', 'upthemes_admin_docs');
}
add_action('admin_menu', 'upfw_upthemes_admin',2);
/******
** Find default options
*************************************/
function find_defaults($options){
global $up_defaults;
print_r($options);
}
/******
** Render theme options
*************************************/
function render_options($options){
//Check if theme options set
global $default_check;
global $default_options;
global $attr;
$attr = '';
if(!$default_check):
foreach($options as $option):
if($option['type'] != 'image'):
$default_options[$option['id']] = $option['value'];
else:
$default_options[$option['id']] = $option['url'];
endif;
endforeach;
$update_option = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
if(is_array($update_option)):
$update_option = array_merge($update_option, $default_options);
update_option('up_themes_'.UPTHEMES_SHORT_NAME, $update_option);
else:
update_option('up_themes_'.UPTHEMES_SHORT_NAME, $default_options);
endif;
endif;
foreach ($options as $value) {
//Check if there are additional attributes
if ( isset( $value['attr'] ) && is_array( $value['attr'] ) ):
$i = $value['attr'];
//Convert array into a string
foreach($i as $k => $v):
$attr .= $k.'="'.$v.'" ';
endforeach;
endif;
//Determine the type of input field
switch ( $value['type'] ) {
//Render Text Input
case 'text': upfw_text_field($value,$attr);
break;
//Render Custom User Text Inputs
case 'text_list': upfw_text_list($value,$attr);
break;
//Render textarea options
case 'textarea': upfw_textarea($value,$attr);
break;
//Render select dropdowns
case 'select': upfw_select($value,$attr);
break;
//Render multple selects
case 'multiple': upfw_multiple($value,$attr);
break;
//Render checkboxes
case 'checkbox': upfw_checkbox($value,$attr);
break;
//Render color picker
case 'color': upfw_color($value,$attr);
break;
//Render upload image
case 'image': upfw_image($value,$attr);
break;
//Render upload image
case 'logo': upfw_logo($value,$attr);
break;
//Render category dropdown
case 'category': upfw_category($value,$attr);
break;
//Render categories multiple select
case 'categories': upfw_categories($value,$attr);
break;
//Render offer dropdown
case 'offer': upfw_offer($value,$attr);
break;
//Render sales letter dropdown
case 'sales_letter': upfw_sales_letter($value,$attr);
break;
//Render squeeze page dropdown
case 'squeeze': upfw_squeeze($value,$attr);
break;
//Render page dropdown
case 'page': upfw_page($value,$attr);
break;
//Render pages muliple select
case 'pages': upfw_pages($value,$attr);
break;
//Render Form Button
case 'submit': upfw_submit($value,$attr);
break;
//Render taxonomy multiple select
case 'taxonomy': upfw_taxonomy($value,$attr);
break;
//Render Style Selector
case 'styles': upfw_style($value,$attr);
break;
//Render Form Button
case 'button': upfw_button($value,$attr);
break;
//Render Text Input
case 'divider': upfw_divider($value,$attr);
break;
//Render Layouts
case 'layouts': upfw_layouts($value,$attr);
break;
default:
break;
}
$attr = '';
}
}
if(is_admin() && is_upthemes_page()) add_action( 'upfw_admin_init','upfw_save_options', 3 );
function upfw_save_options(){
/* ----------------------- Form Security Check -------------------------- */
if(isset($_POST['_wpnonce'])):
//Check if submitted from this domain
check_admin_referer();
//Verify Form Nonce
if (!wp_verify_nonce($_POST['_wpnonce'], 'save_upthemes') )
wp_die('Security exception detected, please try again.');
exit;
endif;
/* ------------------Import/Export Functions ----------------------- */
//Restore Previous Options
global $export_message;
if(isset($_POST['up_restore'])):
$current = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
$backup = get_option('up_themes_'.UPTHEMES_SHORT_NAME.'_backup');
update_option('up_themes_'.UPTHEMES_SHORT_NAME.'_backup', $current);
update_option('up_themes_'.UPTHEMES_SHORT_NAME, $backup);
$export_message = "<p class='import'>" . __("Everything's back to normal now!", MOJO_TEXTDOMAIN) . "</p>";
endif;
//Restore Defaults
if(isset($_POST['up_defaults'])):
$current = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
update_option('up_themes_'.UPTHEMES_SHORT_NAME.'_backup', $current);
delete_option('up_themes_'.UPTHEMES_SHORT_NAME);
$export_message = "<p class='import'>" . __("Default options restored!", MOJO_TEXTDOMAIN) . "<span><form method='post' action=''><input class='up_restore' type='submit' name='up_restore' value='" . __("Click Here to Undo", MOJO_TEXTDOMAIN) . "'></form></span></p>";
endif;
/* ------------------------- Import Options Code ------------------------------- */
if(isset($_POST['up_import']) && isset($_POST['up_import_code'])):
$import = $_POST['up_import_code'];
$import = base64_decode($import);
$import = explode('~~', $import);
//Check if code is legitimate
if(count($import) == 2):
$option_name = $import[0];
$options = explode('||', $import[1]);
foreach ($options as $option):
$option = explode('|', $option);
global $new_options;
$new_options[$option[0]] = preg_replace('/"/', '\'', stripslashes($option[1]));
endforeach;
$current_option = get_option($option_name);
update_option($option_name.'_backup', $current_option);
update_option($option_name, $new_options);
$export_message = "<p class='import'>" . __("Options Code Import Successful!", MOJO_TEXTDOMAIN) . "<span><form method='post' action=''><input class='up_restore' type='submit' name='up_restore' value='" . __("Click Here to Undo", MOJO_TEXTDOMAIN) . "'></form></span></p>";
else:
$export_message = "<p class='import'>" . __("Oops! Something went wrong. <span>Try pasting your import code again.</span>", MOJO_TEXTDOMAIN) . "</p>";
endif;
endif;
/* ------------------------- Save Theme Options ------------------------------- */
if(isset($_POST['up_save'])):
$posts = $_POST;
foreach($posts as $k => $v):
//Check if option is array (mulitple selects)
if(is_array($v)):
//Check if array is empty
$check = 0;
foreach($v as $key => $value):
if($value != ''):
$check++;
endif;
endforeach;
//If array is not empty
if($check > 0 ):
//Remove empty array elements
$post[$k] = array_filter($v);
else:
$post[$k] = '';
endif;
$check = 0;
else:
//Remove slashes
$post[$k] = preg_replace('/"/', '\'', stripslashes($v));
endif;
endforeach;
//Add options array to wp_options table
update_option('up_themes_'.UPTHEMES_SHORT_NAME, $post);
endif;
/* ---------------------- Default Options Functions ----------------- */
global $default_check;
global $default_options;
$option_check = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
if($option_check):
$default_check = true;
else:
$default_check = false;
endif;
}
/******
** Remove Ugly First Link in
** WP Sidebar Menu
*************************************/
function remove_ugly_first_link(){ ?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('li#toplevel_page_upthemes li.wp-first-item').remove();
});
</script>
<?php }
if( is_admin() )
add_action("admin_head","remove_ugly_first_link");
/******
** RSS URL: rss('return') will return
** the value and not echo it.
*************************************/
function upfw_rss($i = ''){
global $up_options;
if($up_options->feedburner):
$rss = "http://feeds.feedburner.com/".$up_options->feedburner;
else:
$rss = get_bloginfo_rss('rss2_url');
endif;
if($i == 'return'): return $rss; else: echo $rss; endif;
}
/******
** RSS Subscribe URL: rss_email('return')
** will return the value and not echo it.
*************************************/
function upfw_rss_email($i = ''){
global $up_options;
if($up_options->feedburner):
$rssemail = "http://www.feedburner.com/fb/a/emailverifySubmit?feedId=" . $up_options->feedburner;
else:
$rssemail = "#";
endif;
if($i == 'return'): return $rssemail; else: echo $rssemail; endif;
}
/******
** Admin header hook
*************************************/
function upfw_admin_header(){
do_action('upfw_admin_header');
}
/******
** Open admin header
*************************************/
function upfw_admin_header_open(){ ?>
<div id="up_header" class="polish"><?php
}
add_action('upfw_admin_header','upfw_admin_header_open',1);
/******
** Set admin header title
*************************************/
function upfw_admin_header_title(){ ?>
<div id="icon-upfw" class="icon32 icon32-upfw"></div>
<h2><?php _e("", MOJO_TEXTDOMAIN); ?></h2> <?php
}
add_action('upfw_admin_header','upfw_admin_header_title',100);
/******
** Create admin header links
*************************************/
function upfw_admin_header_links(){ ?>
<ul id="up_topnav">
<?php do_action('upfw_admin_header_links'); ?>
</ul><!-- /#up_topnav --><?php
}
add_action('upfw_admin_header','upfw_admin_header_links',50);
/******
** Close admin header
*************************************/
function upfw_admin_header_close(){ ?>
<div class="clear"></div>
</div><!-- /#up_header --><?php
}
add_action('upfw_admin_header','upfw_admin_header_close',500);
/******
** Add default header links
*************************************/
function upfw_default_header_links(){ ?>
<li class="documentation"><?php _e("MOJO-Themes Item Page", MOJO_TEXTDOMAIN); ?></li>
<li class="support"><a target="_blank" href="http://docs.mojoness.com/"><?php _e("Support", MOJO_TEXTDOMAIN); ?></a></li>
<?php
}
add_action('upfw_admin_header_links','upfw_default_header_links');
sorry , just add ?> at last.
try to change it to
add_action('upfw_admin_header','upfw_admin_header_links',50);
Holding-Pattern-Theme
Looks like a missing } for function upfw_setup_theme_options() declaration (line 411).
EDIT:
function upfw_setup_theme_options(){
$up_options_db = get_option('up_themes_'.UPTHEMES_SHORT_NAME);
global $up_options;
//Check if options are stored properly
if( isset($up_options_db) && is_array($up_options_db) ):
# missing part start
//Check array to an object
foreach ($up_options_db as $k => $v) {
$up_options -> {$k} = $v;
}
else:
do_action('upfw_theme_activation');
endif;
}
#missing part end
from https://github.com/LiftUX/Holding-Pattern-Theme/blob/master/admin/admin.php
This error was happening on my local env but not on other's computers
Make sure you close the PHP tag correctly:
<?php } ?>
In my particular case:
<?php if( $condition ){ ?>
<div> content </div>
<? } ?>
That last block: <? } ?> was missing the ?php close tag.

Wordpress custom metabox input value with AJAX

I am using Wordpress 3.5, I have a custom post (sp_product) with a metabox and some input field. One of those input (sp_title).
I want to Search by the custom post title name by typing in my input (sp_title) field and when i press add button (that also in my custom meta box), It will find that post by that Title name and bring some post meta data into this Meta box and show into other field.
Here in this picture (Example)
Search
Click Button
Get some value by AJAX from a custom post.
Please give me a example code (just simple)
I will search a simple custom post Title,
Click a button
Get the Title of that post (that i search or match) with any other post meta value, By AJAX (jQuery-AJAX).
Please Help me.
I was able to find the lead because one of my plugins uses something similar to Re-attach images.
So, the relevant Javascript function is findPosts.open('action','find_posts').
It doesn't seem well documented, and I could only found two articles about it:
Find Posts Dialog Box
Using Built-in Post Finder in Plugins
Tried to implement both code samples, the modal window opens but dumps a -1 error. And that's because the Ajax call is not passing the check_ajax_referer in the function wp_ajax_find_posts.
So, the following works and it's based on the second article. But it has a security breach that has to be tackled, which is wp_nonce_field --> check_ajax_referer. It is indicated in the code comments.
To open the Post Selector, double click the text field.
The jQuery Select needs to be worked out.
Plugin file
add_action( 'load-post.php', 'enqueue_scripts_so_14416409' );
add_action( 'add_meta_boxes', 'add_custom_box_so_14416409' );
add_action( 'wp_ajax_find_posts', 'replace_default_ajax_so_14416409', 1 );
/* Scripts */
function enqueue_scripts_so_14416409() {
# Enqueue scripts
wp_enqueue_script( 'open-posts-scripts', plugins_url('open-posts.js', __FILE__), array('media', 'wp-ajax-response'), '0.1', true );
# Add the finder dialog box
add_action( 'admin_footer', 'find_posts_div', 99 );
}
/* Meta box create */
function add_custom_box_so_14416409()
{
add_meta_box(
'sectionid_so_14416409',
__( 'Select a Post' ),
'inner_custom_box_so_14416409',
'post'
);
}
/* Meta box content */
function inner_custom_box_so_14416409( $post )
{
?>
<form id="emc2pdc_form" method="post" action="">
<?php wp_nonce_field( 'find-posts', '_ajax_nonce', false); ?>
<input type="text" name="kc-find-post" id="kc-find-post" class="kc-find-post">
</form>
<?php
}
/* Ajax replacement - Verbatim copy from wp_ajax_find_posts() */
function replace_default_ajax_so_14416409()
{
global $wpdb;
// SECURITY BREACH
// check_ajax_referer( '_ajax_nonce' );
$post_types = get_post_types( array( 'public' => true ), 'objects' );
unset( $post_types['attachment'] );
$s = stripslashes( $_POST['ps'] );
$searchand = $search = '';
$args = array(
'post_type' => array_keys( $post_types ),
'post_status' => 'any',
'posts_per_page' => 50,
);
if ( '' !== $s )
$args['s'] = $s;
$posts = get_posts( $args );
if ( ! $posts )
wp_die( __('No items found.') );
$html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>'.__('Title').'</th><th class="no-break">'.__('Type').'</th><th class="no-break">'.__('Date').'</th><th class="no-break">'.__('Status').'</th></tr></thead><tbody>';
foreach ( $posts as $post ) {
$title = trim( $post->post_title ) ? $post->post_title : __( '(no title)' );
switch ( $post->post_status ) {
case 'publish' :
case 'private' :
$stat = __('Published');
break;
case 'future' :
$stat = __('Scheduled');
break;
case 'pending' :
$stat = __('Pending Review');
break;
case 'draft' :
$stat = __('Draft');
break;
}
if ( '0000-00-00 00:00:00' == $post->post_date ) {
$time = '';
} else {
/* translators: date format in table columns, see http://php.net/date */
$time = mysql2date(__('Y/m/d'), $post->post_date);
}
$html .= '<tr class="found-posts"><td class="found-radio"><input type="radio" id="found-'.$post->ID.'" name="found_post_id" value="' . esc_attr($post->ID) . '"></td>';
$html .= '<td><label for="found-'.$post->ID.'">' . esc_html( $title ) . '</label></td><td class="no-break">' . esc_html( $post_types[$post->post_type]->labels->singular_name ) . '</td><td class="no-break">'.esc_html( $time ) . '</td><td class="no-break">' . esc_html( $stat ). ' </td></tr>' . "\n\n";
}
$html .= '</tbody></table>';
$x = new WP_Ajax_Response();
$x->add( array(
'data' => $html
));
$x->send();
}
Javascript file open-posts.js
jQuery(document).ready(function($) {
// Find posts
var $findBox = $('#find-posts'),
$found = $('#find-posts-response'),
$findBoxSubmit = $('#find-posts-submit');
// Open
$('input.kc-find-post').live('dblclick', function() {
$findBox.data('kcTarget', $(this));
findPosts.open();
});
// Insert
$findBoxSubmit.click(function(e) {
e.preventDefault();
// Be nice!
if ( !$findBox.data('kcTarget') )
return;
var $selected = $found.find('input:checked');
if ( !$selected.length )
return false;
var $target = $findBox.data('kcTarget'),
current = $target.val(),
current = current === '' ? [] : current.split(','),
newID = $selected.val();
if ( $.inArray(newID, current) < 0 ) {
current.push(newID);
$target.val( current.join(',') );
}
});
// Double click on the radios
$('input[name="found_post_id"]', $findBox).live('dblclick', function() {
$findBoxSubmit.trigger('click');
});
// Close
$( '#find-posts-close' ).click(function() {
$findBox.removeData('kcTarget');
});
});

Resources