Show message after new post is published (WordPress) - php

When publishing a new post in WordPress I want to show an extra admin_notice to show a custom message. I'm using the admin_notices hooks for this. I tested this and it works. What doesn't work is to show it when the post is published.
I tried a couple of methods including the ' publish_post' hook. The hook is firing, when I put a var_dump('bla');exit(); I can see this working. I think the reason the admin_notices doesn't show is because the page is refreshing. So if there would be something like 'after_publish_post' that'd be great but I cannot find it.
I also tried something I've found in a similar question:
if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) { echo "New post!"; exit();}
This also has no effect
--
What I have at this moment is:
add_action('publish_post', array($this,'onInsertPost')); //does work, function gets triggered
public function onInsertPost($post_id, $post, $update) {
add_action( 'admin_notices', array($this, 'info_text_news') );
}
public function info_text_news() {
$class = 'notice notice-info';
$message = __( 'My message', 'admin_notice' );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), $message);
}
Like I earlier said, all this code is working but togheter the notice is not showing up. I think because of the refreshing page after pressing the publish button.

I've found a solution to do this. I'm checking the post date and comparing it to the date of today. If the post is posted today it triggers the hook. In my case, one day is fine. If you need to only show it after post you can adjust it to checking the time also.
global $pagenow;
if ( $pagenow == 'post.php' ) {
$currentPost = get_post( $_GET['post'] );
$postdate = substr($currentPost->post_date, 0 , 10);
//if post type is post and post is published today show info message
if($currentPost->post_type == 'post' && $postdate == date('Y-m-d')) {
add_action( 'admin_notices', array($this, 'info_text_news') );
}
}

Related

WordPress "save_post" call only on save post not on update

I am trying to send post data to third-party services when the post is saved via API. I am using hook add_action( 'save_post', [$this, 'save_post_callback'], 100, 3); but this hook seems to be called in update post as well as post-new.php in admin panel. So to get rid of running this hook in post-new.php, I have checked the $_POST request but I am not able to filter the update post since I want to call API only in save the post, not in an update.
There seems to be the third parameter in callback function $update but it's not working either. Below is my code that needs to be called only in save a post but it's not working. Any help would be greatly appreciated.
function save_post_callback( $post_id, $post, $update ) {
// (!$update) => this doesnot seems to work
if(!empty($_POST) && $post->post_type == "post"){
//run only when save post
}
}
simple way is to check if _wp_http_referer last part is post-new.php or not.
here is a simple code
function save_post_callback($post_id, $post, $update)
{
// (!$update) => this doesnot seems to work
if ( ! empty($_POST) && $post->post_type == "post" ){
$end = explode('/', $_POST[ '_wp_http_referer' ]);
$end = end($end);
if($end == 'post-new.php'){
//echo 'it is new post';exit();
//do what you want here.
}
}
}
From StackExchange here. It looks like a clever way is to compare the post_date & post_modified to determine it is a new post.
$is_new = $post->post_date === $post->post_modified;
if ( $is_new ) {
// first publish
}

WooCommerce - Redirect Logged In Users Based on their Role

This is a query based around WooCommerce Membership and Subscriptions.
I must add that I'm also trying to decide if it's good UX to do what I'm doing.
There are many solutions to redirecting users after they log in but I have a situation where I want to redirect a user with the role of 'subscriber' when they click on specific links to pages that describe and allow you to become a member. So although I don't want to hide 'join now' etc I just want those to redirect to the my-account page.
Again there are various roles and redirect plugins but none seem to help in this specific scenario. So the source of the code I've used is here: SOURCE and I'm looking to do something like this:
function eks_redirect_users_by_role() {
global $post;
$current_user = wp_get_current_user();
$role_name = $current_user->roles[0];
if ( 'subscriber' === $role_name && $post->ID == 47145) {
wp_redirect( '/my-account' );
}
}
add_action( 'admin_init', 'eks_redirect_users_by_role' );
So if the user role is a subscriber and they try and visit the page idea it's redirected.
At the current time, it does fall back to a product page which says 'you already have a membership' but it's multiple steps to arrive.
This might be more useful and proper way to achieve your request.
function redirection_based_user_role(){
$current_user = wp_get_current_user();
$role_name = $current_user->roles[0];
$postid = get_the_ID();
if ( 'subscriber' === $role_name && $postid == 47145 ) {
wp_redirect( home_url( '/my-account' ), 301 );
exit;
}
}
add_action( 'template_redirect', 'redirection_based_user_role' );
Hope this works.
I was able to achieve want I wanted to the following way:
function eks_redirect_user() {
$current_user = wp_get_current_user();
$role_name = $current_user->roles[0];
$postid = get_the_ID();
if ( 'subscriber' === $role_name && $postid == 47145 ) { ?>
<script>
function redirectPage() {
window.location = "/my-account/";
}
redirectPage();
</script>
<?php
exit;
}
}
add_action('wp_footer', 'eks_redirect_user' );
The issue is it's a fairly untidy solution as the redirect feels odd. I'm not sure if using wp_redirect would work better. I decided to do was just disable the button on the page with the main membership information rather than redirecting every call to action to the account page which seems like a more elegant solution.

