Wordpress: do something only for new posts and not for updated ones - wordpress

Good morning,
I need a hook or something to call to separate new posts from updated ones.
I want to execute some code only for new posts... something like that:
add_action('publish_post', myfunction);
function myfunction( $post_id ){
if <new post> {
/* do something */
}
else {
/* do nothing */
}
}
I'm using WP v3.5
Any suggestion?

First, you want to use the draft_to_publish hook:
add_action('draft_to_published', 'my_function');
However, this can fire multiple times if a post is published, unpublished, and then published again. To ensure that your action only fires one time, set a custom meta element for the post at the end of your function. At the start of your function, check if you meta element is set and skip the action if it is.
--- Added ---
Here is a sample on how the repeat action protection would work (untested code - so might need a little work):
function my_function() {
$already_done = get_post_meta($post_id, 'do_once', true);
if(!$already_done) {
// Do what you need to do here
add_post_meta($post_id, 'do_once', 1, true);
}
}

Related

$wp_query is returning nothing

I have the following code in my plugin file:
// SET UP REWITE RULES FOR LISTING PERMALINKS //
function my_rewrite_tags() {
add_rewrite_tag('%listingId%', '([^&]+)');
}
add_action('init', 'my_rewrite_tags', 10, 0);
function my_rewrite_rules() {
add_rewrite_rule('^listing/([^/]*)/?','index.php?pagename=listing&listingId=$matches[1]','top');
}
add_action('init', 'my_rewrite_rules', 10, 0);
This idea is that I have a page called "Listing" with the permalink "listing" and I want to be able to have the listing's ID number after it (i.e., /listing/12345/)
I then have a shortcode running on the "Listing" page
// SHORTCODE FOR SINGLE LISTING PAGE //
function my_single_listing(){
ob_start();
include('templates/single-listing.php');
return ob_get_clean();
}
add_shortcode('listing','my_single_listing');
...and the first thing it does is try to get that listing ID with the code:
$listingId = $wp_query->query_vars['listingId'];
I've done this with other plugins I've written in the past, but in this case it's decided to not work. In fact, if I enter the code:
print_r($wp_query);
I get absolutely nothing returned from it at all. (All other content on the page is displaying fine though.)
Any ideas?
Your issue with $wp_query being blank might be due to it not being accessed as a global variable. Prefacing it with a global declaration will allow it to access the global query:
global $wp_query;
print_r( $wp_query )
The issue with the listing ID not being picked up has to do with it not being declared as a possible custom query var. WordPress requires you to declare them before it loads them into the global wp_query for the page (presumably for security). $_GET was able to access them since that bypasses WordPress and just uses it with PHP.
function so_71685702_add_query_vars( $query_vars ) {
$query_vars[] = 'listingId';
return $qvars;
}
add_filter( 'query_vars', 'so_71685702_add_query_vars' );
Once you've got that, $wp_query->query_vars( 'listingid' ) should return a value.
Here's the query_vars hook information page, and the get_query_var hook information page which might be useful for further reading - might cover some things you'll run into based on the way you're setting up custom rewrites and query vars.

Replace Wordpress URL domain in HTML output (for SEO optimisation) [duplicate]

