Parse error: syntax error, unexpected end of file in___ - wordpress

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.

Related

Wordpress Metabox - problem with display value in page template

I am adding a custom metabox for WordPress, I am able to save the value but unable to display the value in a page template.
Code in function.php
//Custome MetaBox
function custom_metabox() {
add_meta_box("custom_metabox_01", "Custom Metabox", "custom_metabox_field", "page", "side", "default", null);
}
add_action("admin_init", "custom_metabox");
function custom_metabox_field() {
wp_nonce_field(basename(__FILE__), "custom_metabox_01_nonce");
global $post;
$data = get_post_custom($post->ID);
$val = isset($data['custom_input']) ? esc_attr($data['custom_input'][0]) : 'no value';
echo '<input type="text" name="custom_input" id="custom_input" value="'.$val.'" />';
}
function save_detail() {
global $post;
if (!isset($_POST["custom_metabox_01_nonce"]) || !wp_verify_nonce($_POST["custom_metabox_01_nonce"], basename(__FILE__))){
return $post->ID;
}
if(!current_user_can("edit_post", $post->ID)){
return $post->ID;
}
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "custom_input", $_POST["custom_input"]);
}
add_action("save_post", "save_detail");
Code in template-parts/content/content-page.php
<div class="metabox">
<?php
$custom_post_type = get_post_meta($post->ID, 'custom_input', true);
echo 'meta box value: ' . $custom_post_type;
?>
</div>
Also please suggest to me how to implement the same only for "theme-template/default.php( Custom Page Template)"
Thanks in advance.

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
}

Import CSV code with insert post and post meta tables?

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.

How to show recent post in the main domain from subdomain blog

need to show the recent post from my subdomain to my main domain frontend. I am using below code, but its picking only main domain recent post. any help to fetch subdomain recent post ?
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
EDIT 2:
So it turns out, that you are not running both sites from the same WordPress installation(otherwise referred to as a WordPress Network). Here is what I can suggest that you use in this case.
Put this code in the main site's functions.php:
/**
* this function retrieves the requested part of the main site
* ok, well basically can be from any site, depending on the $url param, as long as it has the proper function that will display the requested content
* #param $url - the url of the site
* #param $key - part of the name of the function that will display the content
* #param $add_qs - any additional query string that will be appended, use "&params=param1,param2,param3" to pass "param1", "param2" and "param3"
* to the loading function
*/
function get_main_site_part($url, $key, $add_qs = '') {
// cache the result, so we don't make a request with each page load
$cache = ABSPATH . 'wp-content/uploads/main_site_' . $key . '.txt';
$cache_lifetime = 300;
// just to make sure - try to remove the trailing slash in the $url
$url = untrailingslashit($url);
$uri = $url . '/?including_template_part=1&load_part=' . $key . $add_qs;
# reload the cache on every 5 minutes
if (!file_exists($cache) || time() - filemtime($cache) > $cache_lifetime) {
$main_site_html = wp_remote_get($uri);
if (is_a($main_site_html, 'WP_Error')) {
//print_r($main_site_html);
//exit('error! ');
return;
}
$fp = fopen($cache, 'w');
fwrite($fp, $main_site_html);
fclose($fp);
} else {
$main_site_html = file_get_contents($cache);
}
return $main_site_html;
}
Now put this function in your sub-domain's functions.php:
/* HTML LOADING HOOK - For loading content from one site to another - best application in multisite */
function print_requested_template_part() {
// Respond only to requests from the same address...
if ( $_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR'] && $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
$part = $_GET['load_part'];
$func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
if ( function_exists($func) ) {
// Allow for passing parameters to the function
if ( isset($_GET['params']) ) {
$params = $_GET['params'];
$params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
call_user_func_array($func, $params);
} else {
call_user_func($func);
}
}
exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
}
}
add_action('init', 'print_requested_template_part', 1);
function render_my_recent_posts( $numberposts = 5 ) { ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul><?php
}
Then in your main site call this function, where you want your recent posts to appear:
echo get_main_site_part( 'http://questions.admissiontimes.com/', 'my_recent_posts', '&params=5' )
EDIT 1:
Using the sample code that you have in your question, combined with my solution from below, here is what the final code will look like:
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts from. You can see the ID when you edit a site through the Network Admin - the URL will look something like "http://example.com/wp-admin/network/site-info.php?id=2" - you need the value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
Now, you just put that code wherever you had your original code and everything should be working properly.
You need to switch to the blog in question, using the switch_to_blog($blog_id) function, where $blog_id is the ID of the blog(sub-site) in question.
Then do your normal get_posts/or equivalent/ function and display/store the posts in the way you want.
Once you're done with that, just call restore_current_blog() and that's it.

