User ID remove # and transform "." into "-" - php

I have this function in order to set a link for my user to go to their custom profile page :
add_shortcode( 'current_user_link', 'wppbc_current_user_link' );
function wppbc_current_user_link( $atts, $content ) {
if ( is_user_logged_in() )
{
$current_user = wp_get_current_user();
$id = $current_user->user_login;
return "<a class='lienprofils' href='https://mywebsite/author/{$id}'><i class='fas fa-user' aria-hidden='true'></i> MON PROFIL</a>"; }
return ;
}
The issue is that if the user ID is his email like john#example.com the link https://mywebsite/author/john#example.com will have an 403 error. But if the is the link is https://mywebsite/author/johnexample-com it works.
So is there a way to clean the user ID into my function in order to remove # and transform "." into "-" ?
Best regards,
Clément

Try this
$id = $current_user->user_login;
//Remove #
$id = str_replace('#', '', $id);
// Replace . with -
$id = str_replace('.', '-', $id);

Related

Wordpress how to hide user role tab from users list

I have already hidden the admin user from the list and subtracted the users number, however, the administrator role tab from the users list ( Users >> All Users ), is still shown, and I would like to hide this as will.
This is the code I used to hide admin:
add_action('pre_user_query','site_pre_user_query');
function site_pre_user_query($user_search) {
global $current_user;
$username = $current_user->user_login;
if ($username == 'admin') {
}
else {
global $wpdb;
$user_search->query_where = str_replace('WHERE 1=1',
"WHERE 1=1 AND {$wpdb->users}.user_login != 'admin'",$user_search->query_where);
}
}
And this is what I used to subtract the users numbers:
add_filter("views_users", "site_list_table_views");
function site_list_table_views($views){
$users = count_users();
$admins_num = $users['avail_roles']['administrator'] - 1;
$all_num = $users['total_users'] - 1;
$class_adm = ( strpos($views['administrator'], 'current') === false ) ? "" : "current";
$class_all = ( strpos($views['all'], 'current') === false ) ? "" : "current";
$views['administrator'] = '' . translate_user_role('Administrator') . ' <span class="count">(' . $admins_num . ')</span>';
$views['all'] = '' . __('All') . ' <span class="count">(' . $all_num . ')</span>';
return $views;
}
Thanks
"I am not trying to hide the user, am trying hide the ( Administration ) tab on the users list"
You could use unset function and views_users filter hook to remove the "administrator role tab".
add_filter("views_users", "removing_admin_tab_from_users_list");
function removing_admin_tab_from_users_list($views)
{
unset($views['administrator']);
return $views;
}
And here's the result:

How to get variable from functions.php to page

I'm trying to get $cert_url and use it in my custom page to create a sharable link to Facebook. However, I have no idea to get the variable functions.php and pass it to custom page.
Functions.php
add_action( 'woocommerce_thankyou', 'get_cert_url' );
function get_cert_url( $order_id ) {
global $wpdb;
$msf_campaign_status = array('wc-completed');
$msf_campaign_detail = get_post_meta($order_id);
$msf_campaign_fund = $msf_campaign_detail['msf_charity_fund'][0];
$order = wc_get_order( $order_id );
if( $order->has_status('processing') ){
$name_on_e_cert = str_replace(" ", "+", $msf_campaign_detail['name_on_e_cert'][0]);
$msf_charity_name = get_option('wc_fields_billing');
if($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_1'){
$charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_1'];
}
elseif ($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_2') {
$charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_2'];
}
elseif ($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_3') {
$charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_3'];
}
elseif ($msf_campaign_detail['charity_organizations'][0] == 'msf_charity_4') {
$charity_name = $msf_charity_name['charity_organizations']['options']['msf_charity_4'];
}
$donateto = str_replace(" ", "+", $charity_name);
$subtotal = $order->get_subtotal();
$amount = (($subtotal*25)/100);
$request = wp_remote_retrieve_body(wp_remote_get('https://www.api_website.com.my/api/c/product.ashx?key=api_key&orderid='.$order_id.'&name='.$name_on_e_cert.'&donateto='.$donateto.'&amount='.$amount.''));
$data = json_decode($request);
$result[]= $data;
foreach($result[0] as $line) {
$cert_url = $line;
}
return $cert_url;
}
}
The code below is to create a share button to share the link to Facebook.
Custom page
Share this on Facebook
May I know how can I get the $cert_url and use it on custom page? Thanks in advance !
Thank you for your answer. I solved the problem by using add_query_arg().

Add result of php function to WP database

