exporting mysql using php is blocked by javascript - javascript

I am using the below php code to export from my mysql database:
<?php
require_once('connect.php');
$group = 1;//$_GET['group'];
$export = mysql_query ("SELECT * FROM relationship WHERE group_id = $group");
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
mysql_close($my_connection);
?>
I can download the file from my browser (chrome) if I simply run this php file.
However, the download does not show if I use a click button on another page and call below javascript to run this php file:
<script>
function export_data()
{alert(1);
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "export.php",
data: {group: localStorage.group_id},
dataType: "html",
success: function(response){
alert(response);
}
});alert(2);
}
</script>
Javascript will alert all the xls contents, but block the download.
How can I solve this?
Thanks in advance!

Why don't you just use window.location instead of AJAX ?
<script>
function export_data()
{
window.location='export.php';
}
</script>

You can remove JavaScript click even and direct create a link
Download
This will download file without referencing page on browser.

Related

JavaScript code doesn't run inside PHP in WP plugin

I read a few topics like "Javascript inside PHP doesn't work" but I couldn't find a solution. I have a WP plugin that sends emails when someone clicks on a button. Also when an email has been sent a PHP pop-up with confirmation appears. I think it's in the part where "wp_mail()" is. When an email was sent properly, I want to run some JS, right before PHP message. So I tried to do this outside PHP (first attempt) and through echo (second attempt below). I don't see these console logs. Also when I have this JS there, then this PHP alert doesn't show. When I remove it, it works. This code is run for sure because when I change the text in PHP alert message I see it. Also above this function is another function "add_action('wp_footer'..) and there is only JS, and this JS works, when I change something. I can't understand why it doesn't work there.
Function where I have problem:
function updateRequest()
{
$admin_email = get_option('admin_email');
$senderEmail = empty(trim(get_option('settings_page_sender_email'))) ? "no-reply#".$_SERVER['HTTP_HOST'] : get_option('settings_page_sender_email');
$order = wc_get_order($_POST['orderID']);
$title = empty(trim(get_option('settings_page_email_title')))?"“[UPDATE REQUEST]”":get_option('settings_page_email_title');
$recipient = $admin_email;
$subject = str_replace('[PRODUCTTITLE]', $_POST['productTitle'], $title);
$message = " ";
$headers = array(
'Content-Type: text/html; charset=UTF-8',
'From: '.$_POST['name'].' <'.$senderEmail.'>',
'Reply-To: '.$_POST['name'].' <'.$_POST['email'].'>'
);
if(wp_mail( $recipient, $subject, $message, $headers )){
?>
<script type="text/javascript">console.log("Data alert");</script>
<?php
echo'<script type="text/javascript">console.log("Data alert");</script>';
$confirmationTxt = empty(trim(get_option('settings_page_confirmation_text'))) ? "Request has been sent" : get_option('settings_page_confirmation_text');
wp_send_json_success($confirmationTxt , $status_code = null );
}else{
wp_send_json_error( "Something Went Wrong ...!", $status_code );
}
}
And this is the whole file
<?php
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
/**
* Currently plugin version.
* Start at version 1.0.0 and use SemVer - https://semver.org
* Rename this for your plugin and update it as you release new versions.
*/
define( 'VIRTUAL_PRODUCT_WOOCOMMERCE_UPDATE_REQUEST_VERSION', '1.0.0' );
// Define global constants
$plugin_data = get_file_data( __FILE__, array( 'name'=>'Plugin Name', 'version'=>'Version', 'text'=>'Text Domain' ) );
function VPWUR_constants( $constant_name, $value ) {
$constant_name_prefix = 'VPWUR_VERSION';
$constant_name = $constant_name_prefix . $constant_name;
if ( !defined( $constant_name ) )
define( $constant_name, $value );
}
VPWUR_constants( 'DIR', dirname( plugin_basename( __FILE__ ) ) );
VPWUR_constants( 'BASE', plugin_basename( __FILE__ ) );
VPWUR_constants( 'URL', plugin_dir_url( __FILE__ ) );
VPWUR_constants( 'PATH', plugin_dir_path( __FILE__ ) );
VPWUR_constants( 'SLUG', dirname( plugin_basename( __FILE__ ) ) );
VPWUR_constants( 'NAME', $plugin_data['name'] );
VPWUR_constants( 'VERSION', $plugin_data['version'] );
VPWUR_constants( 'TEXT', $plugin_data['text'] );
VPWUR_constants( 'PREFIX', '' );
VPWUR_constants( 'SETTINGS', '' );
/**
* The code that runs during plugin activation.
* This action is documented in includes/class-virtual-product-woocommerce-update-request-activator.php
*/
function activate_virtual_product_woocommerce_update_request() {
require_once plugin_dir_path( __FILE__ ) . 'includes/class-virtual-product-woocommerce-update-request-activator.php';
Virtual_Product_Woocommerce_Update_Request_Activator::activate();
}
/**
* The code that runs during plugin deactivation.
* This action is documented in includes/class-virtual-product-woocommerce-update-request-deactivator.php
*/
function deactivate_virtual_product_woocommerce_update_request() {
require_once plugin_dir_path( __FILE__ ) . 'includes/class-virtual-product-woocommerce-update-request-deactivator.php';
Virtual_Product_Woocommerce_Update_Request_Deactivator::deactivate();
}
register_activation_hook( __FILE__, 'activate_virtual_product_woocommerce_update_request' );
register_deactivation_hook( __FILE__, 'deactivate_virtual_product_woocommerce_update_request' );
/**
* The core plugin class that is used to define internationalization,
* admin-specific hooks, and public-facing site hooks.
*/
require plugin_dir_path( __FILE__ ) . 'includes/class-virtual-product-woocommerce-update-request.php';
/**
* Begins execution of the plugin.
*
* Since everything within the plugin is registered via hooks,
* then kicking off the plugin from this point in the file does
* not affect the page life cycle.
*
* #since 1.0.0
*/
function run_virtual_product_woocommerce_update_request() {
$plugin = new Virtual_Product_Woocommerce_Update_Request();
$plugin->run();
}
run_virtual_product_woocommerce_update_request();
add_action('wp_footer', function ()
{
echo "<br><br><br><br><br>";
echo 'Hamza';
if (shortcode_exists( 'UpdateRequstBtn' )) {
echo "<pre>Shortcode Registered</pre>";
}
});
/* Adding CSS style for public */
function my_enqueued_assets() {
wp_enqueue_style('virtual-product-woocommerce-update-request-public', plugin_dir_url(__FILE__) . '/public/css/virtual-product-woocommerce-update-request-public.css', '', time());
}
add_action('wp_enqueue_scripts', 'my_enqueued_assets');
function updateRequstBtn($atts) {
global $product, $woocommerce;
$html = "";
if (method_exists($product, 'get_id')) {
$id = $product->get_id();
}
$atts = shortcode_atts( array(
'id' => #$id,
), $atts, 'UpdateRequstBtn' );
// echo $atts['id'];
$product = new WC_Product($atts['id']);
if (empty($atts['id']) || $atts['id'] == 0 || !get_current_user_id()) {
return;
}
$order = has_bought_items([$atts['id']]);
if (!$order) {
// you can remove this no orders from here ... just remove the text "No Orders"
return "";
}
// // print_r($order->get_billing_email());
$btnText = empty(trim(get_option( 'settings_page_btn_txt' ))) ? "Update Request": get_option( 'settings_page_btn_txt' );
$html .= '<div class="woocommerce-product-gallery vpwur-button-div">';
$html .= '<a href="javascript:void(0)" onclick="updateRequest(this);" class="button vpwur-button-a"
data-email="'.$order->get_billing_email().'"
data-orderID="'.$order->get_id().'"
data-productTitle="'.get_the_title($atts['id']).'"
data-name="'.$order->get_billing_first_name()." ".$order->get_billing_last_name().'"
>'. $btnText .'</a>';
$html .= '<p class="vpwur-sending-txt-pre">Trwa wysylanie zadania...</div>';
return $html;
}
add_shortcode( 'UpdateRequstBtn', 'UpdateRequstBtn' );
/**
* Show number list of downloadable files for group product
*
* #param array $download
* #return void
*/
/*function prefix_downloads_column_download_file( array $download ) {
// print_r($download);
echo '<a href="', $download['download_url'], '" download>', $download['download_name'], '</a>';
// do_shortcode( '[UpdateRequstBtn id="'.$download['product_id'].'"]' );
// echo shortcode_exists( 'UpdateRequstBtn' );
}
add_action( 'woocommerce_account_downloads_column_download-file', 'prefix_downloads_column_download_file' );*/
add_action( 'woocommerce_account_downloads_column_update-request', function( $download ) {
if (get_option( 'enable_download_page_btn' )) {
echo do_shortcode( '[UpdateRequstBtn id="'.$download['product_id'].'"]' );
}
} );
add_filter( 'woocommerce_account_downloads_columns', function( $columns ) {
if (get_option( 'enable_download_page_btn' )) {
// Add Column
$columnName = empty(trim(get_option( 'download_page_column_name' ))) ? "Update Request": get_option( 'download_page_column_name' );
$columns['update-request'] = $columnName;
}
// Return
return $columns;
} );
add_action('wp_footer', function ()
{
?>
<script type="text/javascript">
function updateRequest(e) {
var data = {
'action': 'updateRequest',
'name': e.dataset.name, // We pass php values differently!
'email': e.dataset.email, // We pass php values differently!
'orderID': e.dataset.orderid, // We pass php values differently!
'productTitle': e.dataset.producttitle, // We pass php values differently!
};
// console.log(data);
jQuery.post('<?php echo admin_url('admin-ajax.php') ?>', data, function(response) {
alert(response.data);
// alert('Got this from the server: ' + response);
});
/* Changing CSS for sending email message under button */
const confirmTxtsList = Array.from(document.getElementsByClassName('vpwur-sending-txt-pre'));
confirmTxtsList.forEach(p => {
p.classList.remove('vpwur-sending-txt-pre');
p.classList.add('vpwur-sending-txt-on');
});
}
</script>
<?php
});
add_action('wp_ajax_updateRequest','updateRequest');
add_action('wp_ajax_nopriv_updateRequest','updateRequest');
function updateRequest()
{
$admin_email = get_option('admin_email');
$senderEmail = empty(trim(get_option('settings_page_sender_email'))) ? "no-reply#".$_SERVER['HTTP_HOST'] : get_option('settings_page_sender_email');
$order = wc_get_order($_POST['orderID']);
$title = empty(trim(get_option('settings_page_email_title')))?"“[UPDATE REQUEST]”":get_option('settings_page_email_title');
$recipient = $admin_email;
$subject = str_replace('[PRODUCTTITLE]', $_POST['productTitle'], $title);
$message = " ";
$headers = array(
'Content-Type: text/html; charset=UTF-8',
'From: '.$_POST['name'].' <'.$senderEmail.'>',
'Reply-To: '.$_POST['name'].' <'.$_POST['email'].'>'
);
if(wp_mail( $recipient, $subject, $message, $headers )){
?>
<script type="text/javascript">console.log("Data alert");</script>
<?php
echo'<script type="text/javascript">console.log("Data alert");</script>';
$confirmationTxt = empty(trim(get_option('settings_page_confirmation_text'))) ? "Request has been sent" : get_option('settings_page_confirmation_text');
wp_send_json_success($confirmationTxt , $status_code = null );
}else{
wp_send_json_error( "Something Went Wrong ...!", $status_code );
}
}
function has_bought_items($prod_arr=[]) {
$bought = false;
// Set HERE ine the array your specific target product IDs
// $prod_arr = array( '21', '67' );
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed' // Only orders with status "completed"
) );
foreach ( $customer_orders as $customer_order ) {
// Updated compatibility with WooCommerce 3+
$order_id = method_exists( $customer_order, 'get_id' ) ? $customer_order->get_id() : $customer_order->id;
$order = wc_get_order( $customer_order );
// Iterating through each current customer products bought in the order
foreach ($order->get_items() as $item) {
// WC 3+ compatibility
if ( version_compare( WC_VERSION, '3.0', '<' ) )
$product_id = $item['product_id'];
else
$product_id = $item->get_product_id();
// Your condition related to your 2 specific products Ids
if ( in_array( $product_id, $prod_arr ) )
$bought = $order;
}
}
// return "true" if one the specifics products have been bought before by customer
return $bought;
}
PS there is no "?>" at the end, as this is main plugin file and must be part of some other file probably.

