Get Permalink by Slug function not working - wordpress

I hadn't realised that WordPress had added a native function for it to the Codex, but for some odd reason the page is blank. Does that mean the functionality is still coming or the page was added by mistake?
http://codex.wordpress.org/Function_Reference/get_permalink_by_slug

It's blank because it doesn't exist. If you change that function name to any random name you like you'll still see a blank page (unless of course the name you change it to is a real function).

function get_permalink_by_slug( $slug, $post_type = '' ) {
// Initialize the permalink value
$permalink = null;
// Build the arguments for WP_Query
$args = array(
'name' => $slug,
'max_num_posts' => 1
);
// If the optional argument is set, add it to the arguments array
if( '' != $post_type ) {
$args = array_merge( $args, array( 'post_type' => $post_type ) );
} // end if
// Run the query (and reset it)
$query = new WP_Query( $args );
if( $query->have_posts() ) {
$query->the_post();
$permalink = get_permalink( get_the_ID() );
} // end if
wp_reset_postdata();
return $permalink;
}

Related

Add different WordPress excerpt formats to different templates

I added the following code to my functions.php file in WordPress 6.1.1 to display excerpts.
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
function new_excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');
...but I also have a use case to show the full excerpt without a read more link.
On page template 1 I add the below code to display the excerpt:
<?php echo the_excerpt(); ?>
...and it displays the excerpt as per the functions.php file but how do I create a 2nd excerpt without the read more link and apply it to page template 2?
Is there a parameter I can use within the_excerpt(parameter); or can I use something like wp_trim_excerpt https://developer.wordpress.org/reference/functions/wp_trim_excerpt/ maybe?
I came across the below code that is supposed to do what I want
function wpex_get_excerpt( $args = array() ) {
// Default arguments.
$defaults = array(
'post' => '',
'length' => 40,
'readmore' => false,
'readmore_text' => esc_html__( 'read more', 'text-domain' ),
'readmore_after' => '',
'custom_excerpts' => true,
'disable_more' => false,
);
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_defaults', $defaults );
// Parse arguments, takes the function arguments and combines them with the defaults.
$args = wp_parse_args( $args, $defaults );
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_args', $args );
// Extract arguments to make it easier to use below.
extract( $args );
// Get the current post.
$post = get_post( $post );
// Get the current post id.
$post_id = $post->ID;
// Check for custom excerpts.
if ( $custom_excerpts && has_excerpt( $post_id ) ) {
$output = $post->post_excerpt;
}
// No custom excerpt...so lets generate one.
else {
// Create the readmore link.
$readmore_link = '' . $readmore_text . $readmore_after . '';
// Check for more tag and return content if it exists.
if ( ! $disable_more && strpos( $post->post_content, '<!--more-->' ) ) {
$output = apply_filters( 'the_content', get_the_content( $readmore_text . $readmore_after ) );
}
// No more tag defined so generate excerpt using wp_trim_words.
else {
// Generate an excerpt from the post content.
$output = wp_trim_words( strip_shortcodes( $post->post_content ), $length );
// Add the readmore text to the excerpt if enabled.
if ( $readmore ) {
$output .= apply_filters( 'wpex_readmore_link', $readmore_link );
}
}
}
// Apply filters and return the excerpt.
return apply_filters( 'wpex_excerpt', $output );
}
Output using:
<?php echo wpex_get_excerpt ( $defaults = array(
'length' => 40,
'readmore' => true,
'readmore_text' => esc_html__( 'read more', 'wpex-boutique' ),
'custom_excerpts' => true,
) ); ?>
...but doesn't seem to workas intended. Outputs the excerpt with no link but the args don't see to work when changed. Would be perfect for my use otherwise. Maybe someone sees how to fix this code?
Thanks

Large WooCommerce query throws fatal memory errors