How to display WordPress RSS feed your website?

Hello i have a website and a blog, i want to display my self hosted wordpress blog on my website.
I want to show only 3 post on my website.
I want to automatically check for any new post everytime when i reload my website, so that the recent three gets displayed only.
I want to show the complete title of my wordpress blogpost but specific letters of description.
Also the description should end up with a word not some piece of non-dictionary word ending with "..."
How this can be done, i have heard that it can be done through RSS.
Can somebody help me?
To accomplish this you need to read the RSS of the blog, from RSS you need to read the Title and the description, after reading the whole description and title you need to trim the description to your desired number of letters. After that you need to check weather the description last word has been completed or not and then you need to remove a the last word if not completed and put the "...".
First we will make a script to trim the description and to put "..." in last:-
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}
Now we will define the variables in which we store the values:-
$xml=("http://your-blog-path/rss/");
global $item_title, $item_link, $item_description;
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
$x=$xmlDoc->getElementsByTagName('item');
Now, we will make an array and store values in it. I am only taking 3 because you have asked it the way. You can change it to anything (The number of post you want to show, put that in the loop)
for ($i=0; $i<3; $i++)
{
$item_title[$i] = $x->item($i)->getElementsByTagName('title')->item(0)->childNodes->item(0)->nodeValue;
$item_link[$i] = $x->item($i)->getElementsByTagName('link')->item(0)->childNodes->item(0)->nodeValue;
$item_description[$i] = $x->item($i)->getElementsByTagName('description')->item(0)->childNodes->item(0)->nodeValue;
}
?>
Now echo all these values, Link is the value where your user will click and he will be taken to your blog:-
FIRST RECENT POST:
<?php echo $item_title[0]; ?>
<?php echo substrwords($item_description[0],70); ?>
SECOND RECENT POST:
<?php echo $item_title[1]; ?>
<?php echo substrwords($item_description[1],70); ?>
THIRD RECENT POST:
<?php echo $item_title[2]; ?>
<?php echo substrwords($item_description[2],70); ?>
Hope this can solve your problem. By the way Nice question.
Click here for the original documentation on displaying RSS feeds with PHP.
Django Anonymous's substrwords function is being used to trim the description and to insert the ... at the end of the description if the it passes the $maxchar value.
Full Code:
blog.php
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
} else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
} else {
$output = $text;
}
return $output;
}
$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/'); // <-- Change feed to your site
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 3; // <-- Change the number of posts shown
for ($x=0; $x<$limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$description = substrwords($description, 100);
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<p><strong>'.$title.'</strong><br />';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}
?>
You can easily put this in a separate PHP file (blog.php) and call it inside your actual page.
Example:
social.php
<h3>Latest blog post:</h3>
<?php require 'blog.php' ?>
Also, this code is plug-n-play friendly.
Why not use the Wordpress REST API to retrieve posts -
API URL is : https://public-api.wordpress.com/rest/v1/sites/$site/posts/
where $site is the site id of your wordpress blog
or else simply use this plugin -
http://www.codehandling.com/2013/07/wordpress-feeds-on-your-website-with.html

Resources