I have the following function to create a member_id:
add_action('user_register', 'generate_member_id');
function generate_member_id($user_id){
$unique_id = 1000 + get_current_user_id();
$chapter_id = fetch_chapter();
$member_id = "FAL-" . $chapter_id . "-" . $unique_id;
return $member_id;
}
It appears to work fine and I can call the function from a shortcode and get the correct value.
Now I want to add the returned value to a database and have tried using
update_user_meta()
$wpdb->update
$wpdb->insert
$wpdb->query
all with necessary arguments but nothing seems to work.
I expected this to do it, but it just generates a generic error that I am not able to debug (I have a problem with error logging):
global $wpdb;
$users = $wpdb->get_results( "SELECT ID FROM $wpdb->users" );
$generated_id = generate_member_id()
if( $users ) {
foreach ( $users as $user ) {
update_user_meta( $user->ID, 'member_id', generate_member_id() );
}
}
However if I change generate_member_id() to a string like 'memberId', it works and the database is updated. So I don't know what I'm doing wrong. Why can't I add' the result of the generate_member_id() function and to a WP database?
EDIT
add_action('user_register', 'fetch_chapter');
function fetch_chapter(){
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
global $wpdb;
$result = $wpdb->get_results('SELECT meta_value FROM usermeta WHERE meta_key = \'chapter_name\' AND user_id = '. $current_user->ID .' LIMIT 1');
if ($result[0]->meta_value == 'Peregrine') {
$result[0]->meta_value = 'PG';
}elseif ($result[0]->meta_value == 'Barbary') {
$result[0]->meta_value = 'BB';
}
return $result[0]->meta_value;
}
There are a few things I notice that could cause problems:
You have this line that (1) has no ; at the end and (2) it doesn't look like you need it anyway - you don't use $generated_id anywhere:
$generated_id = generate_member_id()
You are not passing the user_id into generate_member_id for your users in the loop calling update_user_meta...
... but even if you did pass in the user_id, generate_member_id isn't using it anyway - it is using the current user id. That is the wrong value for the users in your loop.
You need to fix your generate_member_id function to work with the user_id parameter. I assume you want this function to work without one too, so it still gets the get_current_user_id is no user id is passed in:
add_action('user_register', 'generate_member_id');
function generate_member_id($user_id){
// If no user_id is passed in, use the current user id
if (!$user_id) $user_id = get_current_user_id();
$unique_id = 1000 + $user_id;
$chapter_id = fetch_chapter_id();
$member_id = "FAL-" . $chapter_id . "-" . $unique_id;
return $member_id;
}
And then remove the erroneous $generated_id... line and pass the user_id to the generate_member_id in your update_user_meta:
global $wpdb;
$users = $wpdb->get_results( "SELECT ID FROM $wpdb->users" );
if( $users ) {
foreach ( $users as $user ) {
update_user_meta( $user->ID, 'member_id', generate_member_id($user->ID) );
}
}

get unique slug in codeigniter

I want to get unique slug for my articles. I am using codeigniter. I was wondering to have some thing like sample-title-1 and sample-title-2 if there are two articles that have the same title like codeignier does with file upload filename(:num) . I could not figure out a way to do it. I am not an expert on codeigniter. I am learning it.
I prepared a function, when passed a string $str it checks if the slug exists, if it does, it adds the ID of that article to the end of that slug and returns it, if not, it returns the slug.
It is working fine and serving the purpose of unique slug. But what I wanted was to have something like sample-title-1 and sample-title-2 . Is there any way to do so?
$data['slug'] = $this->get_slug($data['title']);
public function get_slug ($str)
{
$slug = url_title($str, 'dash', true);
// Do NOT validate if slug already exists
// UNLESS it's the slug for the current page
$id = $this->uri->segment(4);
$this->db->where('slug', $slug);
! $id || $this->db->where('id !=', $id);
$category = $this->category_m->get();
if (count($category)) {
return $slug.$id;
}
return $slug;
}
easy to use and really helpful to create unique slugs have look on CI slug library
read its documentation to implement it.
what i used to do is to make slug db field UNIQUE.
Then easly do all with the CI helpers Url Helper and Text Helper
$last_id_inserted = //get from db the last post's ID;
$post_title = "My slug would be";
$slug = mb_strtolower(url_title(convert_accented_characters($post_title))).'-'.$last_id_inserted;
echo $slug;
//outputting my-slug-would-be-123
//insert the new post with slug
So ID will be unique and slug too.
I think you need something like that:
//Database loaded
//Text helper loaded
function post_uniq_slug($slug, $separator='-', $increment_number_at_end=FALSE) {
//check if the last char is a number
//that could break this script if we don't handle it
$last_char_is_number = is_numeric($slug[strlen($slug)-1]);
//add a point to this slug if needed to prevent number collision..
$slug = $slug. ($last_char_is_number && $increment_number_at_end? '.':'');
//if slug exists already, increment it
$i=0;
$limit = 20; //for security reason
while( get_instance()->db->where('slug', $slug)->count_all_results('posts') != 0) {
//increment the slug
$slug = increment_string($slug, $separator);
if($i > $limit) {
//break;
return FALSE;
}
$i++;
}
//so now we have unique slug
//remove the dot create because number collision
if($last_char_is_number && $increment_number_at_end) $slug = str_replace('.','', $slug);
return $slug;
}
Examples:
post_uniq_slug('sample'); //"sample" exists
//sample-1
post_uniq_slug('sample-2013'); //"sample-2013" exists
//sample-2013-2
post_uniq_slug('sample-2013', '-', TRUE); //increment "sample-2013"
//sample-2014
*NOT TESTED
public function create_slug($name)
{
$table='tradeshow'; //Write table name
$field='slug'; //Write field name
$slug = $name; //Write title for slug
$slug = url_title($name);
$key=NULL;
$value=NULL;
$i = 0;
$params = array ();
$params[$field] = $slug;
if($key)$params["$key !="] = $value;
while ($this->db->from($table)->where($params)->get()->num_rows())
{
if (!preg_match ('/-{1}[0-9]+$/', $slug ))
$slug .= '-' . ++$i;
else
$slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
$params [$field] = $slug;
}
return $alias=$slug;}