How to get php echo result in javascript

I have my php file on a server that retrieves data from my database.
<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row_number = 0;
while($row = $result->fetch_assoc()) {
$row_number++;
echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Unfortunately, I do not know how to receive data from a php file using javascript.
I would like the script in javascript to display the received data in the console in browser.
The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server.
I've tried to use ajax, unfortunately without positive results.
(the php script works as expected).
JS(not working):
$.ajax({
url: 'https://myserver.com/file.php',
type: 'POST',
success: function(response) {
console.log(response);
}
});
The code within the loop is a little screwy
$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]
that suggests a very oddly named querystring parameter which is not, I think, what was intended.
Instead, perhaps try like this:
<?php
$servername = 'myHosting';
$username = 'myUserName';
$password = 'MyPassword';
$dbname = 'myDbName';
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) {
die( 'Connection failed: ' . $conn->connect_error );
}
$sql = 'select `id`, `name`, `description` from `tablename`;';
$result = $conn->query($sql);
if( $result->num_rows > 0 ) {
$row_number = 0;
while( $row = $result->fetch_assoc() ) {
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
} else {
echo '0 results';
}
$conn->close();
?>
A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* emulate the remote script */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';
$res=$db->query( $sql );
$row_number=0;
while( $row=$res->fetch_assoc() ){
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Basic Ajax & db interaction</title>
<script>
$( document ).ready( function(){
$.ajax({
url: location.href,
type: 'POST',
success: function( response ) {
console.log( response );
document.getElementById('out').innerHTML=response;
}
});
} );
</script>
</head>
<body>
<div id='out'></div>
</body>
</html>
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["id"])) {
$id = $_POST["id"];
if (is_int($id)) {
$query = "select * from alumni_users where userId = '$id' ";
$update = mysqli_query($mysqli, $query);
$response = array();
while($row = mysqli_fetch_array($update)){
.......
fill your response here
}
echo json_encode($response);
}
}
break;
}
}
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter
then in your ajax:
function getdetails() {
var value = $('#userId').val();
return $.ajax({
type: "POST",
url: "getInfo.php",
data: {id: value}
})
}
call it like this:
getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})
Hope it helps