WordPress has great filter support for getting at all sorts of specific bits of content and modifying it before output. Like the_content filter, which lets you access the markup for a post before it's output to the screen.
I'm trying to find a catch-all filter that gives me one last crack at modifying the final markup in its entirety before output.
I've browsed the list of filters a number of times, but nothing jumps out at me:
https://codex.wordpress.org/Plugin_API/Filter_Reference
Anyone know of one?
WordPress doesn't have a "final output" filter, but you can hack together one. The below example resides within a "Must Use" plugin I've created for a project.
Note: I haven't tested with any plugins that might make use of the "shutdown" action.
The plugin works by iterating through all the open buffer levels, closing them and capturing their output. It then fires off the "final_output" filter, echoing the filtered content.
Sadly, WordPress performs almost the exact same process (closing the open buffers), but doesn't actually capture the buffer for filtering (just flushes it), so additional "shutdown" actions won't have access to it. Because of this, the below action is prioritized above WordPress's.
wp-content/mu-plugins/buffer.php
<?php
/**
* Output Buffering
*
* Buffers the entire WP process, capturing the final output for manipulation.
*/
ob_start();
add_action('shutdown', function() {
$final = '';
// We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
// that buffer's output into the final output.
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
// Apply any filters to the final output
echo apply_filters('final_output', $final);
}, 0);
An example of hooking into the final_output filter:
<?php
add_filter('final_output', function($output) {
return str_replace('foo', 'bar', $output);
});
Edit:
This code uses anonymous functions, which are only supported in PHP 5.3 or newer. If you're running a website using PHP 5.2 or older, you're doing yourself a disservice. PHP 5.2 was released in 2006, and even though Wordpress (edit: in WP version < 5.2) STILL supports it, you should not use it.
The question is may be old, but I have found a better way to do it:
function callback($buffer) {
// modify buffer here, and then return the updated code
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');
Explanation
This plugin code registers two actions – buffer_start and buffer_end.
buffer_start is executed at the end of the header section of the html. The parameter, the callback function, is called at the end of the output buffering. This occurs at the footer of the page, when the second registered action, buffer_end, executes.
The callback function is where you add your code to change the value of the output (the $buffer variable). Then you simply return the modified code and the page will be displayed.
Notes
Be sure to use unique function names for buffer_start, buffer_end, and callback, so they do not conflict with other functions you may have in plugins.
AFAIK, there is no hook for this, since the themes uses HTML which won't be processed by WordPress.
You could, however, use output buffering to catch the final HTML:
<?php
// example from php.net
function callback($buffer) {
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html><body>
<p>It's like comparing apples to oranges.</p>
</body></html>
<?php ob_end_flush(); ?>
/* output:
<html><body>
<p>It's like comparing oranges to oranges.</p>
</body></html>
*/
#jacer, if you use the following hooks, the header.php also gets included.
function callback($buffer) {
$buffer = str_replace('replacing','width',$buffer);
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
add_action('after_setup_theme', 'buffer_start');
add_action('shutdown', 'buffer_end');
I was using the top solution of this post (by kfriend) for a while. It uses an mu-plugin to buffer the whole output.
But this solution breaks the caching of wp-super-cache and no supercache-files are generated when i upload the mu-plugin.
So: If you are using wp-super-cache, you can use the filter of this plugin like this:
add_filter('wp_cache_ob_callback_filter', function($buffer) {
$buffer = str_replace('foo', 'bar', $buffer);
return $buffer;
});
Modified https://stackoverflow.com/users/419673/kfriend answer.
All code will be on functions.php. You can do whatever you want with the html on the "final_output" filter.
On your theme's 'functions.php'
//we use 'init' action to use ob_start()
add_action( 'init', 'process_post' );
function process_post() {
ob_start();
}
add_action('shutdown', function() {
$final = '';
// We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
// that buffer's output into the final output.
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
// Apply any filters to the final output
echo apply_filters('final_output', $final);
}, 0);
add_filter('final_output', function($output) {
//this is where changes should be made
return str_replace('foo', 'bar', $output);
});
You might try looking in the wp-includes/formatting.php file. For example, the wpautop function.
If you are looking for doing something with the entire page, look at the Super Cache plugin. That writes the final web page to a file for caching. Seeing how that plug-in works may give you some ideas.
Indeed there was a discusussion recently on the WP-Hackers mailing list about the topic of full page modification and it seems the consensus was that output buffering with ob_start() etc was the only real solution. There was also some discussion about the upsides and downsides of it: http://groups.google.com/group/wp-hackers/browse_thread/thread/e1a6f4b29169209a#
To summarize: It works and is the best solution when necessary (like in the WP-Supercache plugin) but slows down overall speeds because your content isn't allowed to be sent to the browser as its ready, but instead has to wait for the full document to be rendered (for ob_end() ) before it can be processed by you and sent to the browser.
To simplify previous answers, just use this in functions.php:
ob_start();
add_action('shutdown', function () {
$html = ob_get_clean();
// ... modify $html here
echo $html;
}, 0);
I've been testing the answers here now for a while, and since the cache breaking thing is still an issue, I came up with a slightly different solution. In my tests no page cache broke. This solution has been implemented into my WordPress plugin OMGF (which has 50k+ users right now) and no issues with page cache breaking has been reported.
First, we start an output buffer on template redirect:
add_action('template_redirect', 'maybe_buffer_output', 3);
function maybe_buffer_output()
{
/**
* You can run all sorts of checks here, (e.g. if (is_admin()) if you don't want the buffer to start in certain situations.
*/
ob_start('return_buffer');
}
Then, we apply our own filter to the HTML.
function return_buffer($html)
{
if (!$html) {
return $html;
}
return apply_filters('buffer_output', $html);
}
And then we can hook into the output by adding a filter:
add_filter('buffer_output', 'parse_output');
function parse_output($html)
{
// Do what you want. Just don't forget to return the $html.
return $html;
}
Hope it helps anyone.
I have run into problems with this code, as I end up with what seems to be the original source for the page so that some plugins has no effect on the page. I am trying to solve this now - I haven't found much info regarding best practises for collecting the output from WordPress.
Update and solution:
The code from KFRIEND didnt work for me as this captures unprocessed source from WordPress, not the same output that ends up in the browser in fact. My solution is probably not elegant using a globals variable to buffer up the contents - but at least I know get the same collected HTML as is delivered to the browser. Could be that different setups of plugins creates problems but thanks to code example by Jacer Omri above I ended up with this.
This code is in my case located typically in functions.php in theme folder.
$GLOBALS['oldschool_buffer_variable'] = '';
function sc_callback($data){
$GLOBALS['final_html'] .= $data;
return $data;
}
function sc_buffer_start(){
ob_start('sc_callback');
}
function sc_buffer_end(){
// Nothing makes a difference in my setup here, ob_get_flush() ob_end_clean() or whatever
// function I try - nothing happens they all result in empty string. Strange since the
// different functions supposedly have very different behaviours. Im guessing there are
// buffering all over the place from different plugins and such - which makes it so
// unpredictable. But that's why we can do it old school :D
ob_end_flush();
// Your final HTML is here, Yeeha!
$output = $GLOBALS['oldschool_buffer_variable'];
}
add_action('wp_loaded', 'sc_buffer_start');
add_action('shutdown', 'sc_buffer_end');
If you want to modify the output, you can use template_include:
add_filter( 'template_include', static function ( $template ) {
if ( basename( $template ) === 'foo-template.php' ) {
echo str_replace( 'foo', 'bar', file_get_contents( $template ) );
}
return null;
} );
If instead you want to override the output completely, you can use the action template_redirect.
add_action( 'template_redirect', static function () {
wp_head();
echo 'My output.';
wp_footer();
exit;
} );

Track WordPress changes on post edit/save

I would like to know how to run a function when a meta information of a custom post type is changed.
For example, I have a radio box associated with a custom post type. And made it with metaboxes, and when I change the option, I would like to run a function.
How would I do that?
Originally in OP's question.
I think I found what I wanted
function do_my_stuff($post_ID) {
//do my stuff here;
return $post_ID;
}
add_action('save_post', 'do_my_stuff');
Wordpress: executing function when saving or editing post
But is it possible to track what changes were made?
Yup, did it with your help diggy, but had to change something.
function do_my_stuff($post_ID) {
$newvalue = $_POST['my_metabox_value'];
echo $newvalue;
$oldvalue= get_post_meta($post_id, 'my_metabox_value', true );
echo $oldvalue;
}
add_action('pre_post_update', 'do_my_stuff');

Close Overlay and Redirect to Custom URL on Save-Node in Drupal 7?

When my node form saves, I want to close the admin overlay and redirect to a custom URL that is stored with the node. hook_form_alter() is setting $form['#redirect'] but I think that would only work with no admin overlay.
I have never used it before myself, but i think you can call the overlay_close_dialog(...) function from your hook_submit
See http://api.drupal.org/api/drupal/modules--overlay--overlay.module/function/overlay_close_dialog/7 for more info
Kept googling my way here as well.. this is the working solution:
Inside your form:
$form['somebutton']['#submit'] = array('your_custom_callback');
Add a custom callback
function your_custom_callback($form, &$form_state) {
//redirect users to Drupal.org
$url = "http://drupal.org";
if (module_exists('overlay') && overlay_get_mode() == 'child') {
unset($_GET['destination']);
overlay_close_dialog($url, array('external' => TRUE));
$form_state['redirect'] = FALSE;
} else {
$form_state['redirect'] = $url;
}
}
Kept googling my way here and wanted to post a final solution that worked for me on Drupal 7 (got here thanks to jakraska's suggestion). First use hook_form_FORM_ID_alter() to hook into the specific form you want to alter
/**
* Implementation of hook_form_FORM_ID_alter()
*
**/
function mymodule_form_FORM_ID_alter(&$form, &$form_state) {
$form['#submit'][] = 'mymodule_callback';
}
Then write your callback that will render the page. In my case I simply wanted to close the overlay, so that's why I used the $form_state['redirect'] = FALSE;
function mymodule_callback(&$form, &$form_state) {
// Form API will re-render the current page and pass the redirect information to the overlay JavaScript
overlay_close_dialog();
// stay on the same page after all submit callbacks have been processed.
$form_state['redirect'] = FALSE;
}
If you want to redirect to another path,
See https://api.acquia.com/api/drupal/modules!overlay!overlay.module/function/overlay_form_submit/7 - I believe that should get you there.
Make sure to use $form_state['rebuild'] = TRUE; inside your hook_submit function, otherwise it would not close overlay after form is submitted.

Wordpress: executing function when saving or editing post

This is what I'm trying to accomplish:
If I'm adding or editing post I want to run a function that puts post_id, all the custom field values and category ids to some other db table I've created.
I just want to know how to execute this function and how to get the values.
Put the following in your functions.php file of your theme. It will run on both save as well as well update. Since you have the post ID, you can do whatever you want.
function do_my_stuff($post_ID) {
//do my stuff here;
return $post_ID;
}
add_action('save_post', 'do_my_stuff');
This was firing twice.
function do_my_stuff($post_ID) {
//do my stuff here;
return $post_ID;
}
add_action('save_post', 'do_my_stuff');
Adding
if (wp_is_post_revision($post_ID)) return;
to suppress revision solved it for me. Maybe you want to suppress more...
// API request
if (REST_REQUEST) return;
// autosave
if (wp_is_post_autosave($post_ID)) return;

Resources