WordPress plugin to tag category while posting - wordpress

I'm not a big programmer, but this week get in touch with Openai. It's my first experience with AI. I tried to create code that works as a Wordpress plugin to meet a need.
I make a lot of posts and each post I have to mark the same category. Then I thought that there should be a plugin to mark the category so that when I need to post again, the category would already have its checkbox checked, so I wouldn't need to scroll the selection box of the categories and mark the same category.
Openai generated this code, it didn't work, from what I noticed the cookie is not being created.
Plugin Name: Category Marker
Description: Checks the checkbox of the previously marked category when making a post
Version: 0.1
Author:
*/
//This is the first function
function catemarcada_create_cookie() {
global $post;
if ( isset( $post ) && 'post-new.php' == basename( $_SERVER['SCRIPT_FILENAME'] ) ) {
// Create cookie when making a post
if ( isset( $post->ID ) ) {
$categoryID = get_post_meta($post->ID, '_category_id', true);
setcookie( 'catemarcada', $categoryID, time() + (86400 * 30), "/"); // 86400 = 1 day
}
}
}
add_action( 'wp_loaded', 'catemarcada_create_cookie' );
//This is the second function
function catemarcada_get_cookie() {
global $post;
if ( isset( $post ) && 'post-new.php' == basename( $_SERVER['SCRIPT_FILENAME'] ) ) {
// Get cookie when accessing the post-new.php file
if ( isset( $_COOKIE['catemarcada'] ) ) {
$categoryfound = $_COOKIE['catemarcada'];
}
}
}
add_action( 'wp_loaded', 'catemarcada_get_cookie' );
//This is the third function
function catemarcada_check_category() {
global $post;
if ( isset( $post ) && 'post-new.php' == basename( $_SERVER['SCRIPT_FILENAME'] ) ) {
// Compare the value of the cookie with the category IDs in the WordPress database
$categories = get_categories();
foreach ( $categories as $category ) {
if ( $categoryfound == $category->cat_ID ) {
// Check the checkbox field of the category in the WordPress database
echo '<input type="checkbox" name="'.$category->cat_ID.'" checked="checked" />';
}
}
}
}
add_action( 'wp_loaded', 'catemarcada_check_category' );
// Redirect to post-new.php
add_action('post_updated', 'redirect_post_new', 10, 3);
function redirect_post_new( $post_id, $post, $update ){
if( $update ){
wp_redirect( admin_url( 'post-new.php' ) );
exit();
}
}
This is the description of the plugin I asked to be generated:
Write PHP code that works as a Wordpress plugin. The plugin will only work when I access the “post-new.php” file.
First function:
When making a post, the plug-in will create a cookie with the name “catemarcada”.
This cookie will store the selected category ID during text posting. The cookie must expire within 360 days.
Second function:
When accessing the “post-new.php” file, check if the cookie named “catemarcada” already exists. If it exists, do not create it again.
And every time I access the “post-new.php” file, the plug-in will look up the ID that was recorded in the cookie named “catemarcada” and record the ID in a variable called “categoryfound”.
Third function:
The plug-in should compare the ID that is in the variable called “categoryfound” with the IDs of the categories in the Wordpress database.
If the ID that is in the variable called “categoryfound” is the same as the ID of any of the categories in the Wordpress database, check the checkbox field of the category in the Wordpress database in question.
When making a post, redirect to the post-new.php file.

Related

Creating a WordPress post publish button on the front end