echo javascript in php not interpreted

I had to redirect the visitor to another page if something went wrong. Header location couldn't work because there is already some things displayed so I only have the choice to use javascript. Here is a piece of my PHP code :
add_action('frm_field_input_html', 'getDoctypes');
function getDoctypes($field, $echo = true){
$url = 'http://ff/interface/iface.php';
$html = '';
if ($field['id'] == get_id_from_key_frm('doctype')){
$data = array('action' => 'getDoctypes');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'timeout' => 30,
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$return = file_get_contents($url, false, $context);
$doctypes = json_decode($return);
if ($return === FALSE || isset($doctypes -> code)){
$wpBaseUrl = site_url();
echo "<script>window.location = '$wpBaseUrl/error-connection-interface/' </script>";
}else{
$html = ">";
foreach ($doctypes as $code => $name){
$html .= "<option value=\"$code\">$name</option>";
}
}
}
if ($echo)
echo $html;
return $html;
}
The problem is when $return === FALSE, instead of executing the script, it just display "window.location = 'http://my_ip/error-connection-interface/'" into the HTML
Any ideas ?
Thanks in advance

Error in decode json code

i need help with decode json
if($loop->have_posts()) :
$json = '{';
$json .= '
"api_status":1,
"api_message":"success",
"data": [';
while ( $loop->have_posts() ) : $loop->the_post();
$json .= '{
"id":'.get_the_ID().',
"post_name":"'.get_the_title().'"
},
';
endwhile;
$json = substr($json,0,-1);
$json .= ']}';
echo $json;
endif;
break;
}
my error is
in the last } i have still , so i need to remove it.
but i dont know how ?
someone help me ?
As mentioned in the comments, json_encode is the way to go.
$toEncode = array(
"api_status" => 1,
"api_message" => "success",
"data" => array()
);
while ($loop->have_posts()) {
$loop->the_post();
array_push($toEncode["data"], array(
"id" => get_the_ID(),
"post_name" => get_the_title()
));
}
echo json_encode($toEncode);
However, I do not quite understand how your system for posts work. Are you using some type of iterator?
You can use php function json_decode / encode:
JSON_DECODE
JSON_ENCODE
f.ex.
json_decode($variable, true);
json_encode($variable, true);
use rtrim($json, ","); to remove last comma from json output
if($loop->have_posts()) :
$json = '{';
$json .= '
"api_status":1,
"api_message":"success",
"data": [';
while ( $loop->have_posts() ) : $loop->the_post();
$json .= '{
"id":'.get_the_ID().',
"post_name":"'.get_the_title().'"
},';
endwhile;
$json = rtrim($json, ",");
$json .= ']}';
echo $json;
endif;
break;
}
another way
$json = new array();
if($loop->have_posts()) :
$json["api_status"] = 1,
$json["api_message"] = "success",
$json["data"] = new array();
while ( $loop->have_posts() ) : $loop->the_post();
$json["data"]["id"] = get_the_ID();
$json["data"]["post_name"] = get_the_title();
endwhile;
echo json_encode($json);
endif;
break;
}