How to get current post type in functions.php in order to use globally?

I want to check the post type of any pages or posts and display some features depending on the post type. So I'm using a function in functions.php which returns the post type when used in admin pages but not on theme pages.
I need this function to include a php file if the post type is page. So it must work system wide (if it's possible). In templates, admin, edit and post pages.
Here is the function that I'm using:
function vart_current_post_type() {
global $post, $typenow, $current_screen;
if ( $post && $post->post_type ) {
return $post->post_type;
}
elseif ( isset( $_GET[ 'post' ] ) ) {
return get_post_type( $_GET[ 'post' ] );
}
elseif ( $typenow ) {
return $typenow;
}
elseif ( $current_screen && $current_screen->post_type ) {
return $current_screen->post_type;
}
elseif ( isset( $_REQUEST[ 'post_type' ] ) ) {
return sanitize_key( $_REQUEST[ 'post_type' ] );
}
return null;
}
add_action( 'init', 'vart_current_post_type' );
Please tell me what should I do in order to make it work on theme templates and pages?
Thanks.
There's a native method to find out current post type: https://developer.wordpress.org/reference/functions/get_post_type/
$post_type = get_post_type();
On the init hook, the $post object is not yet populated.
See this for WP hook (action) execution. As you can see, posts are selected much later after init. To be more precise, even the request is parsed after init hook. So there is no easy way to get post type in init action, I'm afraid.
With the wp hook you can get the post type with your function.

Wordpress - Change plugin option in function.php

For my website I’m using the plugin Woocommerce Variations to Table Grid, but I would like to restrict this one only for some roles ‘Administrator’ and ‘wholesaler’. (my website is for wholesalers and ‘normal’ customer)
Anyway I was thinking to just desactivate the plugin by checking the user role so I tried the following solution : https://wordpress.stackexchange.com/questions/159085/deactivate-plugin-for-a-specific-user-group
Doesn’t work.
I’ve got a variable in my plugin called $vartable_disabled which is a boolean which “Disable globally” the plugin.
So I am thinking to do something in my functions.php like:
add_action('admin_init', 'my_option_change_plugins');
function my_option_change_plugins()
{
global $current_user;
if (!in_array('administrator' || 'wholesaler', $current_user->roles)) {
deactivate_plugins( // activate for variation-table
$vartable_disabled == 0
$vartable_position == 'under'
);
} else { // desactivate for those than can't use it
activate_plugins(
$vartable_disabled == 1
$vartable_position == 'side'
);
}
But for sure I’m doing something wrong, I tried plenty of different thing the whole day, impossible to figure it out.
Anyone can help?
Cheers 🙂
deactivate_plugins is need. base plugin name. But you are passing variables.
https://codex.wordpress.org/Function_Reference/deactivate_plugins
I found a partial solution with the function "update_option()"
add_action('admin_init', 'my_filter_the_plugins');
function my_filter_the_plugins()
{
global $current_user;
if (in_array('administrator', $current_user->roles)) {
update_option( 'vartable_disabled', 0 );
} else { // activate for those than can use it
update_option( 'vartable_disabled', 1 );
}
}
With that my plugin option switch to '1' (disabled).. but the thing is, it doesn't matter the role as it always go only for the first line..
I'm a bit lost, I don't understand why it works in one way but not the other.
My plugin fonction is:
if ( ((get_post_meta($product->id, 'disable_variations_table', true) == 1 || !empty($checkcat)) || $vartable_disabled == 1) && $vartable_shortcd != 1) {
// Enqueue variation scripts
wp_enqueue_script( 'wc-add-to-cart-variation' );
// Load the template
wc_get_template( 'single-product/add-to-cart/variable.php', array(
'available_variations' => $product->get_available_variations(),
'attributes' => $product->get_variation_attributes(),
'selected_attributes' => $product->get_variation_default_attributes()
) );
return;
}
I think there's a little misunderstanding of a point. A plugin can't be activated for an user and deactivated for another one (in the pure concept of Plugin Activation/Deactivation). It is globally activated or globally deactivated.
Said this, depending on the way that your plugin is programmed, its functions could be disabled to certain users or groups. Instead keeping trying the deactivation method you can, for example, find the parts where your plugin admits to be filtered and take advantage of that. If there is not filters, you can try:
$current_user = wp_get_current_user();
if ( !in_array( array( 'administrator' , 'wholesaler' ) , (array) $current_user->roles ) ) {
update_option( 'vartable_disabled' , 1 ); // Assuming 'vartable_disabled' parameter really disables the plugin for the current user
}
In addition, alike you can hide all the html related to that option (checkboxes, menu elements and others).
It finally didn't work as expected because to change an option you need kind of "administrator" rights, so for the other roles like "customer" it didn't change the option as expected.
Anyway, instead I worked with the plugin developer (thanks Spyros) and the solution has been to hook directly in the plugin (functionnality now added to the new plugin version ;))
The following code has been added:
// if the table is disabled for this product display the default select menus
$checkcat = array();
if (is_array($vartable_categories_exc) && is_array($pcids)) {
$checkcat = array_intersect($pcids, $vartable_categories_exc);
}
$checkrole = array();
if (is_array($vartable_roles_exc) && is_user_logged_in()) {
$user_info = get_userdata(get_current_user_id());
$checkrole = array_intersect($user_info->roles, $vartable_roles_exc);
}
if (!is_user_logged_in() && is_array($vartable_roles_exc) && in_array('guest', $vartable_roles_exc)) {
$checkrole['guest'] = 'guest';
}
if (
((get_post_meta($product->id, 'disable_variations_table', true) == 1 || !empty($checkcat)) || $vartable_disabled == 1 || !empty($checkrole))
&& get_post_meta($product->id, 'disable_variations_table', true) != 2
&& $vartable_shortcd != 1) {
// Enqueue variation scripts
wp_enqueue_script( 'wc-add-to-cart-variation' );
// Load the template
wc_get_template( 'single-product/add-to-cart/variable.php', array(
'available_variations' => $product->get_available_variations(),
'attributes' => $product->get_variation_attributes(),
'selected_attributes' => $product->get_variation_default_attributes()
) );
return;
}
Thanks everyone for your time/help.

WordPress publish_post hook not firing for custom post type

I'm currently doing some work with the WP Job Board Manager plugin and I'm wanting to create a function that will fire when a new job is published.
The first thing I did was to create the general hook to find out what the post type was:
function newJobAdded() {
$posttype = get_post_type( $post );
mail('email#email.com','new job published',$posttype);
}
add_action( 'publish_post', 'newJobAdded' );
Which sent me an email telling me that the post type was: job_listing.
I then created a new function that would only fire if the custom post type was job_listing
function newJobAdded() {
$posttype = "job_listing";
if ($post->post_type == $posttype) {
mail('email#email.com','new job published','done new job publish');
}
}
add_action( 'publish_post', 'newJobAdded' );
However, nothing happens when I do this. Am I missing something simplistic and noobish?
The 'publish_post' action is post type specific. So if you have a custom post type, you need to change the hook you use. if your post type is job_listing, the hook you should use is publish_job_listing.
function newJobAdded($ID, $post ) {
mail('email#email.com','new job published','done new job publish');
}
add_action( 'publish_job_listing', 'newJobAdded', 10, 2 );
Try with
function newJobAdded($ID, $post) {
}
instead of
function newJobAdded() {
}
Reference: publish_post
A more general hook will be transition_post_status which fires everytime a post's status is changed. You can use $old_status and $new_status to check the previous and new status of a post then do something.
For a new post, you can something like this: (Requires PHP 5.3+)
add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
{
if( 'publish' == $new_status && 'publish' != $old_status && $post->post_type == 'my_post_type' ) {
//DO SOMETHING IF NEW POST IN POST TYPE IS PUBLISHED
}
}, 10, 3 );
EDIT
For older versions, use
add_action( 'transition_post_status', 'so27613167_new_post_status', 10, 3 );
function so27613167_new_post_status( $new_status, $old_status, $post )
{
if( 'publish' == $new_status && 'publish' != $old_status && $post->post_type == 'my_post_type' ) {
//DO SOMETHING IF NEW POST IN POST TYPE IS PUBLISHED
}
}

Categories