Wordpress - Create own admin messages for Custom Post Type - wordpress

I've created a custom post type called routes and I'd like to be able to return error messages to the screen when something goes wrong during a save/update e.g. The type allows for gpx/kml files to be uploaded and checked that the correct type has been posted. At the moment it just returns if it goes wrong - how can I set an error message?
//Return if file type wrong.
if($file_type != 'application/octet-stream' && $file_type != 'application/gpx+xml' ) {
return;
}

try this
example:
add_admin_message('Please enter valid URL for the project link', true);
add_admin_message('Your custom post type was updated');
source:
<?php
/**
* Messages with the default wordpress classes
*/
function showMessage($message, $errormsg = false)
{
if ($errormsg) {
echo '<div id="message" class="error">';
}
else {
echo '<div id="message" class="updated fade">';
}
echo "<p>$message</p></div>";
}
/**
* Display custom messages
*/
function show_admin_messages()
{
if(isset($_COOKIE['wp-admin-messages-normal'])) {
$messages = strtok($_COOKIE['wp-admin-messages-normal'], "##");
while ($messages !== false) {
showMessage($messages, true);
$messages = strtok("##");
}
setcookie('wp-admin-messages-normal', null);
}
if(isset($_COOKIE['wp-admin-messages-error'])) {
$messages = strtok($_COOKIE['wp-admin-messages-error'], "##");
while ($messages !== false) {
showMessage($messages, true);
$messages = strtok("##");
}
setcookie('wp-admin-messages-error', null);
}
}
/**
* Hook into admin notices
*/
add_action('admin_notices', 'show_admin_messages');
/**
* User Wrapper
*/
function add_admin_message($message, $error = false)
{
if(empty($message)) return false;
if($error) {
setcookie('wp-admin-messages-error', $_COOKIE['wp-admin-messages-error'] . '##' . $message, time()+60);
} else {
setcookie('wp-admin-messages-normal', $_COOKIE['wp-admin-messages-normal'] . '##' . $message, time()+60);
}
}

Related

Function to check status of gravityforms wordpress

I am trying to make a function to check if the gform has some entries, has all entries or is empty and return $status according to status.
I have looped through the entries and checked if they are infact shown as an empty string if empty but I only ever get partial or empty.
function set_form_status($form_id) {
$entries = GFAPI::get_entries( $form_id, entry_search_criteria());
$status = '';
if (count($entries) > 0) {
foreach($entries as $entry) {
$keys = array_keys($entry);
foreach($keys as $key) {
if ($entry[$key] === '') {
$status = 'partial';
}
if ($entry[$key] !== '') {
$status = 'filled';
}
}
}
} else {
$status = 'empty';
}
return $status;
}
I'd suggest running it like below and seeing what gets returned. I did remove the entry_search_criteria function but other than that I'm just echoing the key/value.
What I found was even if I'm not using purchasing in a form, there are fields created for it and they are empty. They don't show on the back end entry view even if I select show empty fields. You may have a similar scenario.
function set_form_status($form_id) {
$entries = GFAPI::get_entries( $form_id);
$status = '';
if (count($entries) > 0) {
foreach($entries as $entry) {
$keys = array_keys($entry);
foreach($keys as $key) {
echo $key . ' - ' . $entry[$key] . '<br>';
if ($entry[$key] === '') {
$status = 'partial';
}
if ($entry[$key] !== '') {
$status = 'filled';
}
}
}
} else {
$status = 'empty';
}
return $status;
}
Did some refactoring and debugging together with a co-worker, there was HTML fields on all of the forms and all of them returned an empty string. This is the working version.
function set_form_status($form) {
define('FORM_EMPTY', 0);
define('FORM_PARTIAL', 1);
define('FORM_FILLED', 2);
//checks if the form is my special kind of form
if (is_eligible_form($form)) {
$earlier_entry = get_last_entry($form['id']);
if ($earlier_entry === false) {
return STATUS_EMPTY;
} else {
foreach($form['fields'] as $key => $field) {
if ($earlier_entry[$field->id] === '' && $field->type !== 'html') {
return FORM_PARTIAL;
}
}
}
}
return FORM_FILLED;
}

