Categories
WordPress

How to change database charset in WordPress wpdb

Sometime you would get database query results from wpdb with get_results in ????????.

global $wpdb;

$results = $wpdb->get_results("SELECT * FROM tables");
header('Content-Type: application/json;charset=utf-8');
echo wp_json_encode($results);

Although, the encodings of the database, table and the column are all set to utf8, that would not help!

I’ve found a simple solution by setting wpdb character encoding before get_results.

global $wpdb;
$wpdb->set_charset($wpdb->dbh, 'utf8');  // add this line

....

$results = $wpdb->get_results("SELECT * FROM tables");
header('Content-Type: application/json;charset=utf-8');
echo wp_json_encode($results);

I hope this help.

Ref. https://wordpress.stackexchange.com/questions/301822/how-do-i-change-database-charset-when-using-wpdb

Categories
Uncategorized

WordPress React Gutenberg

How this code will be looked when i call wp.element?

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

wp.element is basically a React wrapper. Your code can look like this if you use wp.element

const { Component, render } = wp.element;

class Clock extends Component {
...rest of the code
}

render(
  <Clock />,
  document.getElementById('root')
);

Or you can keep using React too as it already ships with WordPress, in which case set it as an external in webpack so it isn’t bundled with your build and instead takes it from the WP Core.

Hope this helps!

Ref: https://wordpress.org/support/topic/reactjs-in-wpwp-elemet/