WordPress Get the Page ID outside the loop

I want to get the page ID before starting the loop in WordPress. I am using
$page = get_query_var('page_id');
Apparently, it returns nothing.
I just want to check a page for its ID and add a class to <body> tag based on it.
If you're using pretty permalinks, get_query_var('page_id') won't work.
Instead, get the queried object ID from the global $wp_query:
// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id = get_queried_object_id();
// "Dirty" pre 3.1
global $wp_query;
$page_object = $wp_query->get_queried_object();
$page_id = $wp_query->get_queried_object_id();
You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):
<?php
/**
* #uses WP_Query
* #uses get_queried_object()
* #see get_the_ID()
* #return int
*/
function get_the_post_id() {
if (in_the_loop()) {
$post_id = get_the_ID();
} else {
global $wp_query;
$post_id = $wp_query->get_queried_object_id();
}
return $post_id;
} ?>
And simply do:
$page_id = get_the_post_id();
Use this global $post instead:
global $post;
echo $post->ID;
If you by any means searched this topic because of the post page (index page alternative when using static front page), then the right answer is this:
if (get_option('show_on_front') == 'page') {
$page_id = get_option('page_for_posts');
echo get_the_title($page_id);
}
(taken from Forrst | Echo WordPress "Posts Page" title - Some code from tammyhart)
If you're on a page and this does not work:
$page_object = get_queried_object();
$page_id = get_queried_object_id();
you can try to build the permalink manually with PHP so you can lookup the post ID:
// get or make permalink
$url = !empty(get_the_permalink()) ? get_the_permalink() : (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$permalink = strtok($url, '?');
// get post_id using url/permalink
$post_id = url_to_postid($url);
// want the post or postmeta? use get_post() or get_post_meta()
$post = get_post($post_id);
$postmeta = get_post_meta($post_id);
It may not catch every possible permalink (especially since I'm stripping out the query string), but you can modify it to fit your use case.
I have done it in the following way and it has worked perfectly for me.
First declared a global variable in the header.php, assigning the ID of the post or page before it changes, since the LOOP assigns it the ID of the last entry shown:
$GLOBALS['pageid] = $wp_query->get_queried_object_id();
And to use anywhere in the template, example in the footer.php:
echo $GLOBALS['pageid];
You can use is_page($page_id) outside the loop to check.
This function get id off a page current.
get_the_ID();
Use below two lines of code to get current page or post ID
global $post;
echo $post->ID;
This is the correct code.
echo $post->ID;
If you are out of the Loop of WordPress you can not use any of the method of wordpress so you must use pure php.
You can use this code. And sure will help you :)
$page_id = #$_GET['page_id'];
if (!is_numeric($page_id)) {
// Then the uri must be in friendly format aka /my_domain/category/onepage/
// Try this
//$path = '/www/public_html/index.php/';
///$path = '/my_domain/category/onepage/';
$path = $_SERVER['REQUEST_URI'];
// Clean the uri
//$path = str_replace('/', '', $page);
$path = str_replace('.php', '', $path);
//$path = str_replace('?s=', '', $path);
$path = $path ? $path : 'default';
$path_len = strlen($path);
$last_char = substr($path, $path_len -1);
//echo $last_char;
$has_slash = strpos($last_char, "/");
//echo $has_slash;
if ($has_slash === 0) :
$path = substr($path, 0, $path_len -1);
elseif ($has_slash === null) :
$path = substr($path, 0, $path_len);
endif;
//echo "path: ".$path; // '/www/public_html/index'
$page = substr(strrchr($path, "/"), 1);
echo "page: ".$page; // 'index'
}
$my_page_id = 31;
$my_page = 'mypage';
//echo "page: ".$page;
//echo "page_id ".$page_id;
if($page_id == $my_page_id || $page == $my_page)
{
// your stuff....
}
Enjoy!

Categories