Create Wordpress user when new custom post created - wordpress

I want to create custom posts from frontend and backend. And while I create posts I want to create users. At frontend I use form and wp_insert_post so it creates post as I need. At backend I use this code:
add_action( 'publish_user_contact', 'custom_post_user_create', 1, 3);
function custom_post_user_create($post_id){
$user_login_id = 'user_'.random_int(100000, 999999);
update_post_meta($post_id, 'idr_contact_user_id', $user_login_id);
$password = wp_generate_password( 10, true, true );
if (!empty($_POST['contact_email'])){
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'user_email' => $_POST['contact_email'],
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
} else {
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
}
$user_id = wp_insert_user( $userdata );
}
It creates user with custom post nut when I try to edit posts it creates more users. I tried to use new_to_publish, but it doesn't work (users don't creates). I tried to use save_post but it makes duplicates too.
How to prevent duplicates?

Try adding a check for the custom field, then the code won't be executed when editing a post.
add_action( 'publish_user_contact', 'custom_post_user_create', 1, 3);
function custom_post_user_create($post_id){
$user_login_id = 'user_'.random_int(100000, 999999);
if(get_post_meta($post_id, "idr_contact_user_id", true) ) {
return;
}
update_post_meta($post_id, 'idr_contact_user_id', $user_login_id);
$password = wp_generate_password( 10, true, true );
if (!empty($_POST['contact_email'])){
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'user_email' => $_POST['contact_email'],
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
} else {
$userdata = [
'user_login' => "$user_login_id",
'user_pass' => "$password",
'display_name' => sanitize_text_field( $_POST['contact_first_name'] .' '. $_POST['contact_last_name'] ),
'first_name' => sanitize_text_field( $_POST['contact_first_name'] ),
'last_name' => sanitize_text_field( $_POST['contact_last_name'] )
];
}
$user_id = wp_insert_user( $userdata );
}

Related

WORDPRESS : Remove from the urls the prefix /custom-post-name/ in all my articles AND THEIR TRANSLATIONS made with Polylang

