Support » Plugin: WordPress Related Posts » Bug (and solution): Can’t save changes when editing related posts on frotnt end

  • A client’s website has been using this plugin for some time. Recently migrated their website, but the ability to save the manually selected related posts stopped working. The client had specified related posts for many of their posts, so they did not want to change plugins.

    After some time debugging the issue, I found this bug was caused by the website using HTTP while the ajax URL uses HTTPS. However, the browser only logs in to one protocol, so the ajax call thinks you are logged out.

    The fix required two things:

    1. Adding a “wp_ajax_norpiv_” hook so the ajax URL works on HTTP
    2. Overriding the _wp_rp_admin_ajax_url (and wp_ajax_url) variables in JavaScript so the protocol matches.

    I hope this may help improve the plugin!

    Here is the code that fixed our issue, which goes in functions.php:

    /*
    Fix "WordPress Related Posts" ajax_url not working because WordPress thinks we are logged out
    */
    if ( function_exists('wp_rp_update_related_posts_callback') ) {
    	// Allow ajax urls if wordpress thinks you are not logged in
    	add_action('wp_ajax_nopriv_rp_update_related_posts', 'wp_rp_update_related_posts_callback');
    	
    	// Also make ajax_url use same protocol in javascript variables
    	function fix_wp_rp_head_resources() {
    		$admin_ajax_url = admin_url('admin-ajax.php');
    		$wp_ajax_url = admin_url('admin-ajax.php');
    		$https = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 1 : 0;
    		
    		// Make admin-ajax use same protocol
    		if ( $https ) {
    			$admin_ajax_url = str_replace( 'http://', 'https://', $admin_ajax_url );
    			$wp_ajax_url = str_replace( 'http://', 'https://', $wp_ajax_url );
    		}else{
    			$admin_ajax_url = str_replace( 'https://', 'http://', $admin_ajax_url );
    			$wp_ajax_url = str_replace( 'https://', 'http://', $wp_ajax_url );
    		}
    		
    		?>
    <script type="text/javascript">
    // Fix wp related posts ajax url protocol:
    window._wp_rp_admin_ajax_url = <?php echo json_encode( $admin_ajax_url ); ?>;
    window._wp_rp_wp_ajax_url = <?php echo json_encode( $wp_ajax_url ); ?>;
    </script>
    		<?php
    	}
    	add_action('wp_head', 'fix_wp_rp_head_resources', 11);
    }
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Bug (and solution): Can’t save changes when editing related posts on frotnt end’ is closed to new replies.