Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tradesouthwest/2332899a46a74a20e5b0635e2d1f37bb to your computer and use it in GitHub Desktop.
Save tradesouthwest/2332899a46a74a20e5b0635e2d1f37bb to your computer and use it in GitHub Desktop.
<?php
/**
* This code retrieves course data from an external API and displays it in the user's
* My Account area. A merchant has noticed that there's a delay when loading the page.
*
* 1) What changes would you suggest to reduce or remove that delay?
* 2) Is there any other code changes that you would make?
*/
//improvements
/**
* Retrieve API Course data to display on user My Account section.
*
* @param string $api_user_id User ID for API
* @param string $to_top Could be called from method
* @returns string $output Clean data to display as HTML
*
* @since 9.9.9
*/
public function add_my_courses_section() {
//If plugin method does not exists
$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) return; //Might be redundant as per calling _user_meta below
//$api_user_id could be a function inside the class $this->get_helpers()->api_use_id()
$api_user_id = get_user_meta( $current_user->ID,
'_external_api_user_id',
true
);
if ( ! $api_user_id ) return;
//Two known class properties - May not need validation
$courses = $this->get_api()->get_courses_assigned_to_user( $api_user_id );
$sso_link = $this->get_api()->get_sso_link( $api_user_id );
//$to_top = $this->get_helpers()->to_top_html(); (maybe use terniary check)
$to_top = '<a href="Apihead" title="' . esc_attr( 'back to top of chart', 'text-domain' ) . '">'
. esc_html__( 'Top', 'text-domain' ) . '</a>';
//$output
ob_start();
$str = "&#37;";
$percent_str = html_entity_decode($str);
echo '
<h2 class="marg-top-md">' . esc_html__( 'My Courses', 'text-domain' ) . '</h2>
<table>
<thead id="Apihead"><tr>
<th>' . esc_html__( 'Course Code', 'text-domain' ) . '</th>
<th>' . esc_html__( 'Course Title', 'text-domain' ) . '</th>
<th>' . esc_html__( 'Completion', 'text-domain' ) . '</th>
<th>' . esc_html__( 'Date Completed', 'text-domain' ) . '</th>
</tr></thead>
<tbody>';
foreach( $courses as $course ) :
echo
'<tr>
<td>' . __( $course['Code'] ) . '</td>
<td>' . __( $course['Name'] ) . '</td>
<td>' . __( $course['PercentageComplete'] ) . $percent_str . '</td>
<td>' . __( $course['DateCompleted'] ) . '</td>
</tr>';
endforeach;
echo
'</tbody>
<tfoot>
<tr>
<td colspan="4">. ' . $to_top . '</td>
</tr>
</tfoot>
</table>';
//Can GET be called at this point or not?
$active_course = ( empty ( $_GET['active_course'] ) ) ? '' : $_GET['active_course'];
printf( '<p><a href="%s" target="_blank" class="button %s">%s</a></p>',
$sso_link,
$active_course,
esc_html__( 'Course Login', 'text-domain' )
);
$output = ob_get_clean();
//or echo if called by action hook
return $output
//Maybe use wp_remote_retrieve_response_code() or equivalent
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment