Add a posts meta-value to the permalink/url in Wordpress - wordpress

I am trying to build a speaking URL for a custom post type in Wordpress storing event dates. I would like to have the following scheme for event-URLs:
/events/2013-12-24-christmas/ /events/2013-12-31-newyearseve/
The date is not the standard published date, it is instead a date stored in a meta-field: the date on which the event takes place.
I tried to achieve it with a snippet I used to rewrite another custom post type and it looked promising - but the only problem is: I can't get the post-id to query for the meta values :(
Here's the rewrite code so far:
function create_post_type_events {
[...custom-post-type...]
register_post_type('my_events', $args);
global $wp_rewrite;
$permalink_structure = '/events/2013-12-24-%my_events%';
$wp_rewrite->add_rewrite_tag("%my_events%", '([^/]+)', "my_events=");
$wp_rewrite->add_permastruct('my_events', $permalink_structure, false);
}
add_action('init', 'create_post_type_events');
The date is obviously hard-coded and needs to be replaced.
I tried $post, $wp_query, globalizing, get_queried_object()... nothing seems to help.
So, how (and is it actually possible?) can I get the post-ID for further querying?

Related

Using cpt and pass a variable using url

I want to create a nice readable permalink structure for my custom post type (CPT). My CPT "movie" has the following rewrite-slug movie/movie_name" (all works fine).
Now i want to add arg like this: movie/movie_name/arg and use arg in my template file as a php variable.
But obvious it lead to not-found-page. How can i achieve this target?
edit: i want it in FRIENDLY URL format, it means i dont want to use GET for this.
You may pass it like movie/movie_name?movie_arg=movie_value. It is will be available with $_GET['movie_arg']. Of course your need extra sanitization to handle this data.
To be able to read this in a WordPress way add params to a query_vars filter
function add_movie_arg_to_query_vars( $qvars ) {
$qvars[] = 'movie_arg';
return $qvars;
}
add_filter( 'query_vars', 'add_movie_arg_to_query_vars' );
Note: it should not be same as reserved WordPress query parameters
This way it will be available at your template with get_query_var('movie_arg')
print_r( get_query_var('movie_arg') ) // movie_value
More information here

Custom function error to produce a shortcode resulted in white screen of death

I followed the syntax the best I could to create a shortcode on execution, I got the wsod. Once removed, all was well. But I don't know what is wrong with my code. This code sits inside 'My Custom Functions', a plugin for wp.
In researching how to write a custom shortcode, I discovered instructions here: https://torquemag.io/2017/06/custom-shortcode/ My expertise is in mysql and use mostly plugins in our wordpress website. I am very limited with coding.
function last_updated_shortcode {
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM
qgotv.last_updated");
return $last_updated;
}
add_shortcode( 'last_updated', 'last_updated_shortcode' );
This shortcode should retrieve a max(datetime value) from a db table so it can be displayed on a page. The query works. The qgotv db is separate from the wordpress db but can be accessed through wp.
Two issues I can see, one is that you have a syntax error in your function. When defining a function in PHP, you need to include the arguments parenthesis: function my_function(){ /* Do Stuff */ }. Also, you probably need to reference the $wpdb with the global keyword.
You can read up a bit on the $wpdb class as well as creating your own functions.
This should get you sorted out:
add_shortcode( 'last_updated', 'last_updated_shortcode' );
function last_updated_shortcode(){
global $wpdb;
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM qgotv.last_updated");
return $last_updated;
}

Wordpress - Build one Page to use URL to pull data from REST API

I'd appreciate any advice, resources or assistance with this issue.
I want to be able to have part of my Wordpress site where I can parse the URL and then use those values to populate the page with content from another API.
For example:
server.zz/weather/Sydney%20Australia
server.zz/weather/Houston%20Texas
Where I could write a Plugin which would intercept these requests, be able to extract the end of the URLs, and then call another API to get the data to then merge into a Template to be presented to the visitor.
I know that there are Custom Post Types, but I wasn't sure if they were the best solution for this usage case.
As I said, any advice or suggestions would be appreciated.
I found the solution to this problem by using add_rewrite_rule(), add_rewrite_endpoint(), and flush_rewrite_rule().
For the example I provided earlier, I created the following code in a Plugin.
// Define the URL Rewrite Rules
function crw_rewrite_urls(){
add_rewrite_rule(
'^weather/(.+)$' ,
'index.php?weather_location=$matches[1]' ,
'top'
);
add_rewrite_endpoint('weather_location', EP_ROOT);
flush_rewrite_rules();
}
add_action('init', 'crw_rewrite_urls');
// Initialise the Query Variable
function crw_query_var( $vars ) {
$vars[] = 'weather_location';
return $vars;
}
// Check for the Variable and Display Content as needed
function crw_handler() {
global $wp_query;
if ( isset( $wp_query->query_vars['weather_location'] ) ) {
// Call the API, fill the Template here
}
return;
}
add_action('template_redirect', 'crw_handler');

WordPress ACF Save Post function, need it only to fire when the page saved is custom post type. Or, if field is present?

I am trying to manipulate the my_acf_save_post function to do some maths and update a field with the resulting number. This part is working, the fields full_market_price and example_price are used to work out calculated_price.
I did this some days ago but have now run in a problem whenever trying to save a page, or post that doesn't need this function, and doesn't contain the ACF fields. So every section of the website rather than just the 1 that requires this maths. It results in various errors and I can't save the pages properly.
How can I make this code snippet only work if the page being saved is within custom post type? So it won't break the other pages?
I'm trying something using
if (is_single() && is_post_type('nameofposttype'))
however I can't seem to get it right, PHP not my strongest! Is a better way to ask if the fields does not exist, then do nothing?
Many thanks for any help or ideas,
function my_acf_save_post( $post_id ) {
// get values
$fmp = get_field('full_market_price');
$saPercent = get_field('example_price');
// do something
$examplePrice = ($fmp / 100) * $saPercent;
update_field('calculated_price', $examplePrice, $post_id);
}
add_action('acf/save_post', 'my_acf_save_post', 20);
I just ran into a similar issue. I would do something like:
function my_acf_save_post ($post_id) {
// If not CPT, exit
if (get_post_type($post_id) != 'nameofposttype') {
return;
}
// Remainder of code
...
}
add_action('acf/save_post', 'my_acf_save_post', 20);

WP Shortcodes not being added

I was creating a wordpress plugin where the user enters in some information, and is able to generate shortcodes. I was not quite sure where the shortcodes are supposed to go - my current setup is class-based, and I want to be able to create a shortcode when an AJAX request is being made, and is successful. The following two methods are in the same file in the class.
This method gets called via the admin-ajax.php file:
public static function processAjax()
{
global $wpdb;
$event_data = $_POST['obj'];
$event_title = $event_data[0];
$event_subdomain = $event_data[1];
$result_events = $wpdb->get_results("SELECT * FROM wp_shortcode_plugin WHERE subdomain = '{$event_subdomain}'", OBJECT);
if (sizeof($result_events)>0) {
echo "duplicate";
} else {
add_shortcode($event_subdomain, 'getEmbed');
$results = $wpdb->insert('wp_shortcode_plugin', array("event_name"=>$event_title, "subdomain"=>$event_subdomain));
echo json_encode($_POST['obj']);
}
die();
}
And here is my getEmbed() method that I would like to call.
public static function getEmbed()
{
return 'test';
}
It seems that the shortcodes are not being created, however. Am I missing something here? Also, is it possible to pass a value to the getEmbed function from the add_shortcode() method?
Instead of adding shortcode directly from AJAX, you should use update_option to store in the information for the shortcode to be loaded. If option doesn't exist, it will be created.
Than you will simple use wp_init hook to load up all of the shortcodes you need to load in the function.php file for the theme or plugin php file.
You should use get_option within the wp_init hook and check the values in there. You will need to have function(s) associated with the shortcodes, which can be autogenerated in php using create_function or you can route them through 1 function (defined in your php file) that will have the $atts and $content parameters defined and do whatever depending on the value of your get_option that you send to that function.
add_shortcode function should be defined within the wp_init hook, after checking the value of the get_option function. You will need to give your option a name and add to it via the ajax function. the option will most likely want to be an array, that wordpress will automatically serialize. Than you use that array returned from get_option to loop through the array of shortcodes, and call add_shortcode as many times as you need there. This requires setting up your option array so that it has a shortcode tag defined in each index of the array. I would, personally, make the shortcode tag the key of the array and all attributes of the shortcode, imo, would than be an array of that array.
Hope this helps you to get started on this.

Resources