I am customizing a wordpress plugin which is used for popup email subscribing. when the user submits email he gets a confirmation email in which iam sending my custom html to him. I have five different pages on my web site and every page has that popup. what iam doing is that i want to get the name of my page than according to that i want to send html in email. I did exactly the same thing for other plugin and it worked but in this popup plugin iam unable to get the page name from where it is called.
I have tried following things but failed.
global $post; /* this worked perfect on other plugin */
$pagename = $post->post_name;
if($pagename=="page1")
{
// html page1 //
}
else
{
// html page2 //
}
Just tried this
$slug = basename(get_permalink());
if($slug=="page1") and so on
Here you go, you need to get title for this, as
$post = get_post( $post );
$pagename = isset( $post->post_title ) ? $post->post_title : '';
Hope it helps.
The best way is to use get_queried_object. It retrieve the currently-queried object - page, post, taxonomy, whatever...
You can try this code, its working for me:
$qo = get_queried_object();
if ( 'page' !== $qo->post_type ) {
//Here you can be sure, that you are in page query, so this is available
$pagename = $qo->post_name;
}
Please try to use this:
$pagename = get_query_var('pagename');
if ( !$pagename && $id > 0 ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
Related
I have an page (with snippet code and short code and manual php code) and it call a REST API and base Of response, I want change tag title of this page (Not in database).and it was change every call.
i try do :
in snippet code:
$GLOBALS['MyTitle'] = $response-> title;
in function:
function change_title($title) {
$variable = $GLOBALS['MyTitle'];
if (!empty($variable))
{
$title = $variable;
}
return $title;
}
add_filter('pre_get_document_title', 'change_title',500);
but it was empty every time because the function section run sooner then snippet code(Api Call).
WordPress has not any function for change title tag text? like wp_set_title('my title') to use without add_filter?
Changing title of the page dynamically by applying the filter the hook used for the filter is document_title_parts. Here is the official wordpress documentation link and below is the example. In this example i have used get method for API.
add_filter( 'document_title_parts', 'function_to_dynamic_title');
function function_to_dynamic_title( $title_parts_array ) {
$request = wp_remote_get( 'https://dummyjson.com/products/1' );
if( is_wp_error( $request ) ) {
return $data;
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
$title_parts_array['title'] = $data->title;
return $title_parts_array;
}
Screenshot for your reference
In WordPress, we have an action to change the title programmatically.
add_filter('the_title','your_callback_function');
function your_callback_function($data)
{
global $post;
// add your condition according to page
return 'Desired Title'. $post->ID;
}
Example: www.example.com/johndoe/sample-page/
User with username “johndoe” has
Name field value of “John Doe”
E-mail field value of “johndoe#email.com”
Facebook field value of “facebook.com/johndoe”
Address field value of “Main street 47 ”
Show this values on Sample Page via shortcode
[userdata username={read_from_url} field=email]
Once opened, save this username in a cookie and redirect the visitor:
www.example.com/sample-page/ --> www.example.com/username/sample-page/
Add that USERNAME to all internal links to avoid redirects (from there on every active link on the website to contain the prefix)
Live example with the same functionality on another wordpress site: https://eqology.com/15499949/webshop/our-products-en/omega-3-en/
(Check CTRL+U to see all internal links contain the username/id prefix)
I've tried creating a rewrite tag and a rule for it to be put in a url param
add_rewrite_tag('%username%', '([^&]+)', 'username=');
Then use URL Params shortcode
[urlparam param='username'] but I know it's not suppossed to work this way :D
I've managed to solve it :D :D :D Received $1000 offers to create this plugin and some failed in delivering it; Got so much from the wp community I'll share it without comments.
functions.php
add_action('init', 'eqid_url_rewrite');
function eqid_url_rewrite() {
add_rewrite_rule('([^/]*)/(.+)/?$', 'index.php?eqid=$matches[1]&pagename=$matches[2]','top');
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_filter( 'query_vars', 'eqid_query_var' );
function eqid_query_var($vars){
$vars[] = 'eqid';
return $vars;
}
add_action( 'wp', 'eqid_cookie' );
function eqid_cookie(){
$eqid = get_query_var('eqid');
if($eqid) {
$eqbp = get_user_by('login', $eqid);
if (isset($eqbp->user_login))
setcookie('eqid_cookie', $eqid, strtotime('+90 days'), '/');
}
$prefix_slug_wslash = "bp/";
if(($_COOKIE['eqid_cookie']) && (!$eqid) && $_SERVER['REQUEST_URI'] !== "/" && (strpos($_SERVER['REQUEST_URI'],$prefix_slug_wslash) == true) && (strpos($_SERVER['REQUEST_URI'],$_COOKIE['eqid_cookie']) == false) && !is_admin()) {
wp_redirect( "https://".$_SERVER['HTTP_HOST']."/".$_COOKIE['eqid_cookie']."/".$_SERVER['REQUEST_URI'] );
exit;
}
}
function eqid_shortcode(){
$eqid = get_query_var('eqid');
//$eqid = $_COOKIE['eqid_cookie'];
if($eqid)
$eqbp = get_user_by('login', $eqid);
return $eqbp->user_login;
}
add_shortcode( 'eqbp_id', 'eqid_shortcode' );
function eqid_shortcode_nev(){
$eqid = get_query_var('eqid');
//$eqid = $_COOKIE['eqid_cookie'];
if($eqid)
$eqbp = get_user_by('login', $eqid);
return $eqbp->first_name." ".$eqbp->last_name;
}
add_shortcode( 'eqbp_nev', 'eqid_shortcode_nev' );
author.php
if( ! defined( 'ABSPATH' ) ){ die(); }
$eqid = substr($_SERVER['REQUEST_URI'], 1, -1);
if ($eqid)
setcookie('eqid_cookie', $eqid, strtotime('+90 days'), '/');
wp_redirect( home_url() );
exit;
Above script works for all sub-pages of $prefix_slug_wslash = "bp/";
You can remove that and it will work for all pages.
After opening link like: example.com/username cookie is set and the page will redirect to home. I've added this to header top bar with a shortcode or you can put it in child theme header.php also
//Header Site badge tag [shortcode]
function eqid_headersitebadgetag(){
$eqid = get_query_var('eqid');
if(!$eqid)
$eqid = $_COOKIE['eqid_cookie'];
if($eqid) {
$eqbp = get_user_by('login', $eqid);
if (isset($eqbp->user_login))
return "<strong>".$eqbp->first_name." ".$eqbp->last_name."</strong> <em>(".$eqbp->nickname.")</em>";
}
return;
}
add_shortcode( 'eqbp_sheader', 'eqid_headersitebadgetag' );
For posts I needed the author slug in the link:
Permalinks structure: /%author%/%postname%/
function _eqid_shortcode(){
return get_the_author_meta( 'login' );
}
add_shortcode( '_eqbp_id', '_eqid_shortcode' );
This is more like having an affiliate name masked in a pretty url which will be kept across navigation and you can show affiliate specific info on pages with shortcodes without the need of login from other users.
I have a digital download site running on WordPress/WooCommerce that requires users to be logged in to buy products. There is a login/register button displayed for logged-out users instead of the ‘Buy’ button on product pages as seen here: https://prnt.sc/1rc03lw. I’m trying to redirect users after they’ve logged in or registered back to the previous page but only if that previous page was a product page.
Here is the code I'm currently using which saves the referring URL and then executes a redirect. The redirect works but, I'm trying to limit it to only redirect if the referer URL was a product page (domain.com/product):
[CODE REDACTED]
Any help would be appreciated! Thanks, /JJ
SOLUTION
Thanks for all the responses! This is what we ended up with:
[CODE REDACTED]
Massive thanks to Idan for helping me out in the WooCommerce Developer Slack channel!
CLEANER SOLUTION WITH REGISTRATION FORM REDIRECT FUNCTIONALITY
I was receiving some critical errors - Idan helped me create a cleaner script and implemented the registration form actions too!
// Hide Add to Cart for logged out users
add_action( 'init', 'creatorcabin_hide_price_add_cart_not_logged_in' );
function creatorcabin_hide_price_add_cart_not_logged_in() {
if ( ! is_user_logged_in() ) {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
}
}
// Add Login to Buy button for logged out users
add_action( 'woocommerce_single_product_summary', 'creatorcabin_user_logged_out_disable_add_to_cart', 30 );
function creatorcabin_user_logged_out_disable_add_to_cart() {
if ( ! is_user_logged_in() ) {
$parameter = (is_singular("product")) ? '?product_page=1&my_page_id=' . get_the_ID() : '';
echo '<div class="login-to-buy-box"><h4 style="color: #E67E22;">Login to buy!</h4><p style="color: black;">Login or Sign Up for free to unlock the buy button and gain access to your downloads! Why do I need an account to buy stuff?</p><div class="user-bought-singleproduct">Login / Register ></div></div>';
}
}
// Referer
add_action( 'woocommerce_login_form_end', 'creatorcabin_actual_referer' );
function creatorcabin_actual_referer() {
$product_page = (isset($_GET['product_page'])) ? $_GET['product_page'] : 0;
$page_id = (isset($_GET['my_page_id'])) ? $_GET['my_page_id'] : 0;
echo '<input type="hidden" name="product_page" value="' . $product_page . '" /><input type="hidden" name="my_page_id" value="' . $page_id . '" />';
}
//Login redirect
function custom_login_redirect($redirect) {
if (isset($_POST['my_page_id']) && isset($_POST['product_page']) && intval($_POST['product_page']) === 1) {
$redirect = get_permalink($_POST['my_page_id']);
}
return $redirect;
}
add_filter('woocommerce_login_redirect', 'custom_login_redirect', 10, 1);
// Action and Filter for Registration form
add_action( 'woocommerce_register_form_end', 'creatorcabin_actual_referer' );
add_filter('woocommerce_registration_redirect', 'custom_login_redirect', 10, 1);
Again, massive thanks to Idan for helping me out in the WooCommerce Developer/Community Slack channel!
why don't you just add a query arg to the link on product pages?
edit:
okay, so without going into too much detail as I'm tired and somewhat inebriated and can't be trusted around semicolons right now:
I would use https://developer.wordpress.org/reference/functions/wp_login_url/ to set up the hrefs for my login links. You'll notice that the function comes with:
a: an optional argument for passing the url that the user should be referred to after login
and b: a filter hook called 'login_url' that you can use to hijack the process and apply your own logic in.
also wordpress comes with a function conveniently called 'add_query_arg' which does exactly what it says on the tin. (https://developer.wordpress.org/reference/functions/add_query_arg/)
so if i were to set up some php that would return that string on a product page I'd do something like this:
$refer_to_url = get_permalink(get_the_ID()); //get current post/page permalink
$refer_to_url = add_query_arg('is_product_page', true, $refer_to_url); //add arguments to that url.
$this_login_url = wp_login_url($refer_to_url);
then I'd probably try and set up a filter that would change the referring url to e.g. the user's account page if is_product_page is not true.
https://developer.wordpress.org/reference/functions/add_filter/
you may also have to register the queryvar using
add_filter( 'query_vars', function ( $qvars ) {
$qvars[] = 'is_product_page';
return $qvars;
});
otherwise wordpress might refuse to process the query var.
hope that helps.
You need to check on wp or template_redirect hook is previous page is shop page or not. I have assume and suggest code.
redirect after login will redirect and second function will check is request uri contains shop or not.
<?php
// Function to redirect after login (best so far)
function redirect_after_login(){
global $wp;
if (!is_user_logged_in() && !is_home() && ($wp->query_vars['pagename'] != 'downloads') ){
$redirect = home_url() . "/wp/wp-login.php?redirect_to= $protocol://" .
$_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]);
$shop_url = $_SERVER["REQUEST_URI"];
$shop_end = "/shop/";
if (!endsWith($shop_url, $shop_end)) {
wp_redirect( $redirect );
exit;
}
}
}
add_action( 'wp', 'redirect_after_login', 3 );
// Check is previous page requst url shop page
function isCheckShop($haystack, $needle) {
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
Actually,
The wp_login_url() function let you specify a redirect variable through $redirect.
Source # https://developer.wordpress.org/reference/functions/wp_login_url/
<?php
// for the sake of the argument...
$current_url = home_url( '/product/spiderman-toy-statue-red' );
// in live environment you could use something like this...
// global $wp;
// $current_url = home_url( add_query_arg( $_GET, $wp->request ) );
echo 'Login redirect example';
Your user would click that link on a product page and after login be redirected to that page.
I'm trying to set a new http Header for my wordpress installation but I'm not able to work with $post object inside my new wp_headers filter function. I want to send different headers for diferent post types and use Go(lang) for caching stuff (home project).
function add_new_header($headers) {
$headers['PostId'] = get_the_ID();
return $headers;
}
add_filter('wp_headers', 'add_new_header');
Seems Like I can't access to Post / get_queried_object_id() in the hook as it's not started.
So, referencing post attributes, you have to do in the "template_redirect" hook. As in that moment the Post exists...
add_action('template_redirect', 'add_new_header');
function add_new_header($headers) {
$post_id = get_queried_object_id();
if( $post_id ) {
header("PostId: " . $post_id) ;
}
}
Hope helps to someone.. someday...
I'm trying to get the same effect as the plugin Pages Link To where the title of the post is linked to an external link. The reason I don't want to use the plugin is the link is generated dynamically when the post is saved, but I'm unable to update the the permalink of the post with the external link.
Below is my code in functions.php:
function savepost( $post_id ) {
if( $_POST['post_type'] == 'books' ){
$genre = strip_tags(get_field('genre'));
$author = strip_tags(get_field('author'));
$extlink = "http://www.".$genre."/".$author.".com";
update_post_meta( $post_id, 'extlink', $extlink);
$url = strip_tags(get_field('extlink',$post));
update_post_meta( $post_id, 'post_link', $url);
}
}
add_action( 'save_post', 'savepost' );
i m trying another method in which i assigned a template to the post so that when the post loads it redirects to the link but it doesn't redirect
my code
<?php
ob_start();
?>
<?php
/**
* Template Name: post Redirection Template
*/
get_header();
$redirecturl = strip_tags(get_field('extlink',$post));
wp_redirect($redirect_url);
get_sidebar();
get_footer();
?>
<?php
ob_end_flush();
?>
What you should do, is insert the external link as a custom field in the post editor, then display the custom field value in place of the_permalink(). You could use a plugin such as Advanced Custom Fields to grab the URL from the custom field.
EDIT 1: More clarification using the Advanced Custom Fields plugin as an example. The field name for this example is url.
You should use this wherever you want the custom permalink to appear throughout your site, such as in your archive.php, category.php, etc. Replace the code that looks something like this:
<?php the_title(); ?>
with this:
<?php
$value = get_field( "url" );
if( $value ) { ?>
<?php the_title(); ?>
<?php } else { ?>
<?php the_title(); ?>
<?php } ?>
EDIT 2: Clarifying additional information.
You can add a function to the header.php of your theme that checks if the url is set, then redirects to the external link that way, if your user goes directly to the permalink, it will still redirect them. In fact, you could use this code without using the above code to display the external link.
<?php
$value = get_field( "url" );
if( $value ) {
header('Location: '.$value);
die();
} else {} ?>
Warning: make sure to use this code before any HTML (or text) has been passed to the browser, or it will not work correctly.