I have a site that has tens of thousands of orders, which I need to compare the billing and customer/user emails and show a flag if they don't match. One of the stipulations is that I'm unable to add any metadata to the orders. So my solution is to just add a custom column, and compare the emails on the fly when the orders list is rendered. That works just fine.
add_filter( 'manage_edit-shop_order_columns', 'mismatched_orders_column' );
function mismatched_orders_column( $columns ) {
$columns['mismatched'] = 'Mismatched';
return $columns;
}
add_action( 'manage_shop_order_posts_custom_column', 'mismatched_orders_column_data' );
function mismatched_orders_column_data( $column ) {
global $post;
if ( 'mismatched' === $column ) {
$order = new WC_Order( $post->ID );
$customer = $order->get_user();
$result = '';
$billing_email = strtolower ( $order->get_billing_email() );
$customer_email = '';
if ($customer) $customer_email = strtolower ( $customer->user_email );
if ( $customer && ( $billing_email != $customer_email ) ) {
$result = '<span class="mismatched-order" title="Possible order mismatch">Yes</span>';
}
echo $result;
}
}
My issue is when trying to add sorting. Because I'm not accessing any post metadata, I don't have any easy data to sort via the main query. My solution here was originally to hook into pre_get_posts, grab all the orders in a new WP_Query, then loop through them and add the ones that had mismatched emails to an array for use in post__in.
This works/worked fine on my small dev site, but throws fatal memory errors when trying to loop over any more than about 8 or 9 thousand posts (out of a total of 30-40 thousand). Increasing memory isn't really an option.
add_filter( 'manage_edit-shop_order_sortable_columns', 'mismatched_orders_column_sortable');
function mismatched_orders_column_sortable( $columns ) {
$columns['mismatched'] = 'mismatched';
return $columns;
}
add_action( 'pre_get_posts', 'mismatched_emails_posts_orderby' );
function mismatched_emails_posts_orderby( $query ) {
if( ! is_admin() || ! $query->is_main_query() ) {
return;
}
//Remove the pre_get_posts hook so we don't get stuck in a loop
add_action( 'pre_get_posts', 'mismatched_emails_posts_orderby' );
//Make sure we're only looking at our custom column
if ( 'mismatched' === $query->get( 'orderby') ) {
//Set our initial array for 'post__in'
$mismatched = array();
$orders_list = get_posts(array(
'post_type' => 'shop_order',
'posts_per_page' => -1,
'post_status' => 'any',
'fields' => 'ids'
));
//And here is our problem
foreach( $orders_list as $order_post ) :
//Get our order and customer/user object
$order_object = new WC_Order( $order_post );
$customer = $order_object->get_user();
//Check that billing and customer emails don't match, and also that we're not dealing with a guest order
if ( ( $order_object->get_billing_email() != $customer->user_email ) && $order_object->get_user() != false ) {
$mismatched[] = $order_post;
}
endforeach; wp_reset_postdata();
$query->set( 'post__in', $mismatched );
}
}
I would seriously appreciate any insight into how I could either reduce the expense of the query I'm trying to run, or an alternate approach. Again, just for clarification, adding metadata to the orders isn't an option.
Thanks!

How to convert existing code into WooCommerce Plugin