My theme was tailor-made by a developper.
All my (single-post) articles are custom posts.
By default the url of a custom post is : https://www.example.com/custom-post-name/slug
For very good reasons this prefix /custom-post-name/ had to be removed.
The developper of my theme achieved that by editing some code in the file declaring the custom post which is this one : wp-content/themes/mytheme/inc/custom-post-types.php
The custom-post-name as registered in this file is "article"
register_post_type( "article", $args );
I believe the part of code removing the prefix /custom-post-name/ from the urls is :
function gp_remove_cpt_slug( $post_link, $post, $leavename ) {
if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'gp_remove_cpt_slug', 10, 3 );
It has worked fine until now that I want to translate my website.
The translated articles get this url :
https://www.example.com/en/slug
The result is a 404 error
If I add (by hand) in the url the prefix custom-post-name that way :
https://www.example.com/en/custom-post-name/slug
Then it works.
What I need is to get completely rid of this prefix for my custom-post-type registered with the name "article". In the default language AND IN THE TRANSLATED versions made with the plugin Polylang
The complete code of my file wp-content/themes/mytheme/inc/custom-post-types.php is this :
<?php
function cptui_register_my_cpts_module() {
$labels = array(
"name" => __( "Modules", "" ),
"singular_name" => __( "Module", "" ),
);
$args = array(
"label" => __( "Modules", "" ),
"labels" => $labels,
"description" => "",
"public" => false,
"publicly_queryable" => false,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => true,
"capability_type" => "page",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "module", "with_front" => true ),
"query_var" => true,
"menu_icon" => "dashicons-schedule",
"supports" => array( "title", "page-attributes" ),
);
register_post_type( "module", $args );
$labels = array(
"name" => __( "Articles", "" ),
"singular_name" => __( "Article", "" ),
);
$args = array(
"label" => __( "Articles", "" ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "page",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "article", "with_front" => true ),
"query_var" => true,
//"menu_icon" => "dashicons-schedule",
"menu_position" => 5,
"supports" => array( "title", "page-attributes", "comments", "editor" ),
"taxonomies" => array( "categorie" ),
);
register_post_type( "article", $args );
}
add_action( 'init', 'cptui_register_my_cpts_module' );
function cptui_register_my_taxes_categorie() {
/**
* Taxonomy: Catégories.
*/
$labels = array(
"name" => __( "Catégories", "" ),
"singular_name" => __( "Catégorie", "" ),
);
$args = array(
"label" => __( "Catégories", "" ),
"labels" => $labels,
"public" => true,
"hierarchical" => true,
"label" => "Catégories",
"show_ui" => true,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"query_var" => true,
"rewrite" => array( 'slug' => 'categorie', 'with_front' => true, ),
"show_admin_column" => true,
"show_in_rest" => false,
"rest_base" => "",
"show_in_quick_edit" => true,
);
register_taxonomy( "categorie", array( "article" ), $args );
}
add_action( 'init', 'cptui_register_my_taxes_categorie' );
function gp_remove_cpt_slug( $post_link, $post, $leavename ) {
if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'gp_remove_cpt_slug', 10, 3 );
function gp_add_cpt_post_names_to_main_query( $query ) {
// Bail if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Bail if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Bail if we're not querying based on the post name.
if ( empty( $query->query['name'] ) ) {
return;
}
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', array( 'post', 'page', 'article' ) );
}
add_action( 'pre_get_posts', 'gp_add_cpt_post_names_to_main_query' );
add_filter('request', 'rudr_change_term_request', 1, 1 );
function rudr_change_term_request($query){
$tax_name = 'categorie'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
// Request for child terms differs, we should make an additional check
if( $query['attachment'] ) :
$include_children = true;
$name = $query['attachment'];
else:
$include_children = false;
$name = $query['name'];
endif;
$term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
if (isset($name) && $term && !is_wp_error($term)): // check it here
if( $include_children ) {
unset($query['attachment']);
$parent = $term->parent;
while( $parent ) {
$parent_term = get_term( $parent, $tax_name);
$name = $parent_term->slug . '/' . $name;
$parent = $parent_term->parent;
}
} else {
unset($query['name']);
}
switch( $tax_name ):
/* case 'category':{
$query['category_name'] = $name; // for categories
break;
}
case 'post_tag':{
$query['tag'] = $name; // for post tags
break;
}*/
default:{
$query[$tax_name] = $name; // for another taxonomies
break;
}
endswitch;
endif;
return $query;
}
add_filter( 'term_link', 'rudr_term_permalink', 10, 3 );
function rudr_term_permalink( $url, $term, $taxonomy ){
$taxonomy_name = 'categorie'; // your taxonomy name here
$taxonomy_slug = 'categorie'; // the taxonomy slug can be different with the taxonomy name (like 'post_tag' and 'tag' )
// exit the function if taxonomy slug is not in URL
if ( strpos($url, $taxonomy_slug) === FALSE || $taxonomy != $taxonomy_name ) return $url;
$url = str_replace('/' . $taxonomy_slug, '', $url);
return $url;
}
?>
Thanks a lot for reading and any help,
François

ACF. How to update repeater field with files?