How can I create a button in the frontend that when the user clicks on the button, the post changes from draft to published?
I use the default function to generate the shortcode but it doesn't work
In fact, the post that is currently available and in the draft status in the front form, the user clicks on the button to publish it.
function wp_publish_post( $post ) {
global $wpdb;
$post = get_post( $post );
if ( ! $post ) {
return;
}
if ( 'publish' === $post->post_status ) {
return;
}
$post_before = get_post( $post->ID );
add_shortcode('publish_post','wp_publish_post');
tanks

Redirecting customers to custom page after sale in WooCommerce

I'm trying to learn WooCommerce and WordPress plugins so I'm tweaking around. I'm trying to create a plugin that redirects customer to a custom page after checkout. The custom page/url can be defined when I create the product. Here is my code:
<?php
/*
Plugin Name: Custom Redirect After Sale
Description: Redirects customers to a custom page after a successful sale.
*/
// Register a new meta field for products
add_action( 'add_meta_boxes', 'custom_redirect_meta_box' );
function custom_redirect_meta_box() {
add_meta_box( 'custom_redirect_meta_box', 'Custom Redirect URL', 'custom_redirect_meta_box_callback', 'product', 'side' );
}
function custom_redirect_meta_box_callback( $post ) {
$value = get_post_meta( $post->ID, '_custom_redirect_url', true );
echo '<label for="custom_redirect_url">Custom Redirect URL:</label>';
echo '<input type="text" id="custom_redirect_url" name="custom_redirect_url" value="' . esc_attr( $value ) . '" style="width:100%">';
}
// Save the meta field value when the product is saved
add_action( 'save_post_product', 'save_custom_redirect_meta_box_data' );
function save_custom_redirect_meta_box_data( $post_id ) {
if ( isset( $_POST['custom_redirect_url'] ) ) {
update_post_meta( $post_id, '_custom_redirect_url', sanitize_text_field( $_POST['custom_redirect_url'] ) );
}
}
// Redirect to the custom page after a successful sale
add_action( 'woocommerce_payment_complete', 'custom_redirect_after_sale' );
function custom_redirect_after_sale( $order_id ) {
$order = wc_get_order( $order_id );
//$order->update_status( 'completed' );
$items = $order->get_items();
// Get the first product in the order
$product = reset($items);
// Get the custom redirect URL for the product
//$redirect_url = get_post_meta( $product->get_product_id(), '_custom_redirect_url', true );
$redirect_url = get_post_meta( $product->get_id(), '_custom_redirect_url', true );
//echo "Meta retrieved: " . $redirect_url;
//error_log("callback fired");
//echo "Payment complete ho ho ho";
if( $redirect_url ) {
wp_redirect( $redirect_url );
exit;
}
}
It seems the woocommerce_payment_complete hook is not firing. I tried to echo out the redirect url and text but it doesn't seem to work.
I'm on localhost and I'm using the cash on delivery payment method.
Basing this answer on the great https://rudrastyh.com/ - specifically this tutorial https://rudrastyh.com/woocommerce/thank-you-page.html#redirects this is the code that should work for what you are trying to do.
First, you hook into the template_redirect action to determine the URL where the customer needs to go
Getting the Order ID, you can get the products purchased for that order
Once you have the purchased products, you can get their ID and meta data, the redirect URL you saved for each. Note that while you use WP functions for handling meta, when working with WooCommerce it is best practice to use its CRUD methods. In case in the future they port products to custom tables, your code will continue working.
Implement the redirect with the WP function wp_safe_redirect
Note that what you are trying to achieve will have problems if customers purchase orders with more than 1 product, and you have more than 1 redirect URL. In this implementation, the first product in the order that has a saved redirect URL will override all others
add_action( 'template_redirect', 'purchased_product_redirect');
function purchased_product_redirect(){
if( !function_exists( 'is_wc_endpoint_url' )){
return;
}
// do nothing if we are not on the order received page
if( ! is_wc_endpoint_url( 'order-received' ) || empty( $_GET[ 'key' ] ) ) {
return;
}
// Get the order ID
$order_id = wc_get_order_id_by_order_key( $_GET[ 'key' ] );
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Get and Loop Over Order Items
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$product = wc_get_product($product_id);
if(!$product){
continue;
}
//Get the first product's redirect URL
$product_redirect_url = $product->get_meta('_custom_redirect_url');
if(!$product_redirect_url){
continue;
}
wp_safe_redirect( $product_redirect_url );
exit; // always exit after using wp_safe_redirect
}
}