Im extremely new to WordPress and WooCommerce code. I've been provided with some working code that resides in the plugins/woocommerce/templates/archive-product.php
The function is pretty simple, it simply fetches for an array of data from a remote site and makes use of the JSON returned to find the matching SKUs and inject them as items in the product list.
Works quite nicely, however, as I'm new to Woo & WP, I'm hoping someone might be able to show me how I can transform this code into the proper way of it being defined as a plugin?
I'm hoping its just a case of wrapping some additional code around the function, but I'm unsure as to where to start
any tips greatly appreciated
if ( wc_get_loop_prop( 'total' ) ) {
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$cat = explode('/', $actual_link);
if ($cat[4] == 'my-product-list') {
global $current_user;
get_currentuserinfo();
$data = array( 'email' => $current_user->user_email);
$response = wp_remote_post( 'https://www.shop.com/remote-data/', array( 'data' => $data ) );
$curl = 'https://www.shop.com/remote-data/';
$response = wp_remote_get( $curl );
$rows = wp_remote_retrieve_body( $response ) ;
$decode = json_decode(stripslashes($rows), true);
global $wpdb;
$product_id = array();
$i = 0;
foreach ($decode as $single_data) {
foreach ($single_data['items'] as $data) {
$result = $wpdb->get_results ( "SELECT post_id FROM wp_postmeta WHERE meta_key = '_sku' AND meta_value = '".$data."'" );
$product_id[$i] = $result[0]->post_id;
$i++;
}
}
$product_id = array_filter(array_unique($product_id));
$args = array(
'post_type' => 'product',
'post__in' => $product_id
);
//The Query
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) {
$the_query->the_post();
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
}
You could try to hook it into woocommerce_before_main_content
Like so:
function fetch_shop_data() {
// your code
}
add_action('woocommerce_before_main_content', 'fetch_shop_data');

Updating GEO my WP fields using frontend Advanced custom fields form - WordPress

I’ve created a frontend form using the advanced custom fields (ACF) plugin. Within this form I’ve added some location fields such as postcode and city.
Below is the function used to update the post
global $post_id;
add_filter('acf/pre_save_post' , 'tsm_do_pre_save_post' );
function tsm_do_pre_save_post( $post_id ) {
// Bail if not logged in or not able to post
if ( ! ( is_user_logged_in() ) ) {
return;
}
// check if this is to be a new post
if( $post_id != 'new_job' ) {
return $post_id;
}
$profile_id = um_profile_id();
$userID = 'user_'.$profile_id;
$user_id = get_current_user_id();
// Create a new post
$post = array(
'ID'=> $post_id,
'post_type' => 'members',
'post_status' => 'publish',
'post_title' => $userID,
'post_author' => $user_id,
'category' => $_POST['acf']['field_594d0ffc2a66d'],
);
// insert the post
$post_id = wp_insert_post( $post );
// Save the fields to the post
do_action( 'acf/save_post' , $post_id );
return $post_id;
exit;
}
Once this form has been submitted, the custom post type is updated with no issues.
How can I add the submitted location data (postcode, city etc) into the GEO MY WP information for the post?
I’ve tried to follow the information in the docs secetion (http://docs.geomywp.com/gmw_pt_update_location/) but not having much luck.
GEO my WP function fron docs below:
function gmw_update_post_type_post_location( $post_id ) {
// Return if it's a post revision
if ( false !== wp_is_post_revision( $post_id ) )
return;
// check autosave //
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
//check if user can edit post
if ( !current_user_can( 'edit_post', $post_id ) )
return;
//get the address from the custom field "address"
$address = get_post_meta( $post_id, 'address', true );
//varify that address exists. Otherwise abort the function.
if ( empty( $address ) )
return;
//include the update location file file
include_once( GMW_PT_PATH .'/includes/gmw-pt-update-location.php' );
//make sure the file included and the function exists
if ( !function_exists( 'gmw_pt_update_location' ) )
return;
//Create the array that will pass to the function
$args = array(
'post_id' => $post_id, //Post Id of the post
'address' => $address // the address we pull from the custom field above
);
//run the udpate location function
gmw_pt_update_location( $args );
}
//execute the function whenever post type is being updated
add_action( 'save_post_post', 'gmw_update_post_type_post_location' );
I believe I need to somehow combine the two functions so when the ACF form is updated, it also needs to update the GEO my wp meta data also.
I've tried combining the two functions but not having much luck.
If someone can point me in the right direction it will be very much appreciated
Thanks
Updated code.....
I've tried to add the gmw_update_post_type_post_location() function within the ACF function (code below) but still not having much luck...
global $post_id;
add_filter('acf/pre_save_post' , 'tsm_do_pre_save_post' );
function tsm_do_pre_save_post( $post_id ) {
// Bail if not logged in or not able to post
if ( ! ( is_user_logged_in() ) ) {
return;
}
// check if this is to be a new post
if( $post_id != 'new_job' ) {
return $post_id;
}
$profile_id = um_profile_id();
$userID = 'user_'.$profile_id;
$user_id = get_current_user_id();
$profilePostcode = get_post_meta( $post_id, 'location_postcode', true );
// Create a new post
$post = array(
'ID'=> $post_id,
'post_type' => 'members', // Your post type ( post, page, custom post type )
'post_status' => 'publish', // You can use -> publish, draft, private, etc.
'post_title' => $userID, // Post Title ACF field key
'post_author' => $user_id,
'category' => $_POST['acf']['field_594d0ffc2a66d'], // Post Content ACF field key
);
// insert the post
$post_id = wp_insert_post( $post );
// Save the fields to the post
do_action( 'acf/save_post' , $post_id );
gmw_update_post_type_members_location($post_id);
return $post_id;
exit;
}
function gmw_update_post_type_members_location( $post_id ) {
$profilePostcode = get_post_meta( $post_id, 'profile_location_postcode', true );
if ( empty( $profilePostcode ) )
return;
$address = array(
//'street' => $_POST['location_address'],
//'city' => $_POST['location_town'],
//'state' => $_POST['location_state'],
'zipcode' => $profilePostcode,
//'country' => $_POST['location_country']
);
include_once( GMW_PT_PATH .'/includes/gmw-pt-update-location.php' );
if ( !function_exists( 'gmw_pt_update_location' ) )
return;
$profile_id = um_profile_id();
$userID = 'user_'.$profile_id;
$user_id = get_current_user_id();
$args = array(
'post_id' => $post_id, //Post Id of the post
'post_title' => $userID, // Post Title ACF field key
'post_author' => $user_id,
'post_type' => 'members',
'address' => $address
);
//run the udpate location function
gmw_pt_update_location( $args );
}

Wordpress - Check if post exists,if yes update fields

I use a frontend form to post, and what i want is to check if a post exists by title.If yes and metafield value is bigger than the old one,just replace the value.
Anyone that has implemented something like that in the past?
<?php
session_start();
$user_email = $_SESSION['user_email'];
$user_name = $_SESSION['user_name'];
$user_img_url = 'https://graph.facebook.com/'.$user_name.'/picture?width=200&height=200';
global $wpdb;
global $post;
$title = $user_name; // get the inputted title
$content = $_POST['content']; // get the inputted content
$categorie = $_POST['cat']; // get the category selected by user
$zombies = $_POST['zombies'];
$kliks = $_POST['klik'];
$timess = $_POST['times'];
$name = $_POST['namn'];
if( 'POST' == $_SERVER['REQUEST_METHOD'] ) { // if form has been submitted
$my_post = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 2,
'post_category' => array(2),
);
$my_post = wp_insert_post($my_post);
add_post_meta($my_post, 'Zombies', $zombies);
add_post_meta($my_post, 'klik', $kliks);
add_post_meta($my_post, 'times', $timess);
add_post_meta($my_post, 'namn', $name);
add_post_meta($my_post, 'profile_photo', $user_img_url);
wp_redirect( home_url() );
# if $verifica is not empty, then we don't insert the post and we display a message
}
?>
Your question is not quite clear to me but if you want to query a post by it's title then you can use get_page_by_title() function as given below
$post = get_page_by_title( $_POST['post_title'], OBJECT, 'post' );
To get a custom meta field you can use get_post_meta() function as given below
$meta_value = get_post_meta($post->ID, 'field_name', true);
Then compare and update the meta value you can use, for example,
if( $_POST['custom_meta_field'] > $meta_value )
{
// Update the meta value
update_post_meta( $post->id, 'field_name', $meta_value );
}
The update_post_meta() function is being used to update the custom meta field.
Update: (Based on comment)
You can use following to get the post that is available by Facebook ID
$post = get_page_by_title( $_POST['facebook_id'], OBJECT, 'post' );
Also if the meta field is time string (12:10 am) then you have to convert it to timestamp/numeric value before you compare it, like,
$meta_value = strtotime(get_post_meta($post->ID, 'field_name', true));
So, it'll become something like 1363493400 and you can compare like
if( $_POST['custom_meta_field'] > $meta_value ){ ... }
In this case your custom_meta_field should be also a timestamp/numeric value or you have to convert it using strtotime() function just like $meta_value has been converted.

Resources