I am trying to update my repeater field from front end-with files. In case with one field file - it works. But when I'm trying to fill repeater with files it doesn't work.
// JS. Ajaxly sending files
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
$('.js-new-msg-send').click(function (e) {
e.preventDefault();
var form = document.forms.namedItem("new_theme");
var formData = new FormData(form);
formData.append('user_id', '<?php echo $userID; ?>');
formData.append('action', 'msg_to_acf');
var xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl, true);
xhr.send(formData);
})
I found function to handle files uploading to acf field and modified it to handle multiple files from $_FILES variable:
// FOR MULTIPLE FILES
if ( !empty($_FILES[$f]['name']) && is_array($_FILES[$f]['name']) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$file_list = array();
foreach ($_FILES[$f]['name'] as $key => $value) {
$temp_file = array(
'name' => $_FILES[$f]['name'][$key],
'type' => $_FILES[$f]['type'][$key],
'tmp_name' => $_FILES[$f]['tmp_name'][$key],
'error' => $_FILES[$f]['error'][$key],
'size' => $_FILES[$f]['size'][$key]
);
wp_update_attachment_metadata( $pid, $temp_file );
$file = wp_handle_upload( $temp_file , array('test_form' => FALSE, 'action' => 'editpost') );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($temp_file['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if ($file_type['type']) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $t ? $t : $name;
$content = $c;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $pid,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
$final_temp_arr = array(
'pid' =>$pid,
'url' =>$file['url'],
'file'=>$file,
'attach_id'=>$attach_id
);
array_push($file_list, $final_temp_arr);
}
}
return $file_list;
}
In final, I using this function to get an array of information with attach-id variable that I inserting to repeater.
$att = my_update_attachment( 'msg-file-list' , $post_id );
$files_final_list = array();
foreach ($att as $key => $val) {
array_push($files_final_list, $val['attach_id']);
}
$value_arr = array(
array(
"msg-author" => $user_name,
"msg-date" => $date,
"msg-read-check" => true,
"msg-cont" => $msg_cont,
'msg-file-list' => $files_final_list
)
);
update_field( 'test_file_list' , $files_final_list , $post_id );
I guess that mistake is in last part , where I trying to upload files to repeater. Can someone show me what I'am doing wrong? Thanks for helping.

Adding Post Category In Custom Metaboxes of wordpress

I want to load my post category in the drop-down select box
how I do this
help me please I am new to programming:
this is my code that creates the custom meta boxes and now in the category boxenter image description here, I want that it loads all the category of post in the drop-down menu: the output of the code is shown in the image attached
<?php
//Start: Adding custom metaboxes
class leaderboarddetailMetabox {
private $screen = array(
'ld-leaderboard',
);
private $meta_fields = array(
array(
'label' => 'Number of Students',
'id' => 'numberofstudent_81418',
'type' => 'number',
),
array(
'label' => 'Select Point Type',
'id' => 'selectpointtype_39141',
'type' => 'select',
'options' => array(
'Select',
'Int',
'Float',
'String',
),
),
array(
'label' => 'Category',
'id' => 'category_59112',
'type' => 'select',
'options' => array(
'Select',
'Course',
'Lesson',
'Topic',
'Quiz',
'Category',
),
),
array(
'label' => 'Time',
'id' => 'time_93126',
'type' => 'date',
),
array(
'label' => 'Shortcode',
'id' => 'shortcode_85946',
'type' => 'text',
'readonly' => true,
),
);
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'save_post', array( $this, 'save_fields' ) );
}
// show meta boxes on admin page
public function add_meta_boxes() {
foreach ( $this->screen as $single_screen ) {
add_meta_box(
'leaderboarddetail',
__( 'leader board detail', 'textdomain' ),
array( $this, 'meta_box_callback' ),
$single_screen,
'advanced',
'default'
);
}
}
public function meta_box_callback( $post ) {
wp_nonce_field( 'leaderboarddetail_data', 'leaderboarddetail_nonce' );
$this->field_generator( $post );
}
public function field_generator( $post ) {
$output = '';
foreach ( $this->meta_fields as $meta_field ) {
$label = '<label for="' . $meta_field['id'] . '">' . $meta_field['label'] . '</label>';
$meta_value = get_post_meta( $post->ID, $meta_field['id'], true );
if ( empty( $meta_value ) ) {
$meta_value = $meta_field['default']; }
switch ( $meta_field['type'] ) {
case 'select':
$input = sprintf(
'<select id="%s" name="%s">',
$meta_field['id'],
$meta_field['id']
);
foreach ( $meta_field['options'] as $key => $value ) {
$meta_field_value = !is_numeric( $key ) ? $key : $value;
$input .= sprintf(
'<option %s value="%s">%s</option>',
$meta_value === $meta_field_value ? 'selected' : '',
$meta_field_value,
$value
);
}
$input .= '</select>';
break;
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s" %s >',
$meta_field['type'] !== 'color' ? 'style="width: 100%"' : '',
$meta_field['id'],
$meta_field['id'],
$meta_field['type'],
$meta_value,
$meta_field['readonly'] ? "readonly" : ""
);
}
$output .= $this->format_rows( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
public function format_rows( $label, $input ) {
return '<tr><th>'.$label.'</th><td>'.$input.'</td></tr>';
}
// save custom field data to databse and in the field
public function save_fields( $post_id ) {
if ( ! isset( $_POST['leaderboarddetail_nonce'] ) )
return $post_id;
$nonce = $_POST['leaderboarddetail_nonce'];
if ( !wp_verify_nonce( $nonce, 'leaderboarddetail_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->meta_fields as $meta_field ) {
if ( isset( $_POST[ $meta_field['id'] ] ) ) {
switch ( $meta_field['type'] ) {
case 'email':
$_POST[ $meta_field['id'] ] = sanitize_email( $_POST[ $meta_field['id'] ] );
break;
case 'text':
$_POST[ $meta_field['id'] ] = sanitize_text_field( $_POST[ $meta_field['id'] ] );
break;
}
update_post_meta( $post_id, $meta_field['id'], $_POST[ $meta_field['id'] ] );
} else if ( $meta_field['type'] === 'checkbox' ) {
update_post_meta( $post_id, $meta_field['id'], '0' );
}
// generate shortcode and save
if( $meta_field['id'] == 'shortcode_85946' ) {
// update meta
update_post_meta( $post_id, $meta_field['id'], "[custom-shortcode id=" . $post_id . "]");
}
}
}
}
if (class_exists('leaderboarddetailMetabox')) {
new leaderboarddetailMetabox;
};
?>

Wp custom plugins meta filed box are not visible

I have created a plugins about to save Authorz data using wordpress custom fields and meta box. The Plugins has no errors and running but the Meta boxes are not showing.
The plugins is running and i have attached the screenshot.
http://i63.tinypic.com/2czebyh.png
Below is my plugin code
<?php
/*Plugin Name: CNSLounge
Description: This plugin registers the 'Authors CNSLounge' post type.
Version: 1.0
Author: Anita Mandal
Author URI: http://cosmoread.com/
License: GPLv2
*/
// Register Custom Post Type
function CNSLounge() {
register_post_type('CNSLounge', array(
'labels' => array(
'name' => 'Authorz',
'singular_name' => 'Authorz',
'add_new' => 'Add New',
'add_new_item' => 'Add New Authorz',
'edit' => 'Edit',
'edit_item' => 'Edit Authorz',
'new_item' => 'New Authorz',
'view' => 'View',
'view_item' => 'View Authorz',
'search_items' => 'Search Authorz',
'not_found' => 'No Authorz found',
'not_found_in_trash' => 'No Authorz found in Trash',
'parent' => 'Parent Authorz'
),
'public' => true,
'menu_position' => 15,
'supports' => array(
'title',
'editor',
'comments',
'thumbnail'
),
'taxonomies' => array(
''
),
'menu_icon' => plugins_url('images/image.png', __FILE__),
'has_archive' => true
));
register_post_type( 'post_type', $args );
}
add_action( 'init', 'CNSLounge', 0 );
class Rational_Meta_Box {
private $screens = array(
'post',
);
private $fields = array(
array(
'id' => 'authorz-name',
'label' => 'Authorz Name',
'type' => 'text',
),
array(
'id' => 'author-photo',
'label' => 'Author Photo',
'type' => 'media',
),
array(
'id' => 'active-since',
'label' => 'Active Since',
'type' => 'date',
),
array(
'id' => 'languages-expression',
'label' => 'Languages Expression',
'type' => 'text',
),
array(
'id' => 'now-based-at',
'label' => 'Now Based at',
'type' => 'text',
),
array(
'id' => 'location-of-author',
'label' => 'Location of Author',
'type' => 'text',
),
array(
'id' => 'mostly-writes',
'label' => 'Mostly Writes',
'type' => 'text',
),
array(
'id' => 'about-author',
'label' => 'About Author',
'type' => 'textarea',
),
array(
'id' => 'magazines',
'label' => 'Magazines',
'type' => 'media',
),
array(
'id' => 'publication',
'label' => 'Publication',
'type' => 'media',
),
array(
'id' => 'gallery',
'label' => 'Gallery',
'type' => 'media',
),
array(
'id' => 'author-s-website',
'label' => 'Author\'s Website',
'type' => 'url',
),
array(
'id' => 'author-s-email',
'label' => 'Author\'s Email',
'type' => 'email',
),
array(
'id' => 'author-s-phone',
'label' => 'Author\'s Phone',
'type' => 'number',
),
);
/**
* Class construct method. Adds actions to their respective WordPress hooks.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'admin_footer', array( $this, 'admin_footer' ) );
add_action( 'save_post', array( $this, 'save_post' ) );
}
/**
* Hooks into WordPress' add_meta_boxes function.
* Goes through screens (post types) and adds the meta box.
*/
public function add_meta_boxes() {
foreach ( $this->screens as $screen ) {
add_meta_box(
'cnslounge',
__( 'CNSLounge', 'rational-metabox' ),
array( $this, 'add_meta_box_callback' ),
$screen,
'advanced',
'default'
);
}
}
/**
* Generates the HTML for the meta box
*
* #param object $post WordPress post object
*/
public function add_meta_box_callback( $post ) {
wp_nonce_field( 'cnslounge_data', 'cnslounge_nonce' );
echo 'CNSLounge Author Meta Information';
$this->generate_fields( $post );
}
/**
* Hooks into WordPress' admin_footer function.
* Adds scripts for media uploader.
*/
public function admin_footer() {
?><script>
// https://codestag.com/how-to-use-wordpress-3-5-media-uploader-in-theme-options/
jQuery(document).ready(function($){
if ( typeof wp.media !== 'undefined' ) {
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
$('.rational-metabox-media').click(function(e) {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
var id = button.attr('id').replace('_button', '');
_custom_media = true;
wp.media.editor.send.attachment = function(props, attachment){
if ( _custom_media ) {
$("#"+id).val(attachment.url);
} else {
return _orig_send_attachment.apply( this, [props, attachment] );
};
}
wp.media.editor.open(button);
return false;
});
$('.add_media').on('click', function(){
_custom_media = false;
});
}
});
</script><?php
}
/**
* Generates the field's HTML for the meta box.
*/
public function generate_fields( $post ) {
$output = '';
foreach ( $this->fields as $field ) {
$label = '<label for="' . $field['id'] . '">' . $field['label'] . '</label>';
$db_value = get_post_meta( $post->ID, 'advanced_options_' . $field['id'], true );
switch ( $field['type'] ) {
case 'media':
$input = sprintf(
'<input class="regular-text" id="%s" name="%s" type="text" value="%s"> <input class="button rational-metabox-media" id="%s_button" name="%s_button" type="button" value="Upload" />',
$field['id'],
$field['id'],
$db_value,
$field['id'],
$field['id']
);
break;
case 'textarea':
$input = sprintf(
'<textarea class="large-text" id="%s" name="%s" rows="5">%s</textarea>',
$field['id'],
$field['id'],
$db_value
);
break;
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s">',
$field['type'] !== 'color' ? 'class="regular-text"' : '',
$field['id'],
$field['id'],
$field['type'],
$db_value
);
}
$output .= $this->row_format( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
/**
* Generates the HTML for table rows.
*/
public function row_format( $label, $input ) {
return sprintf(
'<tr><th scope="row">%s</th><td>%s</td></tr>',
$label,
$input
);
}
/**
* Hooks into WordPress' save_post function
*/
public function save_post( $post_id ) {
if ( ! isset( $_POST['cnslounge_nonce'] ) )
return $post_id;
$nonce = $_POST['cnslounge_nonce'];
if ( !wp_verify_nonce( $nonce, 'cnslounge_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->fields as $field ) {
if ( isset( $_POST[ $field['id'] ] ) ) {
switch ( $field['type'] ) {
case 'email':
$_POST[ $field['id'] ] = sanitize_email( $_POST[ $field['id'] ] );
break;
case 'text':
$_POST[ $field['id'] ] = sanitize_text_field( $_POST[ $field['id'] ] );
break;
}
update_post_meta( $post_id, 'cnslounge_' . $field['id'], $_POST[ $field['id'] ] );
} else if ( $field['type'] === 'checkbox' ) {
update_post_meta( $post_id, 'cnslounge_' . $field['id'], '0' );
}
}
}
}
new Rational_Meta_Box;
?>
private $screens = array(
'post',
);
So, you are adding the metaboxes to post, not to your custom post type.
Use your custom post type slug here. just like
private $screens = array(
'CNSLounge',
);

WooCommerce Custom Payment Gateway

I am trying to make a Custom Gateway Plugin for my Merchant Account but I got stuck and I don't know how to continue.
Now, here is what I done so far:
<?php
/*
Plugin Name: Paysecure.ro Payment Gateway
Plugin URI: http://www.Paysecure.ro
Description: Allows you to use Paysecure.ro Payment Gateway with the WooCommerce plugin.
Version: 0.0.1
Author: Andrei Raileanu
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action('plugins_loaded', 'woocommerce_Paysecure', 0);
function woocommerce_Paysecure(){
if (!class_exists('WC_Payment_Gateway'))
return; // if the WC payment gateway class is not available, do nothing
if(class_exists('WC_Paysecure'))
return;
class WC_Gateway_Paysecure extends WC_Payment_Gateway{
public function __construct(){
$plugin_dir = plugin_dir_url(__FILE__);
global $woocommerce;
$this->id = 'Paysecure';
$this->icon = apply_filters('woocommerce_Paysecure_icon', ''.$plugin_dir.'Paysecure.png');
$this->has_fields = true;
// Load the settings
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = "Credit/Debit Card";
$this->description = "You will be redirected to paysecure.ro to complete your purchase.";
$this->cui = "XXXXXXXXX";
$this->encryption_key = "XXXXXXXXX";
$this->currency = "USD";
// Logs
if ($this->debug == 'yes'){
$this->log = $woocommerce->logger();
}
// Actions
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
// Save options
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// Payment listener/API hook
add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_ipn_response'));
}
function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable Paysecure', 'woocommerce' ),
'default' => 'yes'
)
);
}
public function admin_options() {
?>
<h3><?php _e( 'Paysecure', 'woocommerce' ); ?></h3>
<p><?php _e( 'Paysecure Payment Gateway', 'woocommerce' ); ?></p>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table>
<?php
}
function payment_fields() {
$plugin_dir = plugin_dir_url(__FILE__);
// Description of payment method from settings
if ($this->description) { ?>
<p><?php
echo $this->description; ?>
</p><?php
} ?>
<?php
}
function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order($order_id);
// I WILL NEED THESE FIELDS
//$this->notify_url;
//$order->get_total();
//$order->get_order_number();
//$order->billing_first_name;
//$order->billing_email;
}
}
function add_Paysecure_gateway($methods){
$methods[] = 'WC_Gateway_Paysecure';
return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_Paysecure_gateway');
}
Here are the PHP instructions from my merchant account provider:
<?php
require_once('./functions.php');
$key = 'THIS IS THE ENCRYPTION KEY';
$data = array( 'cui' => 'THIS IS THE CUI CODE',
'AMOUNT' => '200',
'CURRENCY' => 'USD',
'ORDER' => '12313',
'DESC' => ps_clean('SHORT DESCRIPTION'),
'PENTRU' => 'EMAIL ADDRESS',
'TRTYPE' => 0,
'BACKREF' => 'http://www.site.ro/test.php',
'TIMESTAMP'=>time()
);
echo '<form action="https://paysecure.ro/order/cgi-bin/" method="post" >';
foreach ($data as $l => $v ) echo '<input size="55" readonly type="text" name="'.$l.'" value="'.$v.'" /> : <label for="'.$l.'">'.$l.'</label><br>';
echo '<input size="55" type="text" name="P_SIGN" readonly value="'.calculateSign($data,$key).'" /><br>' ; //se calculeaza P_SIGN - ul , encriptarea datelor
?>
<input type="submit" />
</form>
Can someone help me with the rest of the code?
1st mistake I noticed you made, $this->id MUST be in lowercase. 'Paysecure' is not gonna work here come time for the API hook.
// Payment listener/API hook
add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_ipn_response'));
change to this instead:
// Payment listener/API hook
add_action('woocommerce_api_wc_paysecure', array($this, 'check_ipn_response'));
2nd mistake is that you forgot to create the function check_ipn_response()
// Handles the callbacks received from the payment backend. give this url to your payment processing comapny as the ipn response URL:
// USAGE: http://myurl.com/?wc-api=WC_Gateway_Paysecure
function check_ipn_response() {
$http_contents = file_get_contents("php://input");
$json = json_decode($http_contents, true);
$order = new WC_Order($json['custom']);
if ($callback_json['status'] == 'Transaction approved')
{
$order->payment_complete(); //This will ensure stock reductions are made, and the status is changed to the correct value.
$order->add_order_note( __( 'KiwiPay Transaction Approved.', 'kiwipay' ) );
}
else
{
$order->update_status('failed');
$order->add_order_note('KiwiPay status received - ' . $callback_json['status']);
}
//references:
//http://docs.woothemes.com/document/payment-gateway-api/
//https://github.com/Paymium/WooCommerce/blob/master/checkout.php
//https://github.com/tubiz/voguepay-woocommerce-payment-gateway/blob/master/voguepay-woocommerce-payment-gateway.php
/*
{
"id":1863,
"amount":1750,
"status":"Transaction approved",
"created":1434198776,
"reference":"2626", //this is the order number $order->get_order_number()
"name":"HamishTest Test",
"email":"hamish#tst.xom",
"address":{"street":"my rd","region":"N/A","city":"tauranga","zip":"3175","country":"NZ"},
"test":true,
"price":"17.50",
"custom":"6589" //this is the wc order_id passed during process_payment to the paymen processor.
}
*/
How about this?
add_action( 'plugins_loaded', 'init_gateway_cash' );
function init_gateway_cash() {
class WC_Gateway_Cash extends WC_Payment_Gateway {
function __construct() {
$this->id = "Cash Gateway";
$this->title = "Cash";
$this->description = "More later";
$this->init_form_fields();
$this->init_settings();
add_action( 'woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ) );
}
function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable Cheque Payment', 'woocommerce' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title', 'woocommerce' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ),
'default' => __( 'Cheque Payment', 'woocommerce' ),
'desc_tip' => true,
),
'description' => array(
'title' => __( 'Customer Message', 'woocommerce' ),
'type' => 'textarea',
'default' => ''
)
);
}
function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
$productArray = array();
$x = 0;
foreach( $order->get_items() as $item_id => $item ) {
$productArray[$x] = $order->get_product_from_item( $item );
$x++;
}
// Mark as on-hold (we're awaiting the cheque)
$order->update_status('on-hold',
__( 'Awaiting cheque payment.', 'woocommerce' )
);
// Remove cart
$woocommerce->cart->empty_cart();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
}
}
function add_gateway_cash_class ($methods ) {
$methods[] = 'WC_Gateway_Cash';
return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'add_gateway_cash_class' );

Resources