how to change edit url with "Id" to edit url with "Slug" in Wordpress

I have this is WordPress Post editing Url:
https://example.com/wp-admin/post.php?post=ID&action=edit
and I want to change it to Slug Not the ID Like This:
https://example.com/wp-admin/post.php?post=Slug&action=edit
I was trying to edit the post with this Url but is not working:
https://example.com/wp-admin/post.php?post=MyPostSlug&action=edit
In order to change the edit post link structure, you can use the get_edit_post_link filter like so:
add_filter( 'get_edit_post_link', 'so_73914075_get_edit_post_link', 10, 3);
function so_73914075_get_edit_post_link($link, $post_id, $context) {
$post = get_post( $post_id );
if ( ! in_array( $post->post_type, array( 'post', 'page' ) ) ) {
return $link;
}
$post_type_object = get_post_type_object( $post->post_type );
if ( 'revision' === $post->post_type ) {
$action = '';
} elseif ( 'display' === $context ) {
$action = '&action=edit';
} else {
$action = '&action=edit';
}
if ( 'display' === $context ) {
$post_type = '&post-type=' . $post->post_type;
} else {
$post_type = '&post-type=' . $post->post_type;
}
$custom_edit_link = str_replace( '?post=%d', '?post-name=%s', $post_type_object->_edit_link );
return admin_url( sprintf( $custom_edit_link . $action . $post_type, $post->post_name ) );
}
This will change the edit links for regular posts and pages to something like this:
https://example.com/wp-admin/post.php?post-name=the-post-slug&action=edit&post-type=post
WARNING: make sure you limit this to only the post types you need to change the URL for. Making this change global will almost surely
have unintended effects over other plugins
However, making the admin panel actually load the edit screen is not that easy.
Looking at the source code of the wp-admin/post.php file, you will see that there is no way to hook into the flow and populate the $post_id variable with the post id matching the slug you are sending through.
That means you have 2 options:
RECOMMENDED Update the edit link to whatever format you want and then create an admin redirect function that pulls the slug from the initial URL and redirects to the actual edit page with the ?post=%d in it.
NOT RECOMMENDED Create a new admin edit page that will understand your URL structure and include the wp-admin/post.php after the code that pulls the $post_id based on the slug.
The 2nd method might come with lots of extra code you need to write to cover all the cases and all the instances a post reaches the post.php in the admin panel

How to mark wordpress posts as read?

I want to make something similar to what Techcrunch have on their site. For now I use wordpress plugin that mark posts as new and think to modified it to achieve similar functionality but the plugin won't work for ajax loading.
What I want to make is when user open new post, automatically after he returns to the front page, title and excerpt of the post to be color faded. How to make this with setting cookie and make it to work for title and excerpt on any page (for post list, grids etc.), instead of single post page. And also I need this to work when new posts are loaded with ajax.
I tried this function and It's work ok, but now I need text label to change to Old after user open the post, and then to inject some css to the title. Also, this is not perfect, because I want all posts to be New on first visit, an then to change to Old after user open them.
function wpb_lastvisit_set_cookie() {
if ( ! is_admin() && ! isset( $_COOKIE['lastvisit'] ) ) {
setcookie( 'lastvisit', $current, time() + 3600 * 24 * 100, COOKIEPATH, COOKIE_DOMAIN, false );
}
}
add_action( 'init', 'wpb_lastvisit_set_cookie');
function wpb_lastvisit_the_title ( $title, $id ) {
if ( !in_the_loop() || is_singular() || get_post_type( $id ) == 'page' ) return $title;
// if no cookie then just return the title
if ( !isset($_COOKIE['lastvisit']) || $_COOKIE['lastvisit'] == '' ) return $title;
$lastvisit = $_COOKIE['lastvisit'];
$publish_date = get_post_time( 'U', true, $id );
if ($publish_date > $lastvisit) $title .= ' New';
if ($publish_date < $lastvisit) $title .= ' Old';
return $title;
}
add_filter( 'the_title', 'wpb_lastvisit_the_title', 10, 2);

Set Wordpress excerpt and post thumbnail based on custom field

As stated in the title, I would like to automatically save/update the value of post_excerpt and post_thumbnail based on an ACF custom field (mostly for compatibily reasons with other plugins). Now, while tring to accomplish this I encountered 2 issues, first being with the following function:
function test_FeaturedImageSetByACF() {
$current_screen = get_current_screen(); // Current admin screen needed to identify the current cpt
$current_cpt_name = $current_screen->post_type; // Current cpt name
$current_cpt_support = 'thumbnail'; // We want to check if the CPT supports this feature
$post_id = get_the_ID(); // Current post ID
$post_image_field = get_field('post_head_img'); // ACF field we want to sync
$post_image_id = $post_image_field['id']; // ACF image filed ID
$post_image_url = $post_image_field['url']; // ACF image filed URL
// If current cpt supports thumbnails/featured images
if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
delete_post_thumbnail( $post_id );
set_post_thumbnail( $post_id, $post_image_id );
}
}
}
add_action('save_post', 'test_FeaturedImageSetByACF', 13, 2 );
add_action('publish_post', 'test_FeaturedImageSetByACF', 10, 2 );
It does work, however sometimes it seems to update the value only the second time I save (which means I have to save twice). I understand I'm either using a wrong hook, a wrong priority or something like that, but I can't figure out which one it is.
Second issue I have, is I would like to accomplish something similar for post excerpts. Now the functions's will look alike the previous one quite a lot, but I don't know which value to update. Can anyone point me in the right direction?
Thanks in advance
You can use acf/save_post hook. Object ID is passed
add_action('acf/save_post', 'handle_acf', 20);
function handle_acf($object_id)
{
// Do your stuff
}
Since this became more of an ACF specific question rather than a generic one, I decided to post on ACF's support forums aswell were user John Huebner pointed me in the right direction. For anyone interested, the topic can be found at https://support.advancedcustomfields.com/forums/topic/set-wordpress-excerpt-and-post-thumbnail-based-on-custom-field/ while (in the event that post may get deleted or something) this is the code I used both for the excerpt part and the custom post thumbnail/featured image:
add_action('save_post', 'flex_CustomExcerptSetByACF', 50);
function flex_CustomExcerptSetByACF() {
global $post;
$post_id = ( $post->ID ); // Current post ID
$post_excerpt = get_field( 'post_excerpt', $post_id ); // ACF field
if ( ( $post_id ) AND ( $post_excerpt ) ) {
$post_array = array(
'ID' => $post_id,
'post_excerpt' => $post_excerpt
);
remove_action('save_post', 'flex_CustomExcerptSetByACF', 50); // Unhook this function so it doesn't loop infinitely
wp_update_post( $post_array );
add_action( 'save_post', 'flex_CustomExcerptSetByACF', 50); // Re-hook this function
}
}
add_action('save_post', 'flex_FeaturedImageSetByACF', 50);
function flex_FeaturedImageSetByACF() {
$current_screen = get_current_screen(); // Current admin screen needed to identify the current cpt
$current_cpt_name = $current_screen->post_type; // Current cpt name
$current_cpt_support = 'thumbnail'; // We want to check if the CPT supports this feature
global $post;
$post_id = ( $post->ID ); // Current post ID
$post_image_field = get_field('post_head_img', $post_id ); // ACF field
if ( ( $post_id ) AND ( $post_image_field ) ) {
$post_image_id = $post_image_field['id']; // ACF image filed ID
$post_image_url = $post_image_field['url']; // ACF image filed URL
// If current cpt supports thumbnails/featured images
if ( post_type_supports( $current_cpt_name, $current_cpt_support ) ) {
if ( ( $post_image_url ) AND ( ( $post_image_url ) != ( get_the_post_thumbnail() ) ) ) {
update_post_meta($post_id, '_thumbnail_id', $post_image_id);
}
}
}
}

Resources