Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Dennis Eitner
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dennis Eitner
Full Stack JavaScript Techdegree Graduate 25,644 Points

Function executed in every page but should only execute on a specific page

I have created a submenu page with a custom function that should export a csv file when clicking on it. If I return the function the function gets executed on every page. if i don't return the function, the csv export does not work.

I have no idea how to solve this. If anybody could help, would be great.

        add_action('admin_menu', 'register_my_shipping_export_page');

function register_my_shipping_export_page() {
add_submenu_page( 'woocommerce', 'Export list', 'Export List', 'manage_options', 'my-export-page', 'my_custom_export_page_callback' );


function my_custom_export_page_callback (){

$fileName = 'somefile.csv';

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");

$fh = @fopen( 'php://output', 'w' );

global $wpdb;
$query = "SELECT * FROM `{$wpdb->prefix}my_table`";
$results = $wpdb->get_results( $query, ARRAY_A );

$headerDisplayed = false;

foreach ( $results as $data ) {
// Add a header row if it hasn't been added yet
if ( !$headerDisplayed ) {
// Use the keys from $data as the titles
fputcsv($fh, array_keys($data));
$headerDisplayed = true;
}

// Put the data into the stream
fputcsv($fh, $data);
}
// Close the file
fclose($fh);
// Make sure nothing else is sent, our file is done
exit;

}

return my_custom_export_page_callback(); 

}
Jeremy Castanza
Jeremy Castanza
12,081 Points

I think your issue is related to the WP hierarchy. If you only want your function executed on a specific page, you could create a specific template for that page and pull the function from your functions.php file (assuming it's there) and put into into a page specific template (e.g. page-my-page-slug.php). For more info on how the hierarchy works, check out http://wphierarchy.com/