Warning: session_start(): Cannot send session cache limiter

here is the error i get on my website when trying to process a payment page am not sure what to do i found this code
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/bargainhivee/public_html/wp-includes/wp-db.php:1482) in /home/bargainhivee/public_html/wp-content/plugins/Tevolution/tmplconnector/templatic-connector.php on line 5
this is the line 5
if (!isset($_SESSION)) { session_start(); }
here is the php file templatic-connector.php
<?php
/*
* includes the main files of tevolution default ad-on such as claim ownership,custom taxonomy,csutom fields,etc. and common functions.
*/
if (!isset($_SESSION)) { session_start(); }
require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-claim_ownership/install.php" );
require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-custom_taxonomy/install.php" );
require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-custom_fields/install.php" );
require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-monetization/install.php" );
require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-ratings/install.php" );
require_once(TEMPL_MONETIZE_FOLDER_PATH."/templatic-registration/install.php" );
require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_browse_by_categories_widget.php");
require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_advanced_search_widget.php");
require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_people_list_widget.php");
require_once (TEMPL_MONETIZE_FOLDER_PATH . "/templatic-widgets/templatic_metakey_search_widget.php");
require_once(TEMPL_MONETIZE_FOLDER_PATH."templatic-generalization/general_functions.php" );
/* Add to favourites for tevolution*/
if(file_exists(TEMPL_MONETIZE_FOLDER_PATH."templatic-generalization/add_to_favourites.php") && (!strstr($_SERVER['REQUEST_URI'],'/wp-admin/') || strstr
($_SERVER['REQUEST_URI'],'/admin-ajax.php') )){
require_once(TEMPL_MONETIZE_FOLDER_PATH."templatic-generalization/add_to_favourites.php" );
}
/*
do action for admin menu
*/
add_action('admin_menu', 'templ_add_admin_menu_'); /* create templatic admin menu */
function templ_add_admin_menu_()
{
do_action('templ_add_admin_menu_');
}
add_action('templ_add_admin_menu_', 'templ_add_mainadmin_menu_', 0);
add_action('templ_add_admin_menu_', 'templ_remove_mainadmin_sub_menu_');
if(!function_exists('templ_remove_mainadmin_sub_menu_')){
function templ_remove_mainadmin_sub_menu_(){
remove_submenu_page('templatic_system_menu', 'templatic_system_menu');
add_submenu_page( 'templatic_system_menu', __('Overview','templatic-admin'), __('Overview','templatic-admin'), 'administrator',
'templatic_system_menu', 'templatic_connector_class' );
}
}
/*
include the main.connector.class.php file
*/
function templatic_connector_class()
{
require_once(TEVOLUTION_PAGE_TEMPLATES_DIR.'classes/main.connector.class.php' );
}
/*
Return the main menu at admin sidebar
*/
function templ_add_mainadmin_menu_()
{
$menu_title = __('Tevolution', 'templatic');
if (function_exists('add_object_page'))
{
if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'templatic_system_menu'){
$icon = TEMPL_PLUGIN_URL.'favicon-active.png';
}else{
$icon = TEMPL_PLUGIN_URL.'favicon-active.png';
}
$hook = add_menu_page("Admin Menu", $menu_title, 'administrator', 'templatic_system_menu', 'dashboard_bundles', '',3); /* title of new
sidebar*/
}else{
add_menu_page("Admin Menu", $menu_title, 'administrator', 'templatic_wp_admin_menu', 'design','');
}
}
/*
return the connection with dashboard wizards(bundle box)
*/
function dashboard_bundles()
{
$Templatic_connector = New Templatic_connector;
require_once(TEVOLUTION_PAGE_TEMPLATES_DIR.'classes/main.connector.class.php' );
if(isset($_REQUEST['tab']) && $_REQUEST['tab'] =='extend') {
$Templatic_connector->templ_extend();
}else if(isset($_REQUEST['tab']) && $_REQUEST['tab'] =='payment-gateways') {
$Templatic_connector->templ_payment_gateway();
}else if((!isset($_REQUEST['tab'])&& #$_REQUEST['tab']=='') || isset($_REQUEST['tab']) && $_REQUEST['tab'] =='overview') {
$Templatic_connector->templ_overview();
$Templatic_connector->templ_dashboard_extends();
}
}
/*
return main CSS of Plugin
*/
add_action('admin_head', 'templ_add_my_stylesheet'); /* include style sheet */
add_action('wp_head', 'templ_add_my_stylesheet',0); /* include style sheet */
function templ_add_my_stylesheet()
{
/* Respects SSL, Style.css is relative to the current file */
wp_enqueue_script('jquery');
$tmpl_is_allow_url_fopen = tmpl_is_allow_url_fopen();
/* Tevolution Plug-in Style Sheet File In Desktop view only */
if (function_exists('tmpl_wp_is_mobile') && !tmpl_wp_is_mobile()) {
/* if "allow_url_fopen" is enabled then apply minifiled css otherwise includse seperately */
if(!$tmpl_is_allow_url_fopen){
wp_enqueue_style('tevolution_style',TEMPL_PLUGIN_URL.'style.css','',false);
}else{
wp_enqueue_style('tevolution_style',TEMPL_PLUGIN_URL.'css.minifier.php','',false);
}
}
if(function_exists('theme_get_settings')){
if(theme_get_settings('supreme_archive_display_excerpt')){
if(function_exists('tevolution_excerpt_length')){
add_filter('excerpt_length', 'tevolution_excerpt_length');
}
if(function_exists('new_excerpt_more')){
add_filter('excerpt_more', 'new_excerpt_more');
}
}
}
}
/* check if "allow_url_fopen" is enabled or not */
function tmpl_is_allow_url_fopen(){
if( ini_get('allow_url_fopen') ) {
return true;
}else{
return false;
}
}
/*
return each add-ons is activated or not
*/
function is_active_addons($key)
{
$act_key = get_option($key);
if ($act_key != '')
{
return true;
}
}
/*
Function will remove the admin dashboard widget
*/
function templ_remove_dashboard_widgets()
{
/* Globalize the metaboxes array, this holds all the widgets for wp-admin*/
global $wp_meta_boxes;
/* Remove the Dashboard quickpress widget*/
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
/* Remove the Dashboard incoming links widget*/
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
/* Remove the Dashboard secondary widget*/
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
}
add_action('wp_dashboard_setup', 'templ_remove_dashboard_widgets');
/* -- coding to add submenu under main menu-- */
add_action('templ_add_admin_menu_', 'templ_add_page_menu');
function templ_add_page_menu()
{
/*tevolution_menu_before_general_settings hook for add additional menu before general settings */
do_action('tevolution_menu_before_general_settings');
$menu_title2 = __('Settings', 'templatic-admin');
add_submenu_page('templatic_system_menu', $menu_title2, $menu_title2,'administrator', 'templatic_settings', 'my_page_templates_function');
/*tevolution_menu_after_general_settings hook for add additional menu after general settings */
do_action('tevolution_menu_after_general_settings');
}
/*
Email, security , and set up steps menu selected
*/
add_action('admin_footer','tevolution_menu_script');
function tevolution_menu_script()
{
?>
<script data-cfasync="false" type="text/javascript" async >
jQuery(document).ready(function(){
if(jQuery('#adminmenu ul.wp-submenu li').hasClass('current'))
{
<?php if(isset($_REQUEST['page']) && $_REQUEST['page']=='templatic_system_menu' && isset($_REQUEST['tab']) && $_REQUEST['tab']=='setup-steps'
):?>
jQuery('#adminmenu ul.wp-submenu li').removeClass('current');
jQuery('#adminmenu ul.wp-submenu li a').removeClass('current');
jQuery('#adminmenu ul.wp-submenu li a[href*="page=templatic_system_menu&tab=setup-steps"]').attr('href', function() {
jQuery('#adminmenu ul.wp-submenu li a[href*="page=templatic_system_menu&tab=setup-steps"]').addClass('current');
jQuery('#adminmenu ul.wp-submenu li a[href*="page=templatic_system_menu&tab=setup-steps"]').parent().addClass('current');
});
<?php endif;?>
}
jQuery('.reset_custom_fields').click( function() {
if(confirm("<?php echo __('All your modifications done with this, will be deleted forever! Still you want to proceed?','templatic-admin');?
>")){
return true;
}else{
return false;
}
});
});
</script>
<?php
}
/* include general_settings.php file */
function my_page_templates_function()
{
include(TEMPL_MONETIZE_FOLDER_PATH.'templatic-generalization/general_settings.php');
}
/*
Redirect on plugin dashboard after activating plugin
*/
add_action('admin_init', 'my_plugin_redirect');
function my_plugin_redirect()
{
global $pagenow;
if (get_option('myplugin_redirect_on_first_activation') == 'true' && $pagenow=='plugins.php' ){
update_option('myplugin_redirect_on_first_activation', 'false');
wp_redirect(MY_PLUGIN_SETTINGS_URL);
}
if (get_option('myplugin_redirect_on_first_activation') == 'true' && $pagenow=='themes.php' ){
update_option('myplugin_redirect_on_first_activation', 'false');
wp_redirect(site_url().'/wp-admin/themes.php');
}
}
/*
* View counter for detail page
*/
function view_counter_single_post($pid){
if($_SERVER['HTTP_REFERER'] == '' || !strstr($_SERVER['HTTP_REFERER'],$_SERVER['REQUEST_URI']))
{
$viewed_count = get_post_meta($pid,'viewed_count',true);
$viewed_count_daily = get_post_meta($pid,'viewed_count_daily',true);
$daily_date = get_post_meta($pid,'daily_date',true);
update_post_meta($pid,'viewed_count',$viewed_count+1);
if(get_post_meta($pid,'daily_date',true) == date('Y-m-d')){
update_post_meta($pid,'viewed_count_daily',$viewed_count_daily+1);
} else {
update_post_meta($pid,'viewed_count_daily','1');
}
update_post_meta($pid,'daily_date',date('Y-m-d'));
}
}
/*
* return the count of post view
*/
if(!function_exists('user_single_post_visit_count')){
function user_single_post_visit_count($pid)
{
if(get_post_meta($pid,'viewed_count',true))
{
return get_post_meta($pid,'viewed_count',true);
}else
{
return '0';
}
}
}
/*
* Function Name:user_single_post_visit_count_daily
* Argument: Post id
*/
if(!function_exists('user_single_post_visit_count_daily')){
function user_single_post_visit_count_daily($pid)
{
if(get_post_meta($pid,'viewed_count_daily',true))
{
return get_post_meta($pid,'viewed_count_daily',true);
}else
{
return '0';
}
}
}
/*
* add view count display after the content
*/
if( !function_exists('view_count')){
function view_count( $content ) {
if ( is_single())
{
global $post;
$sep =" , ";
$custom_content='';
$custom_content.="<p>".__('Visited','templatic')." ".user_single_post_visit_count($post->ID)." ".__('times','templatic');
$custom_content.= $sep.user_single_post_visit_count_daily($post->ID).__(" Visits today",'templatic')."</p>";
$custom_content .= $content;
echo $custom_content;
}
}
}
/*
* show counter and share button after custom fields.
*/
function teamplatic_view_counter()
{
$settings = get_option( "templatic_settings" );
if(isset($settings['templatic_view_counter']) && $settings['templatic_view_counter']=='Yes')
{
global $post;
view_counter_single_post($post->ID);
view_count('');
}
//view_sharing_buttons('');
tevolution_socialmedia_sharelink();
}
/*Remove the the_content filter to add view counter everywhere in single page and add action tmpl_detail_page_custom_fields_collection before the custom
field display*/
add_action('tmpl_detail_page_custom_fields_collection','teamplatic_view_counter',5);
function view_sharing_buttons($content)
{
global $post;
if (is_single() && ($post->post_type!='post' && $post->post_type!='page' && $post->post_type!='product' && $post->post_type!='product_variation'
))
{
$post_img = bdw_get_images_plugin($post->ID,'thumb');
$post_images = $post_img[0];
$title=urlencode($post->post_title);
$url=urlencode(get_permalink($post->ID));
$summary=urlencode(htmlspecialchars($post->post_content));
$image=$post_images;
$settings = get_option( "templatic_settings" );
if($settings['facebook_share_detail_page'] =='yes' || $settings['google_share_detail_page'] == 'yes' || $settings
['twitter_share_detail_page'] == 'yes' || $settings['pintrest_detail_page']=='yes'){
echo '<div class="share_link">';
if($settings['facebook_share_detail_page'] == 'yes')
{
?>
<a onClick="window.open('//www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[summary]=<?php echo
$summary;?>&p[url]=<?php echo $url; ?>&&p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=548,height=325');"
href="javascript: void(0)" id="facebook_share_button"><?php _e('Facebook Share.',T_DOMAIN); ?></a>
<?php
}
if($settings['google_share_detail_page'] == 'yes'): ?>
<script data-cfasync="false" type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<div class="g-plus" data-action="share" data-annotation="bubble"></div>
<?php endif;
if($settings['twitter_share_detail_page'] == 'yes'): ?>
<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-text='<?php echo htmlentities
($post->post_content);?>' data-url="<?php echo get_permalink($post->ID); ?>" data-counturl="<?php echo get_permalink($post->ID); ?>"><?php _e
('Tweet',T_DOMAIN); ?></a>
<script data-cfasync="false">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id))
{js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-
wjs");</script>
<?php endif;
if(#$settings['pintrest_detail_page']=='yes'):?>
<!-- Pinterest -->
<div class="pinterest">
<a href="//pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink($post->ID)); ?>&media=<?php echo $image; ?
>&description=<?php the_title(); ?>" ><?php _e('Pin It','templatic');?></a>
<script data-cfasync="false" type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>
</div>
<?php endif;
echo '</div>';
}
}
return $content;
}
/*
return the currency code
*/
function templatic_get_currency_type()
{
global $wpdb;
$option_value = get_option('currency_code');
if($option_value)
{
return stripslashes($option_value);
}else
{
return 'USD';
}
}
/*
this function returns the currency with position selected in currency settings
*/
function fetch_currency_with_position($amount,$currency = '')
{
$amt_display = '';
if($amount==''){ $amount =0; }
$decimals=get_option('tmpl_price_num_decimals');
$decimals=($decimals!='')?$decimals:2;
if($amount >=0 )
{
if(#$amount !='')
$amount = number_format( (float)($amount),$decimals,'.','');
$currency = get_option('currency_symbol');
$position = get_option('currency_pos');
if($position == '1')
{
$amt_display = $currency.$amount;
}
else if($position == '2')
{
$amt_display = $currency.' '.$amount;
}
else if($position == '3')
{
$amt_display = $amount.$currency;
}
else
{
$amt_display = $amount.' '.$currency;
}
return apply_filters('tmpl_price_format',$amt_display,$amount,$currency);
}
}
/*
this function returns the currency with position selected in currency settings
*/
function fetch_currency_with_symbol($amount,$currency = '')
{
$amt_display = '';
if($amount==''){ $amount =0; }
$decimals=get_option('tmpl_price_num_decimals');
$decimals=($decimals!='')?$decimals:2;
if($amount >=0 )
{
if(#$amount !='')
$amount = $amount;
$currency = get_option('currency_symbol');
$position = get_option('currency_pos');
if($position == '1')
{
$amt_display = $currency.$amount;
}
else if($position == '2')
{
$amt_display = $currency.' '.$amount;
}
else if($position == '3')
{
$amt_display = $amount.$currency;
}
else
{
$amt_display = $amount.' '.$currency;
}
return apply_filters('tmpl_price_format',$amt_display,$amount,$currency);
}
}
/* eof - display currency with position */
/* this function will display the legends descr

Wordpress validation for title

Need to add blank and already exist validation for 'supports' => array( 'title') on my custom post type. But i dont want to use any plugin for this.
Thanks in advance.
add_action( 'admin_notices', 'custom_error_notice' );
function custom_error_notice(){
global $current_screen, $post;
if ( $current_screen->parent_base == 'edit' ){
if((!$post->post_name) && $_GET['post']) {
wp_redirect(admin_url('post-new.php?empty=1'));
}
if($_GET['empty']) echo '<div class="error"><p>Warning - Please fill up all fields correctly!</p></div>';
}
}
But this not working properly.
This may help you:-
add_action('save_post', 'album_save_post', 10, 2);
function album_save_post( $album_id, $album ) {
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || $album->post_type != 'music_album') return;
// echo '<pre>';
// print_r($album);
// echo '</pre>';
// die();
$errors = array();
// Validation filters
$title = $album->post_title;
if ( ! $title ) {
$errors['title'] = "The title is required";
}
// if we have errors lets setup some messages
if (! empty($errors)) {
// we must remove this action or it will loop for ever
remove_action('save_post', 'album_save_post');
// save the errors as option
update_option('album_errors', $errors);
// Change post from published to draft
$album->post_status = 'draft';
// update the post
wp_update_post( $album );
// we must add back this action
add_action('save_post', 'album_save_post');
// admin_notice is create by a $_GET['message'] with a number that wordpress uses to
// display the admin message so we will add a filter for replacing default admin message with a redirect
add_filter( 'redirect_post_location', 'album_post_redirect_filter' );
}
}
function album_post_redirect_filter( $location ) {
// remove $_GET['message']
$location = remove_query_arg( 'message', $location );
// add our new query sting
$location = add_query_arg( 'album', 'error', $location );
// return the location query string
return $location;
}
// Add new admin message
add_action( 'admin_notices', 'album_post_error_admin_message' );
function album_post_error_admin_message() {
if ( isset( $_GET['album'] ) && $_GET['album'] == 'error' ) {
// lets get the errors from the option album_errors
$errors = get_option('album_errors');
// now delete the option album errors
delete_option('album_errors');
$display = '<div id="notice" class="error"><ul>';
// Because we are storing as an array we should loop through them
foreach ( $errors as $error ) {
$display .= '<li>' . $error . '</li>';
}
$display .= '</ul></div>';
// finally echo out our display
echo $display;
// add some jQuery
?>
<script>
jQuery(function($) {
$("#title").css({"border": "1px solid red"})
});
</script>
<?php
}
}
i got the solution.
/** ADD Validation for title */
function force_post_title_init()
{
wp_enqueue_script('jquery');
}
function force_post_title()
{
echo "<script type='text/javascript'>\n";
echo "
jQuery('#publish').click(function(){
var testervar = jQuery('[id^=\"titlediv\"]')
.find('#title');
if (testervar.val().length < 1)
{
jQuery('[id^=\"titlediv\"]').css('border', '1px solid red');
alert('Post title is required');
return false;
}
});
";
echo "</script>\n";
}
add_action('admin_init', 'force_post_title_init');
add_action('edit_form_advanced', 'force_post_title');
// Add this row below to get the same functionality for page creations.
add_action('edit_page_form', 'force_post_title');
May be this also help for all of you.

Drupal_mail() empty body and no subject

I'm having issues with drupal_mail(). I receive the email but the subject and body are empty.
Drupal version 7
code below
$params = array(
'subject' => t('Client Requests Quote'),
'body' => t("Body of the email goes here"),
);
drupal_mail("samplemail", "samplemail_html_mail", "email#email.com", language_default(), $params, "email#email.com", TRUE);
I have even tried it with the hook below and I get the same result.
function hook_mail($key, &$message, $params) {
switch ($key) {
case 'samplemail_html_mail':
/*
* Emails with this key will be HTML emails,
* we therefore cannot use drupal default headers, but set our own headers
*/
/*
* $vars required even if not used to get $language in there since t takes in: t($string, $args = array(), $langcode = NULL) */
$message['subject'] = t($params['subject'], $var, $language->language);
/* the email body is here, inside the $message array */
$body = "<html><body>
<h2>HTML Email Sample with Drupal</h2>
<hr /><br /><br />
{$params['body']}
</body></html>";
$message['body'][] = $body;
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
break;
}
}
drupal_mail_system() works but it comes in plain text.
in your module you shouldn't use hook_mail it should be <MODULE_NAME>_hook().
change
function hook_mail($key, &$message, $params) {
With
function samplemail_mail($key, &$message, $params) {
Try using the following snippet.
// Use these two lines when you want to send a mail.
global $user;
drupal_mail('test', 'test_mail', 'your_mail_id', user_preferred_language($user), $params, $from_mail_id, TRUE);
/**
* Implements hook_mail().
*/
function test_mail($key, &$message, $params) {
switch ($key) {
case 'test_mail':
$params['subject'] = t('Subject is here');
$params['message'] = 'message is here';
$message['subject'] = $params['subject'];
$message['body'][] = $params['message'];
break;
}
}
Note: 'test' is module name.
Solution !
Try with below code in your "registration_form" module. This code will send mail often on page refresh since mail trigger is done in hook_init. Use where ever you want.
/**
* Implements hook_init();
*/
function registration_form_init() {
$first_name = 'Shankar';
$params = array(
'subject' => 'Signup Invitation',
'body' => '<p>Dear ' . $first_name . ',</p>
<p>Congratulations! Your account <b> ' . $first_name . ' </b>has been successfully created with SOME portal.</p>
<p>Thanks,SOME portal POSTMASTER</p>',
'first_name' => $first_name
);
drupal_mail('registration_form', 'invitation', $email, language_default(), $params);
}
/**
* Implements hook_mail();
*/
function registration_form_mail($key, &$message, $params) {
switch ($key) {
case 'invitation':
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}

Change User Avatar Programmatically in Wordpress

Is it possible to change the user avatar in WordPress programmatically? I'm asking because I'm facing a problem right now in displaying the user avatar in WordPress multisite: the Avatar is not displaying.
I had to do three things to be able to programmatically insert user avatars into my WordPress starting with an avatar that is hosted at a remote URL.
Install the WP User Avatar plugin.
Borrow an upload function from WooCommerce. See below.
Adapt some code from a similar support post
Suppose you have a user whose avatar is $avatar_url = 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded&a';
I use the upload_product_image() from WooCommerce's class-wc-api-products.php to get the avatar into my local server.
Then, using some of the code from this support post, create an attachment.
Then associate the attachment with the user.
This works only with the WP User Avatar plugin.
function se13911452_set_avatar_url($avatar_url, $user_id) {
global $wpdb;
$file = upload_product_image($avatar_url);
$wp_filetype = wp_check_filetype($file['file']);
$attachment = array(
'guid' => $file['url'],
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($file['file'])),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file['file']);
$attach_data = wp_generate_attachment_metadata($attach_id, $file['file']);
wp_update_attachment_metadata($attach_id, $attach_data);
update_user_meta($user_id, $wpdb->get_blog_prefix() . 'user_avatar', $attach_id);
}
From WooCommerce's class-wc-api-products.php
/**
* WooCommerce class-wc-api-products.php
* See https://github.com/justinshreve/woocommerce/blob/master/includes/api/class-wc-api-products.php
* Upload image from URL
*
* #since 2.2
* #param string $image_url
* #return int|WP_Error attachment id
*/
function upload_product_image($image_url) {
$file_name = basename(current(explode('?', $image_url)));
$wp_filetype = wp_check_filetype($file_name, null);
$parsed_url = #parse_url($image_url);
// Check parsed URL
if(!$parsed_url || !is_array($parsed_url)) {
throw new WC_API_Exception('woocommerce_api_invalid_product_image', sprintf(__('Invalid URL %s', 'woocommerce'), $image_url), 400);
}
// Ensure url is valid
$image_url = str_replace(' ', '%20', $image_url);
// Get the file
$response = wp_safe_remote_get($image_url, array(
'timeout' => 10
));
if(is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
throw new WC_API_Exception('woocommerce_api_invalid_remote_product_image', sprintf(__('Error getting remote image %s', 'woocommerce'), $image_url), 400);
}
// Ensure we have a file name and type
if(!$wp_filetype['type']) {
$headers = wp_remote_retrieve_headers($response);
if(isset($headers['content-disposition']) && strstr($headers['content-disposition'], 'filename=')) {
$disposition = end(explode('filename=', $headers['content-disposition']));
$disposition = sanitize_file_name($disposition);
$file_name = $disposition;
}
elseif(isset($headers['content-type']) && strstr($headers['content-type'], 'image/')) {
$file_name = 'image.' . str_replace('image/', '', $headers['content-type']);
}
unset($headers);
}
// Upload the file
$upload = wp_upload_bits($file_name, '', wp_remote_retrieve_body($response));
if($upload['error']) {
throw new WC_API_Exception('woocommerce_api_product_image_upload_error', $upload['error'], 400);
}
// Get filesize
$filesize = filesize($upload['file']);
if(0 == $filesize) {
#unlink($upload['file']);
unset($upload);
throw new WC_API_Exception('woocommerce_api_product_image_upload_file_error', __('Zero size file downloaded', 'woocommerce'), 400);
}
unset($response);
return $upload;
}
Most likely somewhere the get_avatar filter is being called and doing something. I recommend searching your plugins and themes for get_avatar and looking at things that look like: add_filter ('get_avatar', .....
Otherwise, you can write your own behavior with the code below.
<?php // in a plugin file or in a theme functions.php
function SO13911452_override_avatar ($avatar_html, $id_or_email, $size, $default, $alt) {
// check all values
return $avatar_html
}
add_filter ('get_avatar', 'SO13911452_override_avatar', 10, 5);
This will works :
add_filter('get_avatar_data', 'ht1_change_avatar', 100, 2);
function ht1_change_avatar($args, $id_or_email) {
if($id_or_email == 1) {
$args['url'] = 'https://uinames.com/api/photos/female/1.jpg';
}
if($id_or_email == 2) {
$args['url'] = 'https://uinames.com/api/photos/male/19.jpg';
}
return $args;
} // end of function
If you have avatar dir location metas for users, then use this for all users :
add_filter('get_avatar_data', 'ht1_change_avatar', 100, 2);
function ht1_change_avatar($args, $id_or_email) {
$avatar_url = get_user_meta($id_or_email, 'avatar', true);
$args['url'] = $avatar_url;
return $args;
} // end of function
Hope you get the point.
first add author_pic meta to user profile:
update_usermeta( $user_id, 'author_pic', trim($_POST['author_pic']) );
and add this filter to template function:
add_filter('get_avatar_data', 'ow_change_avatar', 100, 2);
function ow_change_avatar($args, $user_data) {
if(is_object($user_data)){
$user_id = $user_data->user_id;
} else{
$user_id = $user_data;
}
if($user_id){
$author_pic = get_user_meta($user_id, 'author_pic', true);
if($author_pic){
$args['url'] = $author_pic;
} else {
$args['url'] = 'registerd user default img url';
}
} else {
$args['url'] = 'guast user img url';
}
return $args;
}

Resources