WP archive with custom field filter

Hope someone can help.
I'm currently building a directory, and have used ACF to populate some data. I am now working toward building a filter for the options selected within one of my ACF groups, The field group is called 'Member Directory' the field I'm specifically targeting is: 'wha_service_offered'.
There are four checkbox values within this:
supplier : Supplier
manufacturer : Manufacturer
installer : Installer
consultant : Consultant
I have used checkbox as more than one option may apply to a member.
I have set up functions.php with the following:
// Filter Services
add_action('pre_get_posts', 'my_pre_get_posts');
function my_pre_get_posts( $query )
{
// validate
if( is_admin() )
{
return $query;
}
// allow the url to alter the query
// eg: http://www.website.com/members?wha_service_offered=installer
// eg: http://www.website.com/members?wha_service_offered=consultant
if( isset($_GET['wha_service_offered']) )
{
$query->set('meta_key', 'wha_service_offered');
$query->set('meta_value', $_GET['wha_service_offered']);
}
// always return
return $query;
}
And within my archive-members.php
php
<div id="search-services">
<?php
$field = get_field_object('wha_service_offered');
$values = isset($_GET['wha_service_offered']) ? explode(',', $_GET['wha_service_offered']) : array();
?>
<ul>
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
<li>
<input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
</li>
<?php endforeach; ?>
</ul>
</div>
javascript
<script type="text/javascript">
(function($) {
$('#search-services').on('change', 'input[type="checkbox"]', function(){
// vars
var $ul = $(this).closest('ul'),
vals = [];
$ul.find('input:checked').each(function(){
vals.push( $(this).val() );
});
vals = vals.join(",");
window.location.replace('<?php echo home_url('members'); ?>?wha_service_offered=' + vals);
console.log( vals );
});
})(jQuery);
</script>
When the filter is used it simply returns a blank page.
I would be grateful if anyone could point out where I have made an error.
Thanks.
--
So debug returns:
Declaration of Custom_Nav_Walker::start_el() should be compatible with
Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php on line 169
Warning: Cannot modify header information - headers already sent by (output started at
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php:169) in
/Applications/MAMP/htdocs/website.com/wp-includes/pluggable.php on line 1179
The offending item is:
class Custom_Nav_Walker extends Walker_Nav_Menu {
function check_current($classes) {
return preg_match('/(current[-_])/', $classes);
}
function start_el(&$output, $item, $depth, $args) {
global $wp_query;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$slug = sanitize_title($item->title);
$id = apply_filters('nav_menu_item_id', 'menu-' . $slug, $item, $args);
$id = strlen($id) ? '' . esc_attr( $id ) . '' : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$classes = array_filter($classes, array(&$this, 'check_current'));
if ($custom_classes = get_post_meta($item->ID, '_menu_item_classes', true)) {
foreach ($custom_classes as $custom_class) {
$classes[] = $custom_class;
}
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
$class_names = $class_names ? ' class="' . $id . ' ' . esc_attr($class_names) . '"' : ' class="' . $id . '"';
$output .= $indent . '<li' . $class_names . '>';
$attributes = ! empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
$attributes .= ! empty($item->target) ? ' target="' . esc_attr($item->target ) .'"' : '';
$attributes .= ! empty($item->xfn) ? ' rel="' . esc_attr($item->xfn ) .'"' : '';
$attributes .= ! empty($item->url) ? ' href="' . esc_attr($item->url ) .'"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
}
I'm not understanding why the walker nav would affect the filter?
--
Corrected line 169 error by amending the following from:
function start_el(&$output, $item, $depth, $args) {
To
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {}
I now have the following errors:
Notice: Undefined index: choices in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Which relates to:
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>

Categories

Resources