qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
240,679 | <p>here is my option page:
<pre><code>class PriceListOptions {
private $price_list_options_options;
public function __construct() {
add_action( 'admin_menu', array( $this, 'price_list_options_add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'price_list_options_page_init' ) );
}
public function price_list_options_add_plugin_page() {
add_theme_page(
'Price list options', // page_title
'Price list options', // menu_title
'manage_options', // capability
'price-list-options', // menu_slug
array( $this, 'price_list_options_create_admin_page' ) // function
);
}
public function price_list_options_create_admin_page() {
$this->price_list_options_options = get_option( 'price_list_options_option_name' ); ?>
<div class="wrap">
<h2>Price list options</h2>
<p>set price list options</p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields( 'price_list_options_option_group' );
do_settings_sections( 'price-list-options-admin' );
submit_button();
?>
</form>
</div>
<?php }
public function price_list_options_page_init() {
register_setting(
'price_list_options_option_group', // option_group
'price_list_options_option_name', // option_name
array( $this, 'price_list_options_sanitize' ) // sanitize_callback
);
add_settings_section(
'price_list_options_setting_section', // id
'Settings', // title
array( $this, 'price_list_options_section_info' ), // callback
'price-list-options-admin' // page
);
add_settings_field(
'price_list_section_title_0', // id
'Price list section title', // title
array( $this, 'price_list_section_title_0_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_list_section_subtitle_1', // id
'Price list section subtitle', // title
array( $this, 'price_list_section_subtitle_1_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_list_section_subtitle_2', // id
'Price list section subtitle', // title
array( $this, 'price_list_section_subtitle_2_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_title_3', // id
'Price plan 1 title', // title
array( $this, 'price_plan_1_title_3_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_currency_4', // id
'Price currency', // title
array( $this, 'price_currency_4_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_price_5', // id
'Price plan 1 price', // title
array( $this, 'price_plan_1_price_5_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_period_6', // id
'Price plan 1 period', // title
array( $this, 'price_plan_1_period_6_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_info_7', // id
'Price plan 1 info', // title
array( $this, 'price_plan_1_info_7_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_features_8', // id
'Price plan 1 features', // title
array( $this, 'price_plan_1_features_8_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_button_title_9', // id
'Price plan 1 button title', // title
array( $this, 'price_plan_1_button_title_9_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_button_url_10', // id
'Price plan 1 button URL', // title
array( $this, 'price_plan_1_button_url_10_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_panel_color_11', // id
'Price plan 1 panel color', // title
array( $this, 'price_plan_1_panel_color_11_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
}
public function price_list_options_sanitize($input) {
$sanitary_values = array();
$defaults = array (
'price_list_section_title_0' => 'test',
'do_extra_thing' => false
);
if ( isset( $input['price_list_section_title_0'] ) ) {
$sanitary_values['price_list_section_title_0'] = wp_parse_args(sanitize_text_field( $input['price_list_section_title_0'], $defaults ));
}
if ( isset( $input['price_list_section_subtitle_1'] ) ) {
$sanitary_values['price_list_section_subtitle_1'] = sanitize_text_field( $input['price_list_section_subtitle_1'] );
}
if ( isset( $input['price_list_section_subtitle_2'] ) ) {
$sanitary_values['price_list_section_subtitle_2'] = sanitize_text_field( $input['price_list_section_subtitle_2'] );
}
if ( isset( $input['price_plan_1_title_3'] ) ) {
$sanitary_values['price_plan_1_title_3'] = sanitize_text_field( $input['price_plan_1_title_3'] );
}
if ( isset( $input['price_currency_4'] ) ) {
$sanitary_values['price_currency_4'] = sanitize_text_field( $input['price_currency_4'] );
}
if ( isset( $input['price_plan_1_price_5'] ) ) {
$sanitary_values['price_plan_1_price_5'] = sanitize_text_field( $input['price_plan_1_price_5'] );
}
if ( isset( $input['price_plan_1_period_6'] ) ) {
$sanitary_values['price_plan_1_period_6'] = sanitize_text_field( $input['price_plan_1_period_6'] );
}
if ( isset( $input['price_plan_1_info_7'] ) ) {
$sanitary_values['price_plan_1_info_7'] = sanitize_text_field( $input['price_plan_1_info_7'] );
}
if ( isset( $input['price_plan_1_features_8'] ) ) {
$sanitary_values['price_plan_1_features_8'] = esc_textarea( $input['price_plan_1_features_8'] );
}
if ( isset( $input['price_plan_1_button_title_9'] ) ) {
$sanitary_values['price_plan_1_button_title_9'] = sanitize_text_field( $input['price_plan_1_button_title_9'] );
}
if ( isset( $input['price_plan_1_button_url_10'] ) ) {
$sanitary_values['price_plan_1_button_url_10'] = sanitize_text_field( $input['price_plan_1_button_url_10'] );
}
if ( isset( $input['price_plan_1_panel_color_11'] ) ) {
$sanitary_values['price_plan_1_panel_color_11'] = sanitize_text_field( $input['price_plan_1_panel_color_11'] );
}
return $sanitary_values;
}
public function price_list_options_section_info() {
}
public function price_list_section_title_0_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_list_section_title_0]" id="price_list_section_title_0" value="%s">',
isset( $this->price_list_options_options['price_list_section_title_0'] ) ? esc_attr( $this->price_list_options_options['price_list_section_title_0']) : ''
);
}
public function price_list_section_subtitle_1_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_list_section_subtitle_1]" id="price_list_section_subtitle_1" value="%s">',
isset( $this->price_list_options_options['price_list_section_subtitle_1'] ) ? esc_attr( $this->price_list_options_options['price_list_section_subtitle_1']) : ''
);
}
public function price_list_section_subtitle_2_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_list_section_subtitle_2]" id="price_list_section_subtitle_2" value="%s">',
isset( $this->price_list_options_options['price_list_section_subtitle_2'] ) ? esc_attr( $this->price_list_options_options['price_list_section_subtitle_2']) : ''
);
}
public function price_plan_1_title_3_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_title_3]" id="price_plan_1_title_3" value="%s">',
isset( $this->price_list_options_options['price_plan_1_title_3'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_title_3']) : ''
);
}
public function price_currency_4_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_currency_4]" id="price_currency_4" value="%s">',
isset( $this->price_list_options_options['price_currency_4'] ) ? esc_attr( $this->price_list_options_options['price_currency_4']) : ''
);
}
public function price_plan_1_price_5_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_price_5]" id="price_plan_1_price_5" value="%s">',
isset( $this->price_list_options_options['price_plan_1_price_5'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_price_5']) : ''
);
}
public function price_plan_1_period_6_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_period_6]" id="price_plan_1_period_6" value="%s">',
isset( $this->price_list_options_options['price_plan_1_period_6'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_period_6']) : ''
);
}
public function price_plan_1_info_7_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_info_7]" id="price_plan_1_info_7" value="%s">',
isset( $this->price_list_options_options['price_plan_1_info_7'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_info_7']) : ''
);
}
public function price_plan_1_features_8_callback() {
printf(
'<textarea class="large-text" rows="5" name="price_list_options_option_name[price_plan_1_features_8]" id="price_plan_1_features_8">%s</textarea>',
isset( $this->price_list_options_options['price_plan_1_features_8'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_features_8']) : ''
);
}
public function price_plan_1_button_title_9_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_button_title_9]" id="price_plan_1_button_title_9" value="%s">',
isset( $this->price_list_options_options['price_plan_1_button_title_9'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_button_title_9']) : ''
);
}
public function price_plan_1_button_url_10_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_button_url_10]" id="price_plan_1_button_url_10" value="%s">',
isset( $this->price_list_options_options['price_plan_1_button_url_10'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_button_url_10']) : ''
);
}
public function price_plan_1_panel_color_11_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_panel_color_11]" id="price_plan_1_panel_color_11" value="%s">',
isset( $this->price_list_options_options['price_plan_1_panel_color_11'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_panel_color_11']) : ''
);
}
}
// Parse incomming $args into an array and merge it with $defaults
if ( is_admin() )
$price_list_options = new PriceListOptions();
/*
* Retrieve this value with:
* $price_list_options_options = get_option( 'price_list_options_option_name' ); // Array of All Options
* $price_list_section_title_0 = $price_list_options_options['price_list_section_title_0']; // Price list section title
* $price_list_section_subtitle_1 = $price_list_options_options['price_list_section_subtitle_1']; // Price list section subtitle
* $price_list_section_subtitle_2 = $price_list_options_options['price_list_section_subtitle_2']; // Price list section subtitle
* $price_plan_1_title_3 = $price_list_options_options['price_plan_1_title_3']; // Price plan 1 title
* $price_currency_4 = $price_list_options_options['price_currency_4']; // Price currency
* $price_plan_1_price_5 = $price_list_options_options['price_plan_1_price_5']; // Price plan 1 price
* $price_plan_1_period_6 = $price_list_options_options['price_plan_1_period_6']; // Price plan 1 period
* $price_plan_1_info_7 = $price_list_options_options['price_plan_1_info_7']; // Price plan 1 info
* $price_plan_1_features_8 = $price_list_options_options['price_plan_1_features_8']; // Price plan 1 features
* $price_plan_1_button_title_9 = $price_list_options_options['price_plan_1_button_title_9']; // Price plan 1 button title
* $price_plan_1_button_url_10 = $price_list_options_options['price_plan_1_button_url_10']; // Price plan 1 button URL
* $price_plan_1_panel_color_11 = $price_list_options_options['price_plan_1_panel_color_11']; // Price plan 1 panel color
*/
?>
</code></pre>
| [
{
"answer_id": 240754,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p>Missing GET request variables are sometimes a symptom of improper rewrite rules in the web-server's configurati... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240679",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103709/"
] | here is my option page:
```
class PriceListOptions {
private $price_list_options_options;
public function __construct() {
add_action( 'admin_menu', array( $this, 'price_list_options_add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'price_list_options_page_init' ) );
}
public function price_list_options_add_plugin_page() {
add_theme_page(
'Price list options', // page_title
'Price list options', // menu_title
'manage_options', // capability
'price-list-options', // menu_slug
array( $this, 'price_list_options_create_admin_page' ) // function
);
}
public function price_list_options_create_admin_page() {
$this->price_list_options_options = get_option( 'price_list_options_option_name' ); ?>
<div class="wrap">
<h2>Price list options</h2>
<p>set price list options</p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields( 'price_list_options_option_group' );
do_settings_sections( 'price-list-options-admin' );
submit_button();
?>
</form>
</div>
<?php }
public function price_list_options_page_init() {
register_setting(
'price_list_options_option_group', // option_group
'price_list_options_option_name', // option_name
array( $this, 'price_list_options_sanitize' ) // sanitize_callback
);
add_settings_section(
'price_list_options_setting_section', // id
'Settings', // title
array( $this, 'price_list_options_section_info' ), // callback
'price-list-options-admin' // page
);
add_settings_field(
'price_list_section_title_0', // id
'Price list section title', // title
array( $this, 'price_list_section_title_0_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_list_section_subtitle_1', // id
'Price list section subtitle', // title
array( $this, 'price_list_section_subtitle_1_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_list_section_subtitle_2', // id
'Price list section subtitle', // title
array( $this, 'price_list_section_subtitle_2_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_title_3', // id
'Price plan 1 title', // title
array( $this, 'price_plan_1_title_3_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_currency_4', // id
'Price currency', // title
array( $this, 'price_currency_4_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_price_5', // id
'Price plan 1 price', // title
array( $this, 'price_plan_1_price_5_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_period_6', // id
'Price plan 1 period', // title
array( $this, 'price_plan_1_period_6_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_info_7', // id
'Price plan 1 info', // title
array( $this, 'price_plan_1_info_7_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_features_8', // id
'Price plan 1 features', // title
array( $this, 'price_plan_1_features_8_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_button_title_9', // id
'Price plan 1 button title', // title
array( $this, 'price_plan_1_button_title_9_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_button_url_10', // id
'Price plan 1 button URL', // title
array( $this, 'price_plan_1_button_url_10_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
add_settings_field(
'price_plan_1_panel_color_11', // id
'Price plan 1 panel color', // title
array( $this, 'price_plan_1_panel_color_11_callback' ), // callback
'price-list-options-admin', // page
'price_list_options_setting_section' // section
);
}
public function price_list_options_sanitize($input) {
$sanitary_values = array();
$defaults = array (
'price_list_section_title_0' => 'test',
'do_extra_thing' => false
);
if ( isset( $input['price_list_section_title_0'] ) ) {
$sanitary_values['price_list_section_title_0'] = wp_parse_args(sanitize_text_field( $input['price_list_section_title_0'], $defaults ));
}
if ( isset( $input['price_list_section_subtitle_1'] ) ) {
$sanitary_values['price_list_section_subtitle_1'] = sanitize_text_field( $input['price_list_section_subtitle_1'] );
}
if ( isset( $input['price_list_section_subtitle_2'] ) ) {
$sanitary_values['price_list_section_subtitle_2'] = sanitize_text_field( $input['price_list_section_subtitle_2'] );
}
if ( isset( $input['price_plan_1_title_3'] ) ) {
$sanitary_values['price_plan_1_title_3'] = sanitize_text_field( $input['price_plan_1_title_3'] );
}
if ( isset( $input['price_currency_4'] ) ) {
$sanitary_values['price_currency_4'] = sanitize_text_field( $input['price_currency_4'] );
}
if ( isset( $input['price_plan_1_price_5'] ) ) {
$sanitary_values['price_plan_1_price_5'] = sanitize_text_field( $input['price_plan_1_price_5'] );
}
if ( isset( $input['price_plan_1_period_6'] ) ) {
$sanitary_values['price_plan_1_period_6'] = sanitize_text_field( $input['price_plan_1_period_6'] );
}
if ( isset( $input['price_plan_1_info_7'] ) ) {
$sanitary_values['price_plan_1_info_7'] = sanitize_text_field( $input['price_plan_1_info_7'] );
}
if ( isset( $input['price_plan_1_features_8'] ) ) {
$sanitary_values['price_plan_1_features_8'] = esc_textarea( $input['price_plan_1_features_8'] );
}
if ( isset( $input['price_plan_1_button_title_9'] ) ) {
$sanitary_values['price_plan_1_button_title_9'] = sanitize_text_field( $input['price_plan_1_button_title_9'] );
}
if ( isset( $input['price_plan_1_button_url_10'] ) ) {
$sanitary_values['price_plan_1_button_url_10'] = sanitize_text_field( $input['price_plan_1_button_url_10'] );
}
if ( isset( $input['price_plan_1_panel_color_11'] ) ) {
$sanitary_values['price_plan_1_panel_color_11'] = sanitize_text_field( $input['price_plan_1_panel_color_11'] );
}
return $sanitary_values;
}
public function price_list_options_section_info() {
}
public function price_list_section_title_0_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_list_section_title_0]" id="price_list_section_title_0" value="%s">',
isset( $this->price_list_options_options['price_list_section_title_0'] ) ? esc_attr( $this->price_list_options_options['price_list_section_title_0']) : ''
);
}
public function price_list_section_subtitle_1_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_list_section_subtitle_1]" id="price_list_section_subtitle_1" value="%s">',
isset( $this->price_list_options_options['price_list_section_subtitle_1'] ) ? esc_attr( $this->price_list_options_options['price_list_section_subtitle_1']) : ''
);
}
public function price_list_section_subtitle_2_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_list_section_subtitle_2]" id="price_list_section_subtitle_2" value="%s">',
isset( $this->price_list_options_options['price_list_section_subtitle_2'] ) ? esc_attr( $this->price_list_options_options['price_list_section_subtitle_2']) : ''
);
}
public function price_plan_1_title_3_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_title_3]" id="price_plan_1_title_3" value="%s">',
isset( $this->price_list_options_options['price_plan_1_title_3'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_title_3']) : ''
);
}
public function price_currency_4_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_currency_4]" id="price_currency_4" value="%s">',
isset( $this->price_list_options_options['price_currency_4'] ) ? esc_attr( $this->price_list_options_options['price_currency_4']) : ''
);
}
public function price_plan_1_price_5_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_price_5]" id="price_plan_1_price_5" value="%s">',
isset( $this->price_list_options_options['price_plan_1_price_5'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_price_5']) : ''
);
}
public function price_plan_1_period_6_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_period_6]" id="price_plan_1_period_6" value="%s">',
isset( $this->price_list_options_options['price_plan_1_period_6'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_period_6']) : ''
);
}
public function price_plan_1_info_7_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_info_7]" id="price_plan_1_info_7" value="%s">',
isset( $this->price_list_options_options['price_plan_1_info_7'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_info_7']) : ''
);
}
public function price_plan_1_features_8_callback() {
printf(
'<textarea class="large-text" rows="5" name="price_list_options_option_name[price_plan_1_features_8]" id="price_plan_1_features_8">%s</textarea>',
isset( $this->price_list_options_options['price_plan_1_features_8'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_features_8']) : ''
);
}
public function price_plan_1_button_title_9_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_button_title_9]" id="price_plan_1_button_title_9" value="%s">',
isset( $this->price_list_options_options['price_plan_1_button_title_9'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_button_title_9']) : ''
);
}
public function price_plan_1_button_url_10_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_button_url_10]" id="price_plan_1_button_url_10" value="%s">',
isset( $this->price_list_options_options['price_plan_1_button_url_10'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_button_url_10']) : ''
);
}
public function price_plan_1_panel_color_11_callback() {
printf(
'<input class="regular-text" type="text" name="price_list_options_option_name[price_plan_1_panel_color_11]" id="price_plan_1_panel_color_11" value="%s">',
isset( $this->price_list_options_options['price_plan_1_panel_color_11'] ) ? esc_attr( $this->price_list_options_options['price_plan_1_panel_color_11']) : ''
);
}
}
// Parse incomming $args into an array and merge it with $defaults
if ( is_admin() )
$price_list_options = new PriceListOptions();
/*
* Retrieve this value with:
* $price_list_options_options = get_option( 'price_list_options_option_name' ); // Array of All Options
* $price_list_section_title_0 = $price_list_options_options['price_list_section_title_0']; // Price list section title
* $price_list_section_subtitle_1 = $price_list_options_options['price_list_section_subtitle_1']; // Price list section subtitle
* $price_list_section_subtitle_2 = $price_list_options_options['price_list_section_subtitle_2']; // Price list section subtitle
* $price_plan_1_title_3 = $price_list_options_options['price_plan_1_title_3']; // Price plan 1 title
* $price_currency_4 = $price_list_options_options['price_currency_4']; // Price currency
* $price_plan_1_price_5 = $price_list_options_options['price_plan_1_price_5']; // Price plan 1 price
* $price_plan_1_period_6 = $price_list_options_options['price_plan_1_period_6']; // Price plan 1 period
* $price_plan_1_info_7 = $price_list_options_options['price_plan_1_info_7']; // Price plan 1 info
* $price_plan_1_features_8 = $price_list_options_options['price_plan_1_features_8']; // Price plan 1 features
* $price_plan_1_button_title_9 = $price_list_options_options['price_plan_1_button_title_9']; // Price plan 1 button title
* $price_plan_1_button_url_10 = $price_list_options_options['price_plan_1_button_url_10']; // Price plan 1 button URL
* $price_plan_1_panel_color_11 = $price_list_options_options['price_plan_1_panel_color_11']; // Price plan 1 panel color
*/
?>
``` | Missing GET request variables are sometimes a symptom of improper rewrite rules in the web-server's configuration files. In the case of Apache, rewrites are most often implemented using the [`mod_rewrite`](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) module's directives in the WordPress installation's directory-level `.htaccess` configuration file - however, a faulty rewrite rule could also be present in higher-level configuration files (directory, vhost, primary configuration, etc.).
By default, WordPress routes every request for anything except existing files and directories to `index.php` using a configuration similar to the following:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
There are two modifications that will cause these directives to drop the querystring in the process of rewriting the request:
* The [discard querystring flag](http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsd). This is added to the square brackets at the end of a `RewriteRule` directive as either `QSD` or `qsdiscard`. If this flag is present for *either* of the `RewriteRule` directives in the configuration above, the querystring will be discarded for virtually every request handled by WordPress. For example:
```
RewriteRule ^index\.php$ - [L,QSD]
```
* Any use of a `?` in a `RewriteRule` directive's substitution string (without the [append querystring flag](http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa)). Specifying *any* querystring (even a single `?` without any subsequent key/value pairs) in the substitution will result in the rewrite completely replacing the original querystring. For example:
```
RewriteRule . /index.php? [L]
```
or
```
RewriteRule . /index.php?foo=bar [L]
```
If it is desireable to append a custom GET variable to every rewrite, the append querystring flag can be specified in the brackets as `QSA` or `qsappend` in order to merge the querystring in the substitution with the original querystring instead of completely overwriting it:
```
RewriteRule . /index.php?foo=bar [L,QSA]
``` |
240,682 | <p>I have set up a custom loop to display featured products at the top of their relevant category pages.</p>
<p>but now I would like to go about removing featured products from the regular loop below, which is using the standard woocommerce code to display products,</p>
<p>Any help would be greatly appreciated</p>
<p><a href="http://onthesquareauctions.com/index.php/product-category/emporium/furniture/chairs-emporium/" rel="nofollow noreferrer">http://onthesquareauctions.com/index.php/product-category/emporium/furniture/chairs-emporium/</a>
<a href="https://i.stack.imgur.com/FidYe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FidYe.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 240754,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p>Missing GET request variables are sometimes a symptom of improper rewrite rules in the web-server's configurati... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103636/"
] | I have set up a custom loop to display featured products at the top of their relevant category pages.
but now I would like to go about removing featured products from the regular loop below, which is using the standard woocommerce code to display products,
Any help would be greatly appreciated
<http://onthesquareauctions.com/index.php/product-category/emporium/furniture/chairs-emporium/>
[](https://i.stack.imgur.com/FidYe.png) | Missing GET request variables are sometimes a symptom of improper rewrite rules in the web-server's configuration files. In the case of Apache, rewrites are most often implemented using the [`mod_rewrite`](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) module's directives in the WordPress installation's directory-level `.htaccess` configuration file - however, a faulty rewrite rule could also be present in higher-level configuration files (directory, vhost, primary configuration, etc.).
By default, WordPress routes every request for anything except existing files and directories to `index.php` using a configuration similar to the following:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
There are two modifications that will cause these directives to drop the querystring in the process of rewriting the request:
* The [discard querystring flag](http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsd). This is added to the square brackets at the end of a `RewriteRule` directive as either `QSD` or `qsdiscard`. If this flag is present for *either* of the `RewriteRule` directives in the configuration above, the querystring will be discarded for virtually every request handled by WordPress. For example:
```
RewriteRule ^index\.php$ - [L,QSD]
```
* Any use of a `?` in a `RewriteRule` directive's substitution string (without the [append querystring flag](http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa)). Specifying *any* querystring (even a single `?` without any subsequent key/value pairs) in the substitution will result in the rewrite completely replacing the original querystring. For example:
```
RewriteRule . /index.php? [L]
```
or
```
RewriteRule . /index.php?foo=bar [L]
```
If it is desireable to append a custom GET variable to every rewrite, the append querystring flag can be specified in the brackets as `QSA` or `qsappend` in order to merge the querystring in the substitution with the original querystring instead of completely overwriting it:
```
RewriteRule . /index.php?foo=bar [L,QSA]
``` |
240,695 | <p>I am tryping to fetch random posts list in single.php above footer.
Titles of the post displaying randomly and are unique in <code><li></code> but the excerpt is same for every post title (i.e., same excerpt of post content 'single.php').</p>
<p>First tried this:</p>
<pre><code> <ul class="random-list">
<?php $posts = get_posts('orderby=rand&numberposts=12'); foreach($posts as $post) { ?>
<li class="col-xs-6 col-sm-3"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?><br></a>
</li>
<?php } ?>
</ul>
</code></pre>
<p>Second try:</p>
<pre><code><ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><p><?php the_excerpt(); ?></p></li>
<?php endforeach; ?>
</ul>
</code></pre>
| [
{
"answer_id": 240696,
"author": "Sladix",
"author_id": 27423,
"author_profile": "https://wordpress.stackexchange.com/users/27423",
"pm_score": 1,
"selected": false,
"text": "<p>You are trying to use the_title() and the_excerpt() functions outside the <a href=\"https://codex.wordpress.or... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102355/"
] | I am tryping to fetch random posts list in single.php above footer.
Titles of the post displaying randomly and are unique in `<li>` but the excerpt is same for every post title (i.e., same excerpt of post content 'single.php').
First tried this:
```
<ul class="random-list">
<?php $posts = get_posts('orderby=rand&numberposts=12'); foreach($posts as $post) { ?>
<li class="col-xs-6 col-sm-3"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?><br></a>
</li>
<?php } ?>
</ul>
```
Second try:
```
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><p><?php the_excerpt(); ?></p></li>
<?php endforeach; ?>
</ul>
``` | You are trying to use the\_title() and the\_excerpt() functions outside the [wordpress loop](https://codex.wordpress.org/The_Loop), therefore, they will not work.
I suggest you try something like :
```
$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$query = new WP_Query($args);
while($query->have_posts()){
$query->the_post();
// the_excerpt() will now work as expected
}
``` |
240,701 | <p>I'm using an <code><input></code> tag that stores the values of multiple attachment image ids and it's not working.</p>
<p>Can anyone tell me where the problem is?</p>
<pre><code><input type="hidden" name="jfiler-items-exclude-imgid" value="["4602","4603"]">
if (isset($_POST['jfiler-items-exclude-imgid'])) {
$att_ids = $_POST['jfiler-items-exclude-imgid'];
$att_id = explode(',', $att_ids);
foreach ($att_id as $atts_id){
wp_delete_attachment($att_ids);
}
</code></pre>
| [
{
"answer_id": 240696,
"author": "Sladix",
"author_id": 27423,
"author_profile": "https://wordpress.stackexchange.com/users/27423",
"pm_score": 1,
"selected": false,
"text": "<p>You are trying to use the_title() and the_excerpt() functions outside the <a href=\"https://codex.wordpress.or... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240701",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103723/"
] | I'm using an `<input>` tag that stores the values of multiple attachment image ids and it's not working.
Can anyone tell me where the problem is?
```
<input type="hidden" name="jfiler-items-exclude-imgid" value="["4602","4603"]">
if (isset($_POST['jfiler-items-exclude-imgid'])) {
$att_ids = $_POST['jfiler-items-exclude-imgid'];
$att_id = explode(',', $att_ids);
foreach ($att_id as $atts_id){
wp_delete_attachment($att_ids);
}
``` | You are trying to use the\_title() and the\_excerpt() functions outside the [wordpress loop](https://codex.wordpress.org/The_Loop), therefore, they will not work.
I suggest you try something like :
```
$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);
$query = new WP_Query($args);
while($query->have_posts()){
$query->the_post();
// the_excerpt() will now work as expected
}
``` |
240,708 | <p>I am currently using the .htaccess file in cPanel to password protect my Wordpress website. There are a list of whitelisted IP addresses that can bypass the login form. </p>
<p>I would like to whitelist a page, but I don't have a .php or .html file to whitelist. It is a page within Wordpress, so I realize I may have to find a plugin or another way to do this. I don't want to have to manually password protect literally every single page just so I can have one page open to the public, so... there must be a way to do this. </p>
<p>If anyone can help out, it'd be greatly appreciated!</p>
<p>Thanks!</p>
| [
{
"answer_id": 240718,
"author": "Greg McMullen",
"author_id": 36028,
"author_profile": "https://wordpress.stackexchange.com/users/36028",
"pm_score": 1,
"selected": false,
"text": "<p>If you are just wanting a simple \"login\" you could use <code>htpasswd</code> and <code>htaccess</code... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97431/"
] | I am currently using the .htaccess file in cPanel to password protect my Wordpress website. There are a list of whitelisted IP addresses that can bypass the login form.
I would like to whitelist a page, but I don't have a .php or .html file to whitelist. It is a page within Wordpress, so I realize I may have to find a plugin or another way to do this. I don't want to have to manually password protect literally every single page just so I can have one page open to the public, so... there must be a way to do this.
If anyone can help out, it'd be greatly appreciated!
Thanks! | If you are just wanting a simple "login" you could use `htpasswd` and `htaccess`. WordPress sites already have the `htaccess` in the main directory.
Add an `.htpasswd` file at the same level as your root HTML folder. Example:
```
.
├── public_html
| └── wordpress
| └── .htaccess
└── .htpasswd
```
Use a tool like [htpasswd generator](http://www.htaccesstools.com/htpasswd-generator/) to generate a username/password pair. Then add this to your `.htpasswd` file.
Find the path `$_SERVER["DOCUMENT_ROOT"]` may provide some insight for you.
Edit WP's `.htaccess`. After the `#END WORDPRESS#` add
```
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/www/mysite/.htpasswd
require valid-user
```
If you need more detailed instructions see [this post](https://www.zigpress.com/2014/09/22/password-protecting-an-entire-wordpress-site/).
However, this does not address your request about IP Validation. [This question](https://stackoverflow.com/questions/10419592/htaccess-htpasswd-bypass-if-at-a-certain-ip-address) on StackOverflow may address it.
You would update the `.htaccess` file to read
```
AuthUserFile /var/www/mysite/.htpasswd
AuthName "Please Log In"
AuthType Basic
require valid-user
Order allow,deny
Allow from xxx.xxx.xxx.xxx
satisfy any
``` |
240,741 | <p>The home page of my site is set to show the 9 latest posts (via the setting in the admin area), and then at the bottom I have the standard pagination links which allow visitors to view more posts. </p>
<p>I would like to have the home page (and only the home page) show 7 latest posts, but then on the subsequent pages - 2, 3, 4 etc have 9 posts showing. I also want the categories and archives to display 9 posts too.</p>
<p>All the methods I have tried so far either result in missing and duplicated posts, or I end up with an extra page showing in the pagination which results in a 404. </p>
<p><strong>So far I've tried variations of the answer posted here:</strong></p>
<p><a href="https://wordpress.stackexchange.com/questions/176347/pagination-returns-404-after-page-20">Pagination returns 404 after page 20</a></p>
<p><strong>And also here (Case #2: Conditional Offset):</strong></p>
<p><a href="https://wordpress.stackexchange.com/questions/124303/different-posts-per-page-setting-for-first-and-rest-of-the-paginated-pages">Different 'posts_per_page' setting for first, and rest of the paginated pages?</a></p>
<p>Neither seems to work for what I want to achieve, but I feel like I'm close to a solution and could be missing something obvious.</p>
<p>Here's the most recent version of the code I tried (added to functions.php), which resulted in too many pagination links showing (the last link caused a 404):</p>
<pre><code>function home_paged_offset( $query ) {
$ppp = get_option( 'posts_per_page' );
$first_page_ppp = 7;
$paged = $query->query_vars[ 'paged' ];
if( $query->is_home() && $query->is_main_query() ) {
if( !is_paged() ) {
$query->set( 'posts_per_page', $first_page_ppp );
} else {
$paged_offset = $first_page_ppp + ( ($paged - 2) * $ppp );
$query->set( 'offset', $paged_offset );
}
}
}
add_action( 'pre_get_posts', 'home_paged_offset' );
function home_adjust_paged_offset_pagination( $found_posts, $query ) {
$ppp = get_option( 'posts_per_page' );
$first_page_ppp = 7;
$paged = $query->query_vars[ 'paged' ];
if( $query->is_home() && $query->is_main_query() ) {
if( !is_paged() ) {
return( $found_posts );
} else {
return( $found_posts - ($first_page_ppp - $ppp) );
}
}
return $found_posts;
}
add_filter( 'found_posts', 'home_adjust_paged_offset_pagination', 10, 2 );
</code></pre>
| [
{
"answer_id": 240756,
"author": "Ahmed Fouad",
"author_id": 102371,
"author_profile": "https://wordpress.stackexchange.com/users/102371",
"pm_score": 2,
"selected": true,
"text": "<p>Ok this was really tricky. I have so far managed to work around it by lying to the WordPress global <cod... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69134/"
] | The home page of my site is set to show the 9 latest posts (via the setting in the admin area), and then at the bottom I have the standard pagination links which allow visitors to view more posts.
I would like to have the home page (and only the home page) show 7 latest posts, but then on the subsequent pages - 2, 3, 4 etc have 9 posts showing. I also want the categories and archives to display 9 posts too.
All the methods I have tried so far either result in missing and duplicated posts, or I end up with an extra page showing in the pagination which results in a 404.
**So far I've tried variations of the answer posted here:**
[Pagination returns 404 after page 20](https://wordpress.stackexchange.com/questions/176347/pagination-returns-404-after-page-20)
**And also here (Case #2: Conditional Offset):**
[Different 'posts\_per\_page' setting for first, and rest of the paginated pages?](https://wordpress.stackexchange.com/questions/124303/different-posts-per-page-setting-for-first-and-rest-of-the-paginated-pages)
Neither seems to work for what I want to achieve, but I feel like I'm close to a solution and could be missing something obvious.
Here's the most recent version of the code I tried (added to functions.php), which resulted in too many pagination links showing (the last link caused a 404):
```
function home_paged_offset( $query ) {
$ppp = get_option( 'posts_per_page' );
$first_page_ppp = 7;
$paged = $query->query_vars[ 'paged' ];
if( $query->is_home() && $query->is_main_query() ) {
if( !is_paged() ) {
$query->set( 'posts_per_page', $first_page_ppp );
} else {
$paged_offset = $first_page_ppp + ( ($paged - 2) * $ppp );
$query->set( 'offset', $paged_offset );
}
}
}
add_action( 'pre_get_posts', 'home_paged_offset' );
function home_adjust_paged_offset_pagination( $found_posts, $query ) {
$ppp = get_option( 'posts_per_page' );
$first_page_ppp = 7;
$paged = $query->query_vars[ 'paged' ];
if( $query->is_home() && $query->is_main_query() ) {
if( !is_paged() ) {
return( $found_posts );
} else {
return( $found_posts - ($first_page_ppp - $ppp) );
}
}
return $found_posts;
}
add_filter( 'found_posts', 'home_adjust_paged_offset_pagination', 10, 2 );
``` | Ok this was really tricky. I have so far managed to work around it by lying to the WordPress global `$wp_query`. Here is how.
In your theme's `functions.php` you can add these functions to show 7 posts on first page, and 9 posts on any other page.
Okay, that code works so far but you'll notice that the pagination is incorrect on first page. Why? This is because WordPress uses the posts per page on first page (which is 7) and get the number of pages by doing division like ( 1000 / 7 ) = total posts. But what we need is to make the pagination take into account that on next pages we'll show 9 posts per page, not 7. With filters, you cannot do this but if you add this hack to your template just before `the_posts_pagination()` function it'll work as you expect.
**The trick is to change the `max_num_pages` inside $wp\_query global variable to our custom value and ignore WP calculation during the pagination links display only for first page.**
```
global $wp_query;
// Needed for first page only
if ( ! $wp_query->is_paged ) {
$all_posts_except_fp = ( $wp_query->found_posts - 7 ); // Get us the found posts except those on first page
$wp_query->max_num_pages = ceil( $all_posts_except_fp / 9 ) + 1; // + 1 the first page we have containing 7 posts
}
```
And this is the code to put in functions.php to filter the query.
```
add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_query_offset(&$query) {
if ( ! $query->is_home() ) {
return;
}
$fp = 7;
$ppp = 9;
if ( $query->is_paged ) {
$offset = $fp + ( ($query->query_vars['paged'] - 2) * $ppp );
$query->set('offset', $offset );
$query->set('posts_per_page', $ppp );
} else {
$query->set('posts_per_page', $fp );
}
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
function myprefix_adjust_offset_pagination($found_posts, $query) {
$fp = 7;
$ppp = 9;
if ( $query->is_home() ) {
if ( $query->is_paged ) {
return ( $found_posts + ( $ppp - $fp ) );
}
}
return $found_posts;
}
``` |
240,743 | <p>I have a small filter below. It does a regular expression replace of a particular string when the user saves the draft.</p>
<p>However, using this filter causes the warning "The backup of this post in your browser is different from the version below."</p>
<p>Is there a way to 'tell' Wordpress not to display the warning when that filter runs?</p>
<p>To re-create:</p>
<ol>
<li><p>Create a draft post. </p></li>
<li><p>In the body, enter a line of text: </p>
<p>rcq[whatever] </p>
<p>eg. </p>
<p>rcqTestMsg </p></li>
<li><p>Save the draft. </p></li>
</ol>
<p>Here is the code.</p>
<p>UPDATE: WHAT I THINK IS GOING ON: I think that somehow this is triggering the autosave.js CheckPost() function which (apparently) compares the text on screen with the current saved version. Is there a way to disable the autosave or revision just when this filter is triggered? Or is there something in my code that is confusing the revision system?</p>
<p><pre><br>
function jchwebdev_rant_quote_question( $content ) {
global $post;
$pattern = '/rcq/';
$replacement = 'RC$1';
if ($post->post_status == 'draft') {
return preg_replace($pattern, $replacement, $content);
}
else
return $content;
}
add_filter( 'content_save_pre' , 'jchwebdev_rant_quote_question' , 10, 1);
</pre></p>
| [
{
"answer_id": 240780,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": -1,
"selected": false,
"text": "<p>The possible reason of getting warning can be solved from your <code>wp-config.php</code> file. Check if in ... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17248/"
] | I have a small filter below. It does a regular expression replace of a particular string when the user saves the draft.
However, using this filter causes the warning "The backup of this post in your browser is different from the version below."
Is there a way to 'tell' Wordpress not to display the warning when that filter runs?
To re-create:
1. Create a draft post.
2. In the body, enter a line of text:
rcq[whatever]
eg.
rcqTestMsg
3. Save the draft.
Here is the code.
UPDATE: WHAT I THINK IS GOING ON: I think that somehow this is triggering the autosave.js CheckPost() function which (apparently) compares the text on screen with the current saved version. Is there a way to disable the autosave or revision just when this filter is triggered? Or is there something in my code that is confusing the revision system?
```
function jchwebdev_rant_quote_question( $content ) {
global $post;
$pattern = '/rcq/';
$replacement = 'RC$1';
if ($post->post_status == 'draft') {
return preg_replace($pattern, $replacement, $content);
}
else
return $content;
}
add_filter( 'content_save_pre' , 'jchwebdev_rant_quote_question' , 10, 1);
``` | The way to avoid this error is to make sure the `wp-saving-post` cookie is being set to a value of `[post id]-saved`, as seen [here](https://github.com/WordPress/WordPress/blob/10970701d7fbcaf504dd7d35d0e75c5c2b0c2e52/wp-includes/js/autosave.js#L457). As you can see, if that occurs, then WordPress won't complain about the difference, because it then knows that the post was saved properly.
Also take a look at [this line](https://github.com/WordPress/WordPress/blob/a72be13ec0b57a2831d75540fd1892d1bd121f3b/wp-admin/post.php#L197) and note that WordPress [handles this for you](https://github.com/WordPress/WordPress/blob/a72be13ec0b57a2831d75540fd1892d1bd121f3b/wp-admin/post.php#L197) already. So the error you're seeing, it likely has to do with some mild cookie corruption in your browser.
I ran several tests with your plugin and I was unable to reproduce the issue that you reported. So my feeling is that you should clear all browser cookies for your domain and eliminate the possibility of corruption causing the problem. Also be sure to do a review of WordPress config settings related to cookie storage. If there's something wrong with cookie settings on your site, it may have an impact on the behavior that you're seeing when running tests against this.
Finally, check to be sure you're not filtering the content, and then immediately redirecting, or exiting the script, or doing something else that would prevent [this line](https://github.com/WordPress/WordPress/blob/a72be13ec0b57a2831d75540fd1892d1bd121f3b/wp-admin/post.php#L197) from running once your filter is applied. That too, may lead to the problem that you're seeing. |
240,744 | <p>I am trying to make a page that displays a <em><a href="https://codex.wordpress.org/Post_Types#Custom_Post_Types" rel="nofollow">Custom Post Type</a></em>.</p>
<p>I need for all post to be displayed twice. Once at a list of products and once as a modal. I am able to display the product list on the page but I can't get the second post query for the modals to work. </p>
<p><strong>Products page</strong>:</p>
<pre><code><div>
<main>
<?php
if ( have_posts() ) : ?>
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="archive-description">', '</div>' );
?>
</header> <!-- .page-header -->
<?php
/* Start the Loop */
$args = array( 'post_type' => 'kollektion' );
$loop = new WP_Query( $args );
if( $loop ->have_posts() ) :
while( $loop->have_posts() ) : $loop->the_post();
get_template_part( 'template-parts/content-kollektion', get_post_format() );
endwhile;
endif;
the_posts_navigation();
else :
get_template_part( 'template-parts/content-kollektion', 'none' );
endif;
wp_reset_postdata();
?>
</main> <!-- #main -->
</div> <!-- #primary -->
<!-- modal Kollektion 02 -->
<div class="modalDialog">
<section class="kollektion-slider">
<?php
rewind_posts();
/* Start the Loop */
$args = array( 'post_type' => 'kollektion' );
$loop = new WP_Query( $args );
if( $loop ->have_posts() ) :
while( $loop->have_posts() ) :
$loop->the_post();
get_template_part( 'template-parts/content-kollektion-modal', get_post_format() );
endwhile;
endif;
wp_reset_postdata();
?>
</section>
</div>
</code></pre>
<p><code>content-kollektion-modal.php</code>:</p>
<pre><code><div id="post-modal<?php the_ID(); ?>">
<div>
<a href="#close" title="Close" class="close">X</a>
<h2>Modal Box</h2>
<img src="<?php the_field('image_collection'); ?>" />
</div>
</div>
</code></pre>
| [
{
"answer_id": 240759,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>more than just resetting post data i would reset the whole query:</p>\n\n<pre><code> wp_reset_query(); // Re... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240744",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103751/"
] | I am trying to make a page that displays a *[Custom Post Type](https://codex.wordpress.org/Post_Types#Custom_Post_Types)*.
I need for all post to be displayed twice. Once at a list of products and once as a modal. I am able to display the product list on the page but I can't get the second post query for the modals to work.
**Products page**:
```
<div>
<main>
<?php
if ( have_posts() ) : ?>
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="archive-description">', '</div>' );
?>
</header> <!-- .page-header -->
<?php
/* Start the Loop */
$args = array( 'post_type' => 'kollektion' );
$loop = new WP_Query( $args );
if( $loop ->have_posts() ) :
while( $loop->have_posts() ) : $loop->the_post();
get_template_part( 'template-parts/content-kollektion', get_post_format() );
endwhile;
endif;
the_posts_navigation();
else :
get_template_part( 'template-parts/content-kollektion', 'none' );
endif;
wp_reset_postdata();
?>
</main> <!-- #main -->
</div> <!-- #primary -->
<!-- modal Kollektion 02 -->
<div class="modalDialog">
<section class="kollektion-slider">
<?php
rewind_posts();
/* Start the Loop */
$args = array( 'post_type' => 'kollektion' );
$loop = new WP_Query( $args );
if( $loop ->have_posts() ) :
while( $loop->have_posts() ) :
$loop->the_post();
get_template_part( 'template-parts/content-kollektion-modal', get_post_format() );
endwhile;
endif;
wp_reset_postdata();
?>
</section>
</div>
```
`content-kollektion-modal.php`:
```
<div id="post-modal<?php the_ID(); ?>">
<div>
<a href="#close" title="Close" class="close">X</a>
<h2>Modal Box</h2>
<img src="<?php the_field('image_collection'); ?>" />
</div>
</div>
``` | You can Query a lot of time in the same page and all the query that you execute will work perfect irrespective of the custom post type that you choose.
>
> Note: Once after you finish the Wp\_Query at the first time you need to `reset` the `Wp_Query` after the execution of the code.
>
>
>
```
wp_reset_query(); // This will reset all the global variables to "".
```
`wp_reset_query()` restores the $wp\_query and global post data to the original main query. This function should be called after query\_posts(), if you must use that function. As noted in the examples below, it's heavily encouraged to use the pre\_get\_posts filter to alter query parameters before the query is made.
Not only by this method you can reset the `Wp_Query` there are other methods that you can follow up for resetting the `post data` and as well as the `$args`.
Quick Reference About the Resetting Query options.
1. `wp_reset_query()`- best used after a query\_posts loop to reset a custom query
2. `wp_reset_postdata()` - best used after custom or multiple loops created with WP\_Query
3. `rewind_posts()` - best for re-using the same query on the same page.
I hope this is a useful round-up of when & how to reset/rewind the WordPress loop
**wp\_reset\_postdata()**
```
$random_post = new WP_query();
$random_post->query('cat=3&showposts=1&orderby=rand');
while ($random_post->have_posts()) : $random_post->the_post();
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<img src="<?php echo get_post_meta($random_post->ID, 'featured', true); ?>">
</a>
endwhile;
wp_reset_postdata();
```
>
> When to use: best used after custom or multiple loops created with WP\_Query.
>
>
>
**wp\_reset\_query()**
```
<?php query_posts('posts_per_page=3');
if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>
```
>
> When to use: best used after a query\_posts loop to reset things after a custom query.
>
>
>
**rewind\_posts()**
```
if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php endwhile; endif; ?>
<?php rewind_posts(); ?>
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
```
So, while `wp_reset_query` and `wp_reset_postdata` reset the entire query object, rewind\_posts simply resets the post count, as seen for the function in the `wp-includes/query.php` file:
```
// rewind the posts and reset post index
function rewind_posts() {
$this->current_post = -1;
if ( $this->post_count > 0 ) {
$this->post = $this->posts[0];
}
}
```
>
> When to use: best for re-using the same query on the same page.
>
>
> |
240,745 | <p>I have a WordPress installation on a bad server that I want to migrate.</p>
<p>I tried to make a backup via some WordPress plugins, but it was taking forever, generating an enormous zip file.</p>
<p>I asked help from my host support but they haven't replied since.</p>
<p>Looking for a solution I found a <code>www</code> symlink inside the <code>www</code> folder, which is causing the backup to run recursively, re-backing up the entire site again and again, never completing.</p>
<p>I installed the two most known file manager plugins, but both could not delete this symlink, returning an error.</p>
<p>Knowing that I don't have a FTP access, how do I manage to get rid of this symlink?</p>
<p>Is there a plugin that can handle symlinks? Or any way to run a command line to delete this thing?</p>
| [
{
"answer_id": 240815,
"author": "junkrig",
"author_id": 54989,
"author_profile": "https://wordpress.stackexchange.com/users/54989",
"pm_score": 1,
"selected": false,
"text": "<p>Do you have any access to the server? SSH access? If you can get to a command line on the server you could tr... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240745",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103173/"
] | I have a WordPress installation on a bad server that I want to migrate.
I tried to make a backup via some WordPress plugins, but it was taking forever, generating an enormous zip file.
I asked help from my host support but they haven't replied since.
Looking for a solution I found a `www` symlink inside the `www` folder, which is causing the backup to run recursively, re-backing up the entire site again and again, never completing.
I installed the two most known file manager plugins, but both could not delete this symlink, returning an error.
Knowing that I don't have a FTP access, how do I manage to get rid of this symlink?
Is there a plugin that can handle symlinks? Or any way to run a command line to delete this thing? | Do you have any access to the server? SSH access? If you can get to a command line on the server you could try one of these commands. Using sudo would try and run the command as an administrator, so you would need a password:
```
unlink /path/to/symlink
sudo unlink /path/to/symlink
rm /path/to/symlink
sudo rm /path/to/symlink
``` |
240,746 | <p>I would like to show published time "Posted 4:15pm" for the first 24 hours, after 24hours show full published date and time "September 27, 2016 at 4:15pm"</p>
<p>Any suggestions? Thanks in advance</p>
| [
{
"answer_id": 240749,
"author": "user103760",
"author_id": 103760,
"author_profile": "https://wordpress.stackexchange.com/users/103760",
"pm_score": 0,
"selected": false,
"text": "<p>So far :</p>\n\n<pre><code>function ci_posted_on() {\n$time_string = '<time itemprop=\"datePublished\... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240746",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103759/"
] | I would like to show published time "Posted 4:15pm" for the first 24 hours, after 24hours show full published date and time "September 27, 2016 at 4:15pm"
Any suggestions? Thanks in advance | This should do it.
```
// See if the post is older than 24 hours.
if ( get_post_time() <= strtotime( '-1 day' ) ) {
echo 'Published more than 24 hours ago.';
} else {
echo 'Published within the last 24 hours.';
}
``` |
240,762 | <p>I am trying to create a shortcode to display the posts count in a category.
I have successfully done this using this code:</p>
<pre><code>// Add Shortcode to show posts count inside a category
function add_count_of_posts_in_category() {
$term = get_term( 7, 'category' );
$count = $term->count;
echo $count;
}
add_shortcode( 'show-posts-count', 'add_count_of_posts_in_category' );
</code></pre>
<p>However, this means that I need to specify the <code>ID</code> of the category for the shortcode to work. Which means that i need to create a shortcode per category, which is useless.</p>
<p>I am trying to find a way to modify the category ID part with a variable, so that I can use the shortcode like this:
<code>[show-posts-count="cars"]</code> to display the post count in the category called cars.
I can't find a way to do so.</p>
<p>Your help is much appreciated.</p>
<p><strong>EDIT: 29/09/2016</strong>
After getting the code working, I am trying to expand the function to count the posts in the child category too.</p>
<p>So if the main category does not have posts, but has 2 subcategories, each has posts, then when I use the shortcode on the main category, the displayed number is the sum of all the posts in the main category (if any), in addition to, the number of posts in the sub-categories, and the sub-sub-categories..etc</p>
<p>I tried using <code>get_term_children( $term, $taxonomy );</code>, but did not know how to get the post count of subcategories then add them together.</p>
| [
{
"answer_id": 240763,
"author": "Ahmed Fouad",
"author_id": 102371,
"author_profile": "https://wordpress.stackexchange.com/users/102371",
"pm_score": 3,
"selected": true,
"text": "<h3>The shortcode</h3>\n\n<pre><code>// Add Shortcode to show posts count inside a category\nfunction categ... | 2016/09/27 | [
"https://wordpress.stackexchange.com/questions/240762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91570/"
] | I am trying to create a shortcode to display the posts count in a category.
I have successfully done this using this code:
```
// Add Shortcode to show posts count inside a category
function add_count_of_posts_in_category() {
$term = get_term( 7, 'category' );
$count = $term->count;
echo $count;
}
add_shortcode( 'show-posts-count', 'add_count_of_posts_in_category' );
```
However, this means that I need to specify the `ID` of the category for the shortcode to work. Which means that i need to create a shortcode per category, which is useless.
I am trying to find a way to modify the category ID part with a variable, so that I can use the shortcode like this:
`[show-posts-count="cars"]` to display the post count in the category called cars.
I can't find a way to do so.
Your help is much appreciated.
**EDIT: 29/09/2016**
After getting the code working, I am trying to expand the function to count the posts in the child category too.
So if the main category does not have posts, but has 2 subcategories, each has posts, then when I use the shortcode on the main category, the displayed number is the sum of all the posts in the main category (if any), in addition to, the number of posts in the sub-categories, and the sub-sub-categories..etc
I tried using `get_term_children( $term, $taxonomy );`, but did not know how to get the post count of subcategories then add them together. | ### The shortcode
```
// Add Shortcode to show posts count inside a category
function category_post_count( $atts ) {
$atts = shortcode_atts( array(
'category' => null
), $atts );
// get the category by slug.
$term = get_term_by( 'slug', $atts['category'], 'category');
return ( isset( $term->count ) ) ? $term->count : 0;
}
add_shortcode( 'category_post_count', 'category_post_count' );
```
### Usage
```
[category_post_count category="category_slug_or_name"]
```
### If you want to get the count by name, not slug change this
```
$term = get_term_by( 'slug', $atts['category'], 'category');
```
to this:
```
$term = get_term_by( 'name', $atts['category'], 'category');
``` |
240,765 | <p>I want to delete all the resized images while leaving the original image. I have more than 20 GB of unused data taking up room on the server. For example:</p>
<ul>
<li>first-image-name.jpg</li>
<li>first-image-name-72x72.jpg</li>
<li>first-image-name-150x150.jpg</li>
<li>first-image-name-250x250.jpg</li>
<li>first-image-name-300x300.jpg</li>
<li>first-image-name-400x400.jpg</li>
<li>first-image-name-1024x1024.jpg</li>
<li>second-image-name.jpg</li>
<li>second-image-name-72x72.jpg</li>
<li>second-image-name-150x150.jpg</li>
<li>second-image-name-250x250.jpg</li>
<li>second-image-name-300x300.jpg</li>
<li>second-image-name-400x400.jpg</li>
<li>second-image-name-1024x1024.jpg</li>
</ul>
<p>Is there a way to delete all the resized images and disable creating such ones in the future?</p>
| [
{
"answer_id": 240773,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 2,
"selected": false,
"text": "<p>No idea, how to remove existing images. But you can stop generating image sizes for new images you are going ... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240765",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103757/"
] | I want to delete all the resized images while leaving the original image. I have more than 20 GB of unused data taking up room on the server. For example:
* first-image-name.jpg
* first-image-name-72x72.jpg
* first-image-name-150x150.jpg
* first-image-name-250x250.jpg
* first-image-name-300x300.jpg
* first-image-name-400x400.jpg
* first-image-name-1024x1024.jpg
* second-image-name.jpg
* second-image-name-72x72.jpg
* second-image-name-150x150.jpg
* second-image-name-250x250.jpg
* second-image-name-300x300.jpg
* second-image-name-400x400.jpg
* second-image-name-1024x1024.jpg
Is there a way to delete all the resized images and disable creating such ones in the future? | A majority of the answers covered how to stop creating future default image sizes but this doesnt account for creating any custom sizes in your theme but here is another solution to add to `functions.php`:
```
function wpse_240765_unset_images( $sizes ){
unset( $sizes[ 'thumbnail' ]);
unset( $sizes[ 'medium' ]);
unset( $sizes[ 'medium_large' ] );
unset( $sizes[ 'large' ]);
unset( $sizes[ 'full' ] );
return $sizes;
}
add_filter( 'intermediate_image_sizes_advanced', 'wpse_240765_unset_images' );
```
and you can also turn off future default image generation by setting the images to zero:
[](https://i.stack.imgur.com/7VTBX.png)
but to remove the images other then the originals I've ran into your same issue when I forgot to set it to not do it and what I did was:
* Download all the photos locally using an SFTP service, I love [Transmit](https://panic.com/transmit/) (paid) but you can use something like [Filezilla](https://filezilla-project.org/) (free) .
* Download all the files to a directory.
I'm on a Mac but any terminal that allows bash will work. I coded a simple bash script:
```
# !/bin/bash
USERNAME=vader
DIRECTORY="/Users/$USERNAME/desktop/question240765"
for imageWithSize in $(find "$DIRECTORY" -type f -regex '.*/[a-z-]*-[0-9].*.txt$'); do
cd $DIRECTORY
echo rm $imageWithSize
done
```
The folder is located on my desktop, and for the question I named it `question240765`. I used `.txt` files to test this but you can change it to `.jpg`. I saved it as a bash file `image_dust.sh` so that it will allow me to modify or enhance later down the road. Run the script first with the `echo` and you could even dump it to a file with changing the line:
```
echo rm $imageWithSize
```
to:
```
echo rm $imageWithSize >> result.txt
```
which will log everything to the file result.txt and allow you to browse it before really removing them. If all is well change that line to:
```
rm $imageWithSize
```
If you're curious here is what the regex does:
* `[a-z-]*` looks for filenames like `foo-bar` or `fo-fo-bar`. if you have uppercase letters in your name use `[A-Za-z-]*`
* `-[0-9]` after the filename it looks for the remaining `-` (dash) with a number `[0-9]`
* `.*.txt` looks for anything after the first digit to the end of the name with the extension.
After completing the scripting and running it. You could blow everything away on your site and re-upload the images. If you're worried about file size I would even use `imagemagick` but I prefer `sips` to reduce the compression size of the images. |
240,800 | <p>Good morning,
actually i'm going to start with a new entrepreneur project and I'm thinking about build the website in Wordpress but I'll need to upload many GB of video everyday. There's some limit about the upload or the quality of the video?
Will I be able to upload also from a FTP like Filezilla?</p>
<p>Thanks</p>
| [
{
"answer_id": 240773,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 2,
"selected": false,
"text": "<p>No idea, how to remove existing images. But you can stop generating image sizes for new images you are going ... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240800",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103801/"
] | Good morning,
actually i'm going to start with a new entrepreneur project and I'm thinking about build the website in Wordpress but I'll need to upload many GB of video everyday. There's some limit about the upload or the quality of the video?
Will I be able to upload also from a FTP like Filezilla?
Thanks | A majority of the answers covered how to stop creating future default image sizes but this doesnt account for creating any custom sizes in your theme but here is another solution to add to `functions.php`:
```
function wpse_240765_unset_images( $sizes ){
unset( $sizes[ 'thumbnail' ]);
unset( $sizes[ 'medium' ]);
unset( $sizes[ 'medium_large' ] );
unset( $sizes[ 'large' ]);
unset( $sizes[ 'full' ] );
return $sizes;
}
add_filter( 'intermediate_image_sizes_advanced', 'wpse_240765_unset_images' );
```
and you can also turn off future default image generation by setting the images to zero:
[](https://i.stack.imgur.com/7VTBX.png)
but to remove the images other then the originals I've ran into your same issue when I forgot to set it to not do it and what I did was:
* Download all the photos locally using an SFTP service, I love [Transmit](https://panic.com/transmit/) (paid) but you can use something like [Filezilla](https://filezilla-project.org/) (free) .
* Download all the files to a directory.
I'm on a Mac but any terminal that allows bash will work. I coded a simple bash script:
```
# !/bin/bash
USERNAME=vader
DIRECTORY="/Users/$USERNAME/desktop/question240765"
for imageWithSize in $(find "$DIRECTORY" -type f -regex '.*/[a-z-]*-[0-9].*.txt$'); do
cd $DIRECTORY
echo rm $imageWithSize
done
```
The folder is located on my desktop, and for the question I named it `question240765`. I used `.txt` files to test this but you can change it to `.jpg`. I saved it as a bash file `image_dust.sh` so that it will allow me to modify or enhance later down the road. Run the script first with the `echo` and you could even dump it to a file with changing the line:
```
echo rm $imageWithSize
```
to:
```
echo rm $imageWithSize >> result.txt
```
which will log everything to the file result.txt and allow you to browse it before really removing them. If all is well change that line to:
```
rm $imageWithSize
```
If you're curious here is what the regex does:
* `[a-z-]*` looks for filenames like `foo-bar` or `fo-fo-bar`. if you have uppercase letters in your name use `[A-Za-z-]*`
* `-[0-9]` after the filename it looks for the remaining `-` (dash) with a number `[0-9]`
* `.*.txt` looks for anything after the first digit to the end of the name with the extension.
After completing the scripting and running it. You could blow everything away on your site and re-upload the images. If you're worried about file size I would even use `imagemagick` but I prefer `sips` to reduce the compression size of the images. |
240,811 | <p>The first query is working fine individually. Vouchers have a day, a start time and an end time. I'm grabbing the current time (e.g 11:10) and trying to show posts where the <code>$time_now</code> comes BETWEEN the <code>start_time</code> and <code>end_time</code>. Are you not able to pass an array into the <code>key</code>?</p>
<pre><code>$today = date('l');
$time_now = date('H:i');
$args = array (
'post_type' => array( 'voucher' ),
'meta_query' => array(
array(
'key' => '_voucher_days_available',
'value' => $today,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => array('_voucher_start_time','_voucher_end_time'),
'value' => $time_now,
'compare' => 'BETWEEN',
),
),
);
</code></pre>
| [
{
"answer_id": 240823,
"author": "Ahmed Fouad",
"author_id": 102371,
"author_profile": "https://wordpress.stackexchange.com/users/102371",
"pm_score": 1,
"selected": false,
"text": "<p>Can you please try the following <code>$args</code></p>\n\n<pre><code>$today = date('l');\n$time_now = ... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240811",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103807/"
] | The first query is working fine individually. Vouchers have a day, a start time and an end time. I'm grabbing the current time (e.g 11:10) and trying to show posts where the `$time_now` comes BETWEEN the `start_time` and `end_time`. Are you not able to pass an array into the `key`?
```
$today = date('l');
$time_now = date('H:i');
$args = array (
'post_type' => array( 'voucher' ),
'meta_query' => array(
array(
'key' => '_voucher_days_available',
'value' => $today,
'compare' => 'LIKE',
'type' => 'CHAR',
),
array(
'key' => array('_voucher_start_time','_voucher_end_time'),
'value' => $time_now,
'compare' => 'BETWEEN',
),
),
);
``` | In addition to the suggestion by @AhmedMahdi to solve your problem, here's the narrower answer to your question: Nope, `key` cannot be an array. As you can see in the [specs of WP\_Meta\_Query](https://codex.wordpress.org/Class_Reference/WP_Meta_Query) `key` must be a string. |
240,834 | <p>Recently Themeforest Ask all the new developers to Add Custom Post Type Throught Plugin.. My question is
I have testimonial.php Custom Post Type With Meta Boxes</p>
<pre><code><?php
function register_testimonial() {
$labels = array(
'name' => 'Testimonial',
'singular_name' => 'Testimonial',
'add_new' => 'Add New',
'add_new_item' => 'Add New testimonial',
'edit_item' => 'Edit Testimonial',
'new_item' => 'New Testimonial',
'view_item' => 'View Testimonial',
'search_items' => 'Search Testimonial',
'not_found' => 'No Testimonial found',
'not_found_in_trash' => 'No Testimonial found in Trash',
'menu_name' => 'Testimonial',
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-testimonial',
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
register_post_type( 'testimonial', $args );
}
add_action( 'init', 'register_testimonial' );
add_action( 'admin_init', 'testimonial_admin' );
function testimonial_admin() {
add_meta_box( 'testimonial_meta_box',
'Testimonial Details',
'display_testimonial_meta_box',
'testimonial', 'normal', 'high'
);
}
function register_post_assets(){
}
add_action('admin_init', 'register_post_assets', 1);
function display_testimonial_meta_box( $testimonial ) {
// Retrieve current name of the Name and testimonial Rating based on review ID
$WEBSITE_Name = esc_html( get_post_meta( $testimonial->ID, 'WEBSITE_Name', true ) );
$WEBSITE_URL = esc_html( get_post_meta( $testimonial->ID, 'WEBSITE_URL', true ) );
?>
<table>
<tr>
<td style="width: 100%">WEBSITE Name : </td>
<td><input type="text" name="WEBSITE_Name" value="<?php echo $WEBSITE_Name; ?>" /></td>
</tr>
<tr>
<td style="width: 100%">WEBSITE URL : </td>
<td><input type="url" name="WEBSITE_URL" value="<?php echo $WEBSITE_URL; ?>" /></td>
</tr>
</table>
<?php
}
add_action( 'save_post', 'add_testimonial_fields', 10, 2 );
function add_testimonial_fields( $testimonial_id, $testimonial ) {
// Check post type for testimonial reviews
if ( $testimonial->post_type == 'testimonial' ) {
// Store data in post meta table if present in post data
if ( isset( $_POST['WEBSITE_Name'] ) && $_POST['WEBSITE_Name'] != '' ) {
update_post_meta( $testimonial_id, 'WEBSITE_Name', $_POST['WEBSITE_Name'] );
}
if ( isset( $_POST['WEBSITE_URL'] ) && $_POST['WEBSITE_URL'] != '' ) {
update_post_meta( $testimonial_id, 'WEBSITE_URL', $_POST['WEBSITE_URL'] );
}
}
}
?>
</code></pre>
<p>How can i create Plugin of This???</p>
| [
{
"answer_id": 240842,
"author": "xWaZzo",
"author_id": 95090,
"author_profile": "https://wordpress.stackexchange.com/users/95090",
"pm_score": 0,
"selected": false,
"text": "<p>You need to move this out of your theme into a new folder (The plugin folder) and add the next lines to the be... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103817/"
] | Recently Themeforest Ask all the new developers to Add Custom Post Type Throught Plugin.. My question is
I have testimonial.php Custom Post Type With Meta Boxes
```
<?php
function register_testimonial() {
$labels = array(
'name' => 'Testimonial',
'singular_name' => 'Testimonial',
'add_new' => 'Add New',
'add_new_item' => 'Add New testimonial',
'edit_item' => 'Edit Testimonial',
'new_item' => 'New Testimonial',
'view_item' => 'View Testimonial',
'search_items' => 'Search Testimonial',
'not_found' => 'No Testimonial found',
'not_found_in_trash' => 'No Testimonial found in Trash',
'menu_name' => 'Testimonial',
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-testimonial',
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
register_post_type( 'testimonial', $args );
}
add_action( 'init', 'register_testimonial' );
add_action( 'admin_init', 'testimonial_admin' );
function testimonial_admin() {
add_meta_box( 'testimonial_meta_box',
'Testimonial Details',
'display_testimonial_meta_box',
'testimonial', 'normal', 'high'
);
}
function register_post_assets(){
}
add_action('admin_init', 'register_post_assets', 1);
function display_testimonial_meta_box( $testimonial ) {
// Retrieve current name of the Name and testimonial Rating based on review ID
$WEBSITE_Name = esc_html( get_post_meta( $testimonial->ID, 'WEBSITE_Name', true ) );
$WEBSITE_URL = esc_html( get_post_meta( $testimonial->ID, 'WEBSITE_URL', true ) );
?>
<table>
<tr>
<td style="width: 100%">WEBSITE Name : </td>
<td><input type="text" name="WEBSITE_Name" value="<?php echo $WEBSITE_Name; ?>" /></td>
</tr>
<tr>
<td style="width: 100%">WEBSITE URL : </td>
<td><input type="url" name="WEBSITE_URL" value="<?php echo $WEBSITE_URL; ?>" /></td>
</tr>
</table>
<?php
}
add_action( 'save_post', 'add_testimonial_fields', 10, 2 );
function add_testimonial_fields( $testimonial_id, $testimonial ) {
// Check post type for testimonial reviews
if ( $testimonial->post_type == 'testimonial' ) {
// Store data in post meta table if present in post data
if ( isset( $_POST['WEBSITE_Name'] ) && $_POST['WEBSITE_Name'] != '' ) {
update_post_meta( $testimonial_id, 'WEBSITE_Name', $_POST['WEBSITE_Name'] );
}
if ( isset( $_POST['WEBSITE_URL'] ) && $_POST['WEBSITE_URL'] != '' ) {
update_post_meta( $testimonial_id, 'WEBSITE_URL', $_POST['WEBSITE_URL'] );
}
}
}
?>
```
How can i create Plugin of This??? | i agree with the other answers, but neither addressed flushing the re-write rules. If you don't add this, it will confuse your users when they activate the plugin and still can't access the custom postypes on the front.
The other problem you're going to have is that LOTS of people will use testimonials so if your clients load a plugin that uses testimonials and is using the same postype or if they were previously using another plugin that had a CPT testimonials, there will be conflicts.
It is better if you prefix your identifier with a short namespace that identifies your plugin, theme or website that implements the custom post type (instead of testimonials, say "haroon\_testimonials" to ensure no one else will be using your post type in their systems.
Then to address post links on the front (so they see www.example.com/testimoinals/1 instead of www.example.com/haroon-testimonials/1
you'll need to use a re-write back to testimonials:
```
'rewrite' => array('slug' => 'locations'),
```
Here is a sample code i use:
```
<?php
/**
* @package rt_create_cpt
* @version 1.0
*/
/*
Plugin Name: Custom Post Creation by RT
Description: A Plugin to create CPT
Author: RT, Inc
Version: 3.4
Author URI: http://
*/
add_action( 'init', 'rt_custom_post' );
function rt_custom_post() {
register_post_type( 'rt_locations',
array(
'labels' => array(
'name' => __( 'Locations' ),
'singular_name' => __( 'Location' ),
'add_new' => _x('Add New Location', 'Location'),
'add_new_item' => __("Add New Location"),
'edit_item' => __("Edit This Location"),
'new_item' => __("New Location"),
'view_item' => __("View Location"),
'search_items' => __("Search in Locations"),
'uploaded_to_this_item' => __("Used for image for this Location"),
'featured_image' => __("Location Image"),
'set_featured_image' => __("Set Location Image"),
'remove_featured_image' => __("Remove Location Image"),
'use_featured_image' => __("Use Location Image"),
'not_found' => __('No Locations'),
'not_found_in_trash' => __('No Locations found in Trash')
),
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-store',
'supports' => array('title','author','thumbnail','editor'),
'rewrite' => array('slug' => 'locations'),
)
);
}
function rt_rewrite_flush() {
// First, we "add" the custom post type via the above written function.
// Note: "add" is written with quotes, as CPTs don't get added to the DB,
// They are only referenced in the post_type column with a post entry,
// when you add a post of this CPT.
rt_custom_post();
// ATTENTION: This is *only* done during plugin activation hook in this example!
// You should *NEVER EVER* do this on every page load!!
flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'rt_rewrite_flush' );
?>
```
you'll just want to put your code function in and then change the rewrite rule to match your code! |
240,836 | <p>I am having to update a website for someone that was built with one of those (not very nice, clunky) pre-made themes. The theme (it's the parent theme, actually, called Mineral) inserts a meta box in all of the post and page edit pages of the site with various layout options. </p>
<p>I want to hide this though for various pages. So, to get this working, I have tried the normal code:</p>
<pre><code>function remove_page_excerpt_field() {
remove_meta_box( 'pexeto-meta-page-boxes' , 'page' , 'normal' );
}
add_action( 'admin_menu' , 'remove_page_excerpt_field' );
</code></pre>
<p>where <code>pexeto-meta-page-boxes</code> is the name of the id of the meta box's outer div. This has no effect though.</p>
<p>I've had this problem in the past but never got to the bottom of it. I assume it's due to a priority issue of some kind. Is there a way to set up my <code>remove_meta_box()</code> function with a greater priority to override whatever was defined by the parent theme's coders?</p>
| [
{
"answer_id": 240841,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>You can try to hook your function with admin_init.</p>\n\n<pre><code>add_action('admin_init', 'remove_page_exc... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240836",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28543/"
] | I am having to update a website for someone that was built with one of those (not very nice, clunky) pre-made themes. The theme (it's the parent theme, actually, called Mineral) inserts a meta box in all of the post and page edit pages of the site with various layout options.
I want to hide this though for various pages. So, to get this working, I have tried the normal code:
```
function remove_page_excerpt_field() {
remove_meta_box( 'pexeto-meta-page-boxes' , 'page' , 'normal' );
}
add_action( 'admin_menu' , 'remove_page_excerpt_field' );
```
where `pexeto-meta-page-boxes` is the name of the id of the meta box's outer div. This has no effect though.
I've had this problem in the past but never got to the bottom of it. I assume it's due to a priority issue of some kind. Is there a way to set up my `remove_meta_box()` function with a greater priority to override whatever was defined by the parent theme's coders? | **Remove WordPress Meta Boxes**
You have to make use of the function called `remove meta box`.
**Description:**
Removes a meta box or any other element from a particular post edit screen of a given post type. It can be also used to remove a widget from the dashboard screen.
>
> Steps to remove the meta box from WordPress Dashboard:
>
>
>
When removing WordPress meta boxes, I’ve seen it done in a number of different ways two of which are often done via JavaScript. Though this is functional for many, client-side solutions aren’t always great especially as it relates to accessibility.
On top of that, hiding things via JavaScript is kind of a hack – the visibility of elements should often be set in terms of CSS and it will likely cause a little bit of a flicker when the element is being hidden while the DOM loads.
Anyway, the two ways I’ve often seen it done is when:
Developers look for the check boxes under the Screen Options and then trigger the click event.
Developers sniff out the meta boxes ID and then use `jQuery’s hide()` method to hide the meta boxes from the page.
Sure, these work, but you’re still faced with the challenges of accessibility and with the fact that you’re modifying something that should probably be done via CSS.
Unless a hook exists.
And that’s really the mentality that we, as WordPress developers, should have whenever we’re attempting to introduce, remove, or modify anything as it relates to WordPress both in the dashboard and on the front-end.
Specifically, we need to ask ourselves:
Given what I need to do, is there a hook that makes this available?
And this is this case (and many, many cases), there is. We can take advantage of the `default_hidden_meta_boxes` hook.
**Using The Hook**
The function accepts two arguments:
1. An array of meta boxes that should be hidden
2. The current screen being displayed
This allows us to modify the existing array of hidden meta boxes (or create our own) and only trigger it on specific screen’s, as well.
So let’s say that we have a custom post type called `acme_post_type` and we want to hide the Categories, Author, Post Excerpt, and Slug meta box.
```
<?php
add_action( 'default_hidden_meta_boxes', 'acme_remove_meta_boxes', 10, 2 );
/**
* Removes the category, author, post excerpt, and slug meta boxes.
*
* @since 1.0.0
*
* @param array $hidden The array of meta boxes that should be hidden for Acme Post Types
* @param object $screen The current screen object that's being displayed on the screen
* @return array $hidden The updated array that removes other meta boxes
*/
function acme_remove_meta_boxes( $hidden, $screen ) {
if ( 'acme_post_type' == $screen->id ) {
$hidden = array(
'acme_post_type_categorydiv',
'authordiv',
'postexcerpt',
'slugdiv'
);
}
return $hidden;
}
```
First, the code checks to see if we’re on the screen for the custom post type. If so, then we define a new array that includes the IDs of the meta boxes that we want to hide. After that, we the array to WordPress and the end-result of the function will be that the specified meta boxes will be hidden from view.
In terms of getting the ID of the meta boxes that you want to hide, you can use the Developer Tools of your preferred browser to inspect the elements on the page.
>
> Another Example of how to remove the meta box in WordPress.
>
>
>
```
// REMOVE POST META BOXES
function remove_my_post_metaboxes() {
remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Status Metabox
remove_meta_box( 'commentsdiv','post','normal' ); // Comments Metabox
remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
remove_meta_box( 'revisionsdiv','post','normal' ); // Revisions Metabox
remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
remove_meta_box( 'trackbacksdiv','post','normal' ); // Trackback Metabox
}
add_action('admin_menu','remove_my_post_metaboxes');
```
Place the following code in your functions file `(Appearance > Editor > Theme Functions – functions.php)`.
Placing that code should remove all the meta boxes below the post editor and give you a nice, clean look. |
240,838 | <p>I have a CPT named “football_fixture”.This CPT has taxonomy named “competition”, and this taxonomy has different terms , laliga, eng.
I want to show my post as follow:<br>
laliga:<br>
List of all posts published including above terms.<br>
eng:<br>
List of all posts published including above terms.<br>
I am using following codes but it show the content as showed in the image1.
<a href="https://i.stack.imgur.com/MILrX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MILrX.png" alt="enter image description here"></a></p>
<p>I want the post like image 2:
<a href="https://i.stack.imgur.com/D8PcR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D8PcR.png" alt="enter image description here"></a>
image1:
Here is the codes I am using:</p>
<pre><code><?php
/**
* Template Name: Fixture
* Description: The template for displaying all posts and attachments
*/
?>
<?php get_header(); ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$term_id = get_queried_object()->term_id;
$args = array( 'post_type' => 'football_fixture',
'paged' => $paged,
);
query_posts( $args );
?>
<?php if(have_posts()): ?>
<div class="<?php echo $col; ?>">
<?php while(have_posts()): ?>
<?php the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
$id = get_the_ID();
$date = rwmb_meta( 'pb_match_date','', $post->ID);
$time = rwmb_meta( 'pb_match_time','', $post->ID );
$competition = rwmb_meta( 'pb_match_competition_cats','', $post->ID );
$team_a = get_post_meta( $post->ID, 'match_details_home_team', true );
$team_b = get_post_meta( $post->ID, 'match_details_away_team', true );
?>
<div class="fixture-item">
<div class="fixture-info clearfix">
<p class="pull-left match-date"><?php echo ($date); ?></p>
<p class="pull-left match-date">
<?php
$terms = get_the_terms( get_the_ID(), 'competition' ); // 'taxonomy' field doesn't store term IDs in the custom fields, instead, it sets post terms
if ( !empty( $terms ) ) {
$content = '<ul>';
foreach ( $terms as $term ) {
$content .= sprintf(
'<li><a href="%s" title="%s">%s</a></li>',
get_term_link( $term, 'tax_slug' ),
$term->name,
$term->name
);
}
$content .= '</ul>';
echo $content;
}
?>
</p>
</div>
<div class="row">
<div class="col-xs-4">
<div class="media">
<div class="media-body">
<h4><?php echo $team_a; ?></h4>
</div>
</div>
</div>
<div class="col-xs-4 match-time">
<i class="fa fa-clock-o"></i> <?php echo $time; ?>
</div>
<div class="col-xs-4">
<div class="media">
<div class="media-body">
<h4 class="pull-right"><?php echo $team_b; ?></h4>
</div>
</div>
</div>
</div>
</div>
</div><!--/#post-->
<?php endwhile; ?>
<?php
wp_reset_query();
?>
</div>
<?php endif; ?>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 240849,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 1,
"selected": false,
"text": "<p>You need to <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofo... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240838",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83330/"
] | I have a CPT named “football\_fixture”.This CPT has taxonomy named “competition”, and this taxonomy has different terms , laliga, eng.
I want to show my post as follow:
laliga:
List of all posts published including above terms.
eng:
List of all posts published including above terms.
I am using following codes but it show the content as showed in the image1.
[](https://i.stack.imgur.com/MILrX.png)
I want the post like image 2:
[](https://i.stack.imgur.com/D8PcR.png)
image1:
Here is the codes I am using:
```
<?php
/**
* Template Name: Fixture
* Description: The template for displaying all posts and attachments
*/
?>
<?php get_header(); ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$term_id = get_queried_object()->term_id;
$args = array( 'post_type' => 'football_fixture',
'paged' => $paged,
);
query_posts( $args );
?>
<?php if(have_posts()): ?>
<div class="<?php echo $col; ?>">
<?php while(have_posts()): ?>
<?php the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
$id = get_the_ID();
$date = rwmb_meta( 'pb_match_date','', $post->ID);
$time = rwmb_meta( 'pb_match_time','', $post->ID );
$competition = rwmb_meta( 'pb_match_competition_cats','', $post->ID );
$team_a = get_post_meta( $post->ID, 'match_details_home_team', true );
$team_b = get_post_meta( $post->ID, 'match_details_away_team', true );
?>
<div class="fixture-item">
<div class="fixture-info clearfix">
<p class="pull-left match-date"><?php echo ($date); ?></p>
<p class="pull-left match-date">
<?php
$terms = get_the_terms( get_the_ID(), 'competition' ); // 'taxonomy' field doesn't store term IDs in the custom fields, instead, it sets post terms
if ( !empty( $terms ) ) {
$content = '<ul>';
foreach ( $terms as $term ) {
$content .= sprintf(
'<li><a href="%s" title="%s">%s</a></li>',
get_term_link( $term, 'tax_slug' ),
$term->name,
$term->name
);
}
$content .= '</ul>';
echo $content;
}
?>
</p>
</div>
<div class="row">
<div class="col-xs-4">
<div class="media">
<div class="media-body">
<h4><?php echo $team_a; ?></h4>
</div>
</div>
</div>
<div class="col-xs-4 match-time">
<i class="fa fa-clock-o"></i> <?php echo $time; ?>
</div>
<div class="col-xs-4">
<div class="media">
<div class="media-body">
<h4 class="pull-right"><?php echo $team_b; ?></h4>
</div>
</div>
</div>
</div>
</div>
</div><!--/#post-->
<?php endwhile; ?>
<?php
wp_reset_query();
?>
</div>
<?php endif; ?>
<?php get_footer(); ?>
``` | In your custom templates, First you have to fetch all terms for your custom post type.
You can use [get\_terms](https://developer.wordpress.org/reference/functions/get_terms/) to retrive terms in taxonomy
If you are using wordpress prior to 4.5
```
$terms = get_terms( 'competition' , array(
'hide_empty' => false
) );
```
OR if you are using wordpress prior to 4.5.0 or later
```
$terms = get_terms( array(
'taxonomy' => 'competition',
'hide_empty' => false,
) );
```
Next Build Term name lists:
```
$termNames = array();
$count = count( $terms );
if ( $count > 0 ) {
foreach ( $terms as $term ) {
$termNames[] = $term->name;
}
}
```
Next loop trough each terms and query posts for the current terms & then run the loop:
```
foreach($termNames as $termName) :
$args = array(
'post_type' => 'football_fixture',
'competition' => $termName,
'order' => 'ASC',
);
query_posts( $args );
if(have_posts()): ?>
<div class="<?php echo $col; ?>">
<h2><?php echo $termName; ?></h2>
<?php while(have_posts()): the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
$id = get_the_ID();
$date = rwmb_meta( 'pb_match_date','', $post->ID);
$time = rwmb_meta( 'pb_match_time','', $post->ID );
$competition = rwmb_meta( 'pb_match_competition_cats','', $post->ID );
$team_a = get_post_meta( $post->ID, 'match_details_home_team', true );
$team_b = get_post_meta( $post->ID, 'match_details_away_team', true );
?>
<div class="fixture-item">
<div class="row">
<div class="col-xs-4">
<div class="media">
<div class="media-body">
<h4><?php echo $team_a; ?></h4>
</div>
</div>
</div>
<div class="col-xs-4 match-time">
<i class="fa fa-clock-o"></i> <?php echo $time; ?>
</div>
<div class="col-xs-4">
<div class="media">
<div class="media-body">
<h4 class="pull-right"><?php echo $team_b; ?></h4>
</div>
</div>
</div>
</div>
</div>
</div><!--/#post-->
<?php endwhile; ?>
<?php
wp_reset_query();
?>
``` |
240,844 | <p>I have a theme which appears to have broken previewing posts. When I preview a page/post I get a 404 error.</p>
<p>If I change to another theme previews work fine again so it must be something in this theme.</p>
<p>I can't work out when/if I would have broken previews. Going through my filters and actions I can't see anything obvious.</p>
<p>Has anyone had a similar problem/ What did it turn out to be?</p>
| [
{
"answer_id": 240869,
"author": "italiansoda",
"author_id": 71608,
"author_profile": "https://wordpress.stackexchange.com/users/71608",
"pm_score": 1,
"selected": false,
"text": "<p>This is just a shot in the dark without knowing more like sMyles said. Try saving (flushing) your permali... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240844",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85357/"
] | I have a theme which appears to have broken previewing posts. When I preview a page/post I get a 404 error.
If I change to another theme previews work fine again so it must be something in this theme.
I can't work out when/if I would have broken previews. Going through my filters and actions I can't see anything obvious.
Has anyone had a similar problem/ What did it turn out to be? | I found the answer.
It was only for post-formats on pages. The issue was that I needed to also register the taxonomy `post_format` on pages as well in the init action.
I have updated the wiki page to reflect this.
<https://codex.wordpress.org/Post_Formats#Adding_Post_Type_Support>
```
// add post-formats to post_type 'page'
add_action('init', 'my_theme_slug_add_post_formats_to_page', 11);
function my_theme_slug_add_post_formats_to_page(){
add_post_type_support( 'page', 'post-formats' );
register_taxonomy_for_object_type( 'post_format', 'page' );
}
``` |
240,854 | <p>The value of the field it is checking is '25000' and I want to check that the value in the variable is less than or equal to this meta field.</p>
<p>This is working fine in the most part for any number above 10000 but anything below this it doesn't bring the results back.</p>
<p>I am trying to figure out what the issue is here, any input will be greatly appreciated.</p>
<p>The code is as follows:</p>
<pre><code>$args = array(
'post_type' => 'loan-offers',
'meta_query' => array(
array(
'key' => 'amount',
'value' => $amount,
'compare' => '>='
),
array(
'key' => 'time',
'value' => $months,
'compare' => '>='
)
));
$custom_query = new WP_Query($args);
</code></pre>
| [
{
"answer_id": 240859,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": 0,
"selected": false,
"text": "<p>use relation inside <code>meta_query</code> <code>'relation' => 'OR',</code></p>\n\n<pre><code>$args... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102637/"
] | The value of the field it is checking is '25000' and I want to check that the value in the variable is less than or equal to this meta field.
This is working fine in the most part for any number above 10000 but anything below this it doesn't bring the results back.
I am trying to figure out what the issue is here, any input will be greatly appreciated.
The code is as follows:
```
$args = array(
'post_type' => 'loan-offers',
'meta_query' => array(
array(
'key' => 'amount',
'value' => $amount,
'compare' => '>='
),
array(
'key' => 'time',
'value' => $months,
'compare' => '>='
)
));
$custom_query = new WP_Query($args);
``` | In order to deliver the amount variable to be less than 25000 you need to check the query with the operator called `<=` but you have tested it with `>=` in your query.
**Note:** There are several comparison operators available
```
= equals
!= does not equal
> greater than
>= greater than or equal to
< less than
<= less than or equal to
```
>
> But in your query you have misjudged the query and used. You have to use `<=` rather you have used `>=`
>
>
>
1. `<=` - Less than or Equal to
2. `>=` - Greater than or Equal to
>
> Usage of relation is appreciated in the Meta Query since without specifying the relation you are not supposed to mix the array of parameters that is given to the query for execution
>
>
>
```
$args = array(
'post_type' => 'loan-offers',
'meta_query' => array(
relation => 'AND', // This can be AND / OR depending on your choice
array(
'key' => 'amount',
'value' => $amount,
'compare' => '<='
),
array(
'key' => 'time',
'value' => $months,
'compare' => '>='
)
));
```
`LIKE` and `NOT LIKE` are `SQL operators` that let you add in wild-card symbols, so you could have a meta query that looks like this:
```
array(
'key' => 'name',
'value' => 'Pat',
'compare' => 'LIKE'
)
```
>
> Get Posts Within a Given Range of Numeric Meta Values
>
>
>
```
// the loan-offers is more than 10000 and less than 25000
$rd_args = array(
'post_type' => 'loan-offers',
'meta_query' => array(
array(
'key' => 'amount',
'value' => array( 10000, 25000 ),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
)
);
$rd_query = new WP_Query( $rd_args );
```
You can use BETWEEN operator for getting the output as required by you. |
240,856 | <p>Somewhat of a weird problem: </p>
<p>I have a post loop that display the three most recent posts from specific categories. It seems to work, except the post url is not being returned. It returns just the root url 'localhost:8888'. Any help would be appreciated!</p>
<pre><code> <?php $posts = get_posts( "category=17,12,35,23,24,25,13,27,14,26,22,16,29,15,19,20,21&numberposts=3" ); ?>
<?php if( $posts ) : ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<div class="post homepage">
<a href="<?php echo get_permalink($post->ID); ?>"><img src="<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo $feat_image;?>" /></a>
<h3 class="homepage-post-title"><a href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title; ?></a></h3>
<a class="read-more-link" href="<?php echo get_permalink($post->ID); ?>">Read More</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 240867,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 2,
"selected": false,
"text": "<p>You have made the mistake in getting the post link in your code.</p>\n\n<p><strong>Missing</strong><... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240856",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101935/"
] | Somewhat of a weird problem:
I have a post loop that display the three most recent posts from specific categories. It seems to work, except the post url is not being returned. It returns just the root url 'localhost:8888'. Any help would be appreciated!
```
<?php $posts = get_posts( "category=17,12,35,23,24,25,13,27,14,26,22,16,29,15,19,20,21&numberposts=3" ); ?>
<?php if( $posts ) : ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<div class="post homepage">
<a href="<?php echo get_permalink($post->ID); ?>"><img src="<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo $feat_image;?>" /></a>
<h3 class="homepage-post-title"><a href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title; ?></a></h3>
<a class="read-more-link" href="<?php echo get_permalink($post->ID); ?>">Read More</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
``` | You have made the mistake in getting the post link in your code.
**Missing**
1. `<?php global $post; ?>` - Initialization at the start of the loop
>
> After setting up the post data your query becomes like normal `Wp_Query` so that you can get the `permalink()` in normal method itself using `the_permalink()` instead of `get_permalink($post->id)`.
>
>
>
Since your posts is behaving in the normal method you need to make the following changes.
1. Remove the `get_permalink()` from the code
2. Remove the echo tag in roder to display the permalink
Replace your code with the current one.
**Wherever you have used**
```
<?php echo get_permalink($post->ID); ?>
```
**Replace it with**
```
<?php the_permalink(); ?>
```
And your final code will look like as follows.
```
<?php $posts = get_posts( "category=17,12,35,23,24,25,13,27,14,26,22,16,29,15,19,20,21&numberposts=3" ); ?>
<?php if( $posts ) : ?>
<?php global $post; ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<div class="post homepage">
<a href="<?php the_permalink(); ?>"><img src="<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo $feat_image;?>" /></a>
<h3 class="homepage-post-title"><a href="<?php the_permalink(); ?>"><?php echo $post->post_title; ?></a></h3>
<a class="read-more-link" href="<?php the_permalink(); ?>">Read More</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
``` |
240,858 | <p>I made some researches for my question, but found nothing.</p>
<p>I have a query that gets all posts from a specific post type and where a specific custom field is not empty. But I would like that this same custom field has a max characters' length. And I don't want to trim the value, I only want to get posts that have a characters' length between 1 and 75.</p>
<p>Here is my current query that works but without the characters' length.</p>
<pre><code>new WP_Query(array(
'post_type' => 'experts',
'posts_per_page' => 1,
'meta_key' => 'quote',
'meta_value' => '',
'meta_compare' => '!=',
'orderby' => 'rand'
));
</code></pre>
| [
{
"answer_id": 240867,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 2,
"selected": false,
"text": "<p>You have made the mistake in getting the post link in your code.</p>\n\n<p><strong>Missing</strong><... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103829/"
] | I made some researches for my question, but found nothing.
I have a query that gets all posts from a specific post type and where a specific custom field is not empty. But I would like that this same custom field has a max characters' length. And I don't want to trim the value, I only want to get posts that have a characters' length between 1 and 75.
Here is my current query that works but without the characters' length.
```
new WP_Query(array(
'post_type' => 'experts',
'posts_per_page' => 1,
'meta_key' => 'quote',
'meta_value' => '',
'meta_compare' => '!=',
'orderby' => 'rand'
));
``` | You have made the mistake in getting the post link in your code.
**Missing**
1. `<?php global $post; ?>` - Initialization at the start of the loop
>
> After setting up the post data your query becomes like normal `Wp_Query` so that you can get the `permalink()` in normal method itself using `the_permalink()` instead of `get_permalink($post->id)`.
>
>
>
Since your posts is behaving in the normal method you need to make the following changes.
1. Remove the `get_permalink()` from the code
2. Remove the echo tag in roder to display the permalink
Replace your code with the current one.
**Wherever you have used**
```
<?php echo get_permalink($post->ID); ?>
```
**Replace it with**
```
<?php the_permalink(); ?>
```
And your final code will look like as follows.
```
<?php $posts = get_posts( "category=17,12,35,23,24,25,13,27,14,26,22,16,29,15,19,20,21&numberposts=3" ); ?>
<?php if( $posts ) : ?>
<?php global $post; ?>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<div class="post homepage">
<a href="<?php the_permalink(); ?>"><img src="<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo $feat_image;?>" /></a>
<h3 class="homepage-post-title"><a href="<?php the_permalink(); ?>"><?php echo $post->post_title; ?></a></h3>
<a class="read-more-link" href="<?php the_permalink(); ?>">Read More</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
``` |
240,861 | <p>In my wordpress theme i m trying to print multiple <code>custom fields</code> of posts with ajax. First i get <code>title</code> of post with ajax live search correctly, now need to show post data after click on any post title.</p>
<p>After <code>Click</code> on any <code>title</code> in live search it show custom field for that post on same page??</p>
<p><strong>HTML:</strong></p>
<pre><code><h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a></h2>
<div id="viewspec"> Meta key result here </div>
</code></pre>
<p><strong>Funtion:</strong></p>
<pre><code><?php
add_action('wp_ajax_data_fetchmeta' , 'data_fetchmeta');
add_action('wp_ajax_nopriv_data_fetchmeta','data_fetchmeta');
function data_fetchmeta(){
$the_query = new WP_Query( array( 's' => esc_attr( $_POST['metakey'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<p>
<?php echo get_post_meta( get_the_ID(), 'brand', true );?>
<?php echo get_post_meta( get_the_ID(), 'price', true );?>
<?php echo get_post_meta( get_the_ID(), 'cpu', true );?>
<?php echo get_post_meta( get_the_ID(), 'ram', true );?>
</p>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
?>
</code></pre>
<p><strong>Script:</strong></p>
<pre><code><script type="text/javascript">
function h2 a{
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetchmeta', metakey: jQuery('#metakey').onclick() },
success: function(data) {
jQuery('#viewspec').html( data );
}
});
}
</script>
</code></pre>
<p><strong>AJAX live search: working</strong></p>
<pre><code><input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch"> Search result here </div>
<?php
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a> </h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
</code></pre>
| [
{
"answer_id": 240866,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 0,
"selected": false,
"text": "<p>It appears you are not capturing the event when a search result is clicked. Your code for each search result is... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240861",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97572/"
] | In my wordpress theme i m trying to print multiple `custom fields` of posts with ajax. First i get `title` of post with ajax live search correctly, now need to show post data after click on any post title.
After `Click` on any `title` in live search it show custom field for that post on same page??
**HTML:**
```
<h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a></h2>
<div id="viewspec"> Meta key result here </div>
```
**Funtion:**
```
<?php
add_action('wp_ajax_data_fetchmeta' , 'data_fetchmeta');
add_action('wp_ajax_nopriv_data_fetchmeta','data_fetchmeta');
function data_fetchmeta(){
$the_query = new WP_Query( array( 's' => esc_attr( $_POST['metakey'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<p>
<?php echo get_post_meta( get_the_ID(), 'brand', true );?>
<?php echo get_post_meta( get_the_ID(), 'price', true );?>
<?php echo get_post_meta( get_the_ID(), 'cpu', true );?>
<?php echo get_post_meta( get_the_ID(), 'ram', true );?>
</p>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
?>
```
**Script:**
```
<script type="text/javascript">
function h2 a{
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetchmeta', metakey: jQuery('#metakey').onclick() },
success: function(data) {
jQuery('#viewspec').html( data );
}
});
}
</script>
```
**AJAX live search: working**
```
<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>
<div id="datafetch"> Search result here </div>
<?php
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a> </h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
``` | I'm not sure Why you used loop to display your post meta. and you code are all ok but you have to change little-bit.
***Q***. *Why you used inline script ? On my opinion you should used external script file to do this.*
anyway that's not the main issue here. In order to work with click function with ajax generate conten. You have to bind click function proper way otherwise it not will work.
Here is an example, but I'm useing external js file for this and so you just have to register.
```
/**
* Add js file with Enqueues scripts.
*/
function wpse_scripts() {
wp_enqueue_script( 'wpse-ajax-init', get_stylesheet_directory_uri() . '/js/wpse-ajax-init.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'wpse-ajax-init', 'ajaxwpse', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
}
add_action( 'wp_enqueue_scripts', 'wpse_scripts' );
```
And now change you title markup that you fetch post title.
```
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><a href="#" name="metakey" id="<?php the_ID(); ?>"><?php the_title();?></a> </h2>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
```
I'm here just changed `<h2><a href="#" name="metakey" id="metakey"><?php the_title();?></a> </h2>` to `<h2><a href="#" name="metakey" id="<?php the_ID(); ?>"><?php the_title();?></a> </h2>` because you need to grab the ID of the title dynamically.
After doing that add below code on your `wpse-ajax-init.js` that you just register and hook with `admin-ajax.php`.
```
(function ($) {
$("#datafetch").on('click', 'a', function(e) {
e.preventDefault();
$('#keyword').delay(100).attr('value', '');
$(this).delay(100).hide();
$.ajax({
url: ajaxwpse.ajaxurl,
type: 'post',
data: {
action: 'data_fetchmeta',
ID: $(this).attr('id')
},
success: function(data) {
$('#viewspec').html( data );
}
});
});
})(jQuery);
```
And finally changed your `data_fetchmeta()` function query like this
```
add_action('wp_ajax_data_fetchmeta' , 'data_fetchmeta');
add_action('wp_ajax_nopriv_data_fetchmeta','data_fetchmeta');
function data_fetchmeta(){
$ID = esc_attr( $_POST['ID'] ); ?>
<p>
<?php echo get_post_meta( $ID, 'brand', true );?>
<?php echo get_post_meta( $ID, 'price', true );?>
<?php echo get_post_meta( $ID, 'cpu', true );?>
<?php echo get_post_meta( $ID, 'ram', true );?>
</p>
<?php die();
}
```
You can see, I just grab the dynamic id and used to display post meta.
Hope it make sense to you. |
240,877 | <p>We have a situation where the users (children) keep not forgetting their password but making trivial mistakes while trying to login.<br>
As per question they should be first redirected to page e.g. id=5 with instructions like: </p>
<blockquote>
<p>Please go back and:<br>
Activate your cookies<br>
Check if the correct language is on your keyboard<br>
Ask your mother to log you in<br>
etc...<br>
If none of the above works please click here (<a href="http://oursite.com/wp-login.php?action=lostpassword" rel="nofollow">http://oursite.com/wp-login.php?action=lostpassword</a>) to ask for a new password </p>
</blockquote>
<p>So, the lostpassword link on the login page should redirect to the existing page with the custom message/instructions <strong>and then</strong>, the link on the page to the actual lostpassword link. </p>
<p><em>PS: I believe that the lately introduced <a href="https://developer.wordpress.org/reference/hooks/lostpassword_post/" rel="nofollow">lostpassword_post</a> hook could be useful.</em></p>
| [
{
"answer_id": 240885,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>the action <code>login_form_lostpassword</code> is called before the lost password page. try this : </p>\n\n<pre>... | 2016/09/28 | [
"https://wordpress.stackexchange.com/questions/240877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17797/"
] | We have a situation where the users (children) keep not forgetting their password but making trivial mistakes while trying to login.
As per question they should be first redirected to page e.g. id=5 with instructions like:
>
> Please go back and:
>
> Activate your cookies
>
> Check if the correct language is on your keyboard
>
> Ask your mother to log you in
>
> etc...
>
> If none of the above works please click here (<http://oursite.com/wp-login.php?action=lostpassword>) to ask for a new password
>
>
>
So, the lostpassword link on the login page should redirect to the existing page with the custom message/instructions **and then**, the link on the page to the actual lostpassword link.
*PS: I believe that the lately introduced [lostpassword\_post](https://developer.wordpress.org/reference/hooks/lostpassword_post/) hook could be useful.* | This is straightforward.
1. Hook on init to detect the lostpassword page
2. If the user is not coming from your instructions page (which we defined by adding extra query parameter) he'll be redirected to your custom page
3. In your custom page add the link to lost password page including the extra parameter we set to skip the redirection.
```
add_action( 'init', 'lostpassword_instructions' );
function lostpassword_instructions() {
global $pagenow;
if ( $pagenow == 'wp-login.php' &&
isset( $_REQUEST[ 'action' ] ) &&
$_REQUEST[ 'action' ] == 'lostpassword' &&
! isset( $_REQUEST[ 'skip' ] )
) {
exit( wp_redirect( 'http://domain.com/lost-password-instructions' ) );
}
}
```
Now on your custom page, something like that should work:
```
$url = 'http://domain.com/wp-login.php?action=lostpassword&skip=true';
``` |
240,914 | <p>Wordpress 4.4 indroduced a way to display the genitive case of a months name for specific locale by using the function <code>date_i18n</code> (<a href="https://core.trac.wordpress.org/ticket/11226#comment:32" rel="nofollow">https://core.trac.wordpress.org/ticket/11226#comment:32</a>) which is filtered by <code>wp_maybe_decline_date()</code> (<a href="https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/functions.php#L172" rel="nofollow">https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/functions.php#L172</a>). Even though both my locale (el) and the translation of the string "decline months names: on or off" in my el.po file are correct, the genitive case of the months name is not working. So with this: <code>echo date_i18n( 'j F Y', strtotime( '2016/9/20' ) );</code> I got the date with the month name in nominative case.</p>
<p>Any ideas? Thanks in advance!</p>
| [
{
"answer_id": 301367,
"author": "Cubakos",
"author_id": 107648,
"author_profile": "https://wordpress.stackexchange.com/users/107648",
"pm_score": 2,
"selected": false,
"text": "<p>Although, in my wp your <code>echo</code> displayed correctly (so maybe double check that you use the corre... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/240914",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19543/"
] | Wordpress 4.4 indroduced a way to display the genitive case of a months name for specific locale by using the function `date_i18n` (<https://core.trac.wordpress.org/ticket/11226#comment:32>) which is filtered by `wp_maybe_decline_date()` (<https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/functions.php#L172>). Even though both my locale (el) and the translation of the string "decline months names: on or off" in my el.po file are correct, the genitive case of the months name is not working. So with this: `echo date_i18n( 'j F Y', strtotime( '2016/9/20' ) );` I got the date with the month name in nominative case.
Any ideas? Thanks in advance! | Although, in my wp your `echo` displayed correctly (so maybe double check that you use the correct locale and that "decline months names: on or off" is translated as "on" in your locale), you can *"force"* genitive case, by making a generic wrap function based on the `wp_maybe_decline_date()`.
I have tested and used this, in order to overcome the `wp_maybe_decline_date()` regex that ,matches formats like `'j F Y'` or `'j. F'`, while I wanted to use `'l j F Y'`
Example use case:
In our theme `functions.php` we define the wrapper function like:
```
/**
* [multi_force_use_genitive_month_date]
* Call this to force genitive use case for months in date translation
* @param string $date Formatted date string.
* @return string The date, declined if locale specifies it.
*/
function multi_force_use_genitive_month_date( $date ) {
global $wp_locale;
// i18n functions are not available in SHORTINIT mode
if ( ! function_exists( '_x' ) ) {
return $date;
}
/* translators: If months in your language require a genitive case,
* translate this to 'on'. Do not translate into your own language.
*/
if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {
// Match a format like 'j F Y' or 'j. F'
$months = $wp_locale->month;
$months_genitive = $wp_locale->month_genitive;
foreach ( $months as $key => $month ) {
$months[ $key ] = '# ' . $month . '( |$)#u';
}
foreach ( $months_genitive as $key => $month ) {
$months_genitive[ $key ] = ' ' . $month . '$1';
}
$date = preg_replace( $months, $months_genitive, $date );
}
// Used for locale-specific rules
$locale = get_locale();
return $date;
}
```
Then, in our template file where we want the genitive case to appear, we wrap the `date_i18n()`, like:
```
<?php echo multi_force_use_genitive_month_date( date_i18n( 'l j F Y' ) ); ?>
```
Hope this helps. |
240,917 | <p>I am trying to add an custom action hook in wordpress but it's not working.Please help me through this.</p>
<pre><code><?php
function wp_add_google_link(){
global $WP_Admin_Bar;
var_dump($WP_Admin_Bar);
$WP_Admin_Bar->add_menu(array(
'id'=>'google_analytics',
'title'=>'GoogleAnalytics',
'href'=>'https://google.com/analytics'
));
}
add_action('wp_before_admin_bar_render','wp_add_google_link');
</code></pre>
| [
{
"answer_id": 301367,
"author": "Cubakos",
"author_id": 107648,
"author_profile": "https://wordpress.stackexchange.com/users/107648",
"pm_score": 2,
"selected": false,
"text": "<p>Although, in my wp your <code>echo</code> displayed correctly (so maybe double check that you use the corre... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/240917",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103858/"
] | I am trying to add an custom action hook in wordpress but it's not working.Please help me through this.
```
<?php
function wp_add_google_link(){
global $WP_Admin_Bar;
var_dump($WP_Admin_Bar);
$WP_Admin_Bar->add_menu(array(
'id'=>'google_analytics',
'title'=>'GoogleAnalytics',
'href'=>'https://google.com/analytics'
));
}
add_action('wp_before_admin_bar_render','wp_add_google_link');
``` | Although, in my wp your `echo` displayed correctly (so maybe double check that you use the correct locale and that "decline months names: on or off" is translated as "on" in your locale), you can *"force"* genitive case, by making a generic wrap function based on the `wp_maybe_decline_date()`.
I have tested and used this, in order to overcome the `wp_maybe_decline_date()` regex that ,matches formats like `'j F Y'` or `'j. F'`, while I wanted to use `'l j F Y'`
Example use case:
In our theme `functions.php` we define the wrapper function like:
```
/**
* [multi_force_use_genitive_month_date]
* Call this to force genitive use case for months in date translation
* @param string $date Formatted date string.
* @return string The date, declined if locale specifies it.
*/
function multi_force_use_genitive_month_date( $date ) {
global $wp_locale;
// i18n functions are not available in SHORTINIT mode
if ( ! function_exists( '_x' ) ) {
return $date;
}
/* translators: If months in your language require a genitive case,
* translate this to 'on'. Do not translate into your own language.
*/
if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {
// Match a format like 'j F Y' or 'j. F'
$months = $wp_locale->month;
$months_genitive = $wp_locale->month_genitive;
foreach ( $months as $key => $month ) {
$months[ $key ] = '# ' . $month . '( |$)#u';
}
foreach ( $months_genitive as $key => $month ) {
$months_genitive[ $key ] = ' ' . $month . '$1';
}
$date = preg_replace( $months, $months_genitive, $date );
}
// Used for locale-specific rules
$locale = get_locale();
return $date;
}
```
Then, in our template file where we want the genitive case to appear, we wrap the `date_i18n()`, like:
```
<?php echo multi_force_use_genitive_month_date( date_i18n( 'l j F Y' ) ); ?>
```
Hope this helps. |
240,929 | <p>I have a plugin that adds the following action which among other things sends out a registration mail when a new user is added:</p>
<pre><code>add_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
</code></pre>
<p>I would like to remove this action, so I can add it again with some additional checks in the called function. I have tried the following, but can't get it to work:</p>
<pre><code>add_action( 'um_post_registration_approved_hook', 'remove_my_action', 11 );
function remove_my_action(){
remove_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
}
</code></pre>
<p>Any ideas?</p>
<p><strong>EDIT</strong></p>
<p>Turns out I had the priority wrong, thanks! I am now able to remove the action and register a new one instead. However, I'm now having some problems with that. This is what I've unregistered:</p>
<pre><code>add_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
function um_post_registration_approved_hook($user_id, $args){
global $ultimatemember;
$ultimatemember->user->approve();
}
</code></pre>
<p>I have then registered the following instead:</p>
<pre><code>add_action( 'um_post_registration_approved_hook', 'remove_my_action', 9 );
function remove_my_action(){
remove_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
add_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook_new', 10, 2);
}
function um_post_registration_approved_hook_new($user_id, $args){
newApprove();
}
// Make the action call another version of this function - check for user meta - paupress_pp_user_type
function newApprove(){
global $ultimatemember;
$user_id = um_user('ID');
delete_option( "um_cache_userdata_{$user_id}" );
if ( um_user('account_status') == 'awaiting_admin_review' ) {
$this->password_reset_hash();
$ultimatemember->mail->send( um_user('user_email'), 'approved_email' );
} else {
// check for paupress_pp_user_type before sending
$this->password_reset_hash();
// DONT SEND THIS MAIL
//$ultimatemember->mail->send( um_user('user_email'), 'welcome_email');
}
$this->set_status('approved');
$this->delete_meta('account_secret_hash');
$this->delete_meta('_um_cool_but_hard_to_guess_plain_pw');
do_action('um_after_user_is_approved', um_user('ID') );
}
</code></pre>
<p>Which is simply another version of the original approve()-function, with the mail notification removed. BUT this doesn't work, since the original approve() is defined inside the UM_user class and the function relies on this. The original file is here, with the approve()-function defined from line 941: <a href="http://pastebin.com/FknrcxzM" rel="nofollow">http://pastebin.com/FknrcxzM</a></p>
<p>Does my problem make sense? And can I hook into the class instead of the function? - Don't really know the correct approach here..</p>
| [
{
"answer_id": 240930,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 4,
"selected": true,
"text": "<p>You want:</p>\n\n<pre><code>remove_action('um_post_registration_approved_hook', 'um_post_registrat... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/240929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54742/"
] | I have a plugin that adds the following action which among other things sends out a registration mail when a new user is added:
```
add_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
```
I would like to remove this action, so I can add it again with some additional checks in the called function. I have tried the following, but can't get it to work:
```
add_action( 'um_post_registration_approved_hook', 'remove_my_action', 11 );
function remove_my_action(){
remove_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
}
```
Any ideas?
**EDIT**
Turns out I had the priority wrong, thanks! I am now able to remove the action and register a new one instead. However, I'm now having some problems with that. This is what I've unregistered:
```
add_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
function um_post_registration_approved_hook($user_id, $args){
global $ultimatemember;
$ultimatemember->user->approve();
}
```
I have then registered the following instead:
```
add_action( 'um_post_registration_approved_hook', 'remove_my_action', 9 );
function remove_my_action(){
remove_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
add_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook_new', 10, 2);
}
function um_post_registration_approved_hook_new($user_id, $args){
newApprove();
}
// Make the action call another version of this function - check for user meta - paupress_pp_user_type
function newApprove(){
global $ultimatemember;
$user_id = um_user('ID');
delete_option( "um_cache_userdata_{$user_id}" );
if ( um_user('account_status') == 'awaiting_admin_review' ) {
$this->password_reset_hash();
$ultimatemember->mail->send( um_user('user_email'), 'approved_email' );
} else {
// check for paupress_pp_user_type before sending
$this->password_reset_hash();
// DONT SEND THIS MAIL
//$ultimatemember->mail->send( um_user('user_email'), 'welcome_email');
}
$this->set_status('approved');
$this->delete_meta('account_secret_hash');
$this->delete_meta('_um_cool_but_hard_to_guess_plain_pw');
do_action('um_after_user_is_approved', um_user('ID') );
}
```
Which is simply another version of the original approve()-function, with the mail notification removed. BUT this doesn't work, since the original approve() is defined inside the UM\_user class and the function relies on this. The original file is here, with the approve()-function defined from line 941: <http://pastebin.com/FknrcxzM>
Does my problem make sense? And can I hook into the class instead of the function? - Don't really know the correct approach here.. | You want:
```
remove_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
```
... to run after the original `add_action`, but before the action triggers the function `um_post_registration_approved_hook`
The easiest way to do this, but I haven't tested it, might be to just give your removal an earlier priority on the same hook:
```
add_action( 'um_post_registration_approved_hook', 'remove_my_action', 9 );
function remove_my_action(){
remove_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);
}
```
This is what you were trying, but the priority was the wrong way around. `11` runs after `10`. |
240,945 | <p>I have the code below for google fonts I retrieved google fonts detail as JSON data from google web fonts URL. Then i put all information into <code>$items = $data['items'];</code></p>
<p>Then I created the select box for <code>Goole font names</code> and then created another select box for <code>google font variants(font weights)</code> by using javascript.</p>
<p>All codes work without any error. I put the <code><?php echo selected($YPE_font['my_option'], $item['family'], false); ?></code> for saving the first select box font names value in <code>my_option</code> array.</p>
<p>But I don't know how i can save the second select box values within javascript code in my plugin option name array</p>
<pre><code><?php
$YPE_font = get_option('my_option_name');
$items = $data['items'];
$jsItems = array();
foreach($items as $item) {
$family = $item['family'];
$jsItems[$family] = $item['variants'];
}
?>
<select id="fonts" name="my_option[<?php echo $id1; ?>]" class="form-control">
<?php foreach($items as $item): ?>
<option value="<?php echo $item['family']; ?>" <?php echo selected($YPE_font[id1], $item['family'], false); ?>><?php echo $item['family']; ?></option>
<?php endforeach;?>
</select>
<select id="variants" name="my_option[<?php echo $id2; ?>]" class="form-control">
</select>
<script>
jQuery(document).ready(function($){
var items = <?php echo json_encode($jsItems);?>;
$("#fonts").change(function(){
var selectedFont = $(this).val();
var variants = items[selectedFont];
for (i = 0; i < variants.length; i++){
$("#variants").append('<option value="'+variants[i]+'">'+variants[i]+'</option>');
}
})
});
</script>
</code></pre>
| [
{
"answer_id": 240957,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": true,
"text": "<p>This depends on what is it that you are trying to do/use. In theory the protocol used to communicate with ... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/240945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82436/"
] | I have the code below for google fonts I retrieved google fonts detail as JSON data from google web fonts URL. Then i put all information into `$items = $data['items'];`
Then I created the select box for `Goole font names` and then created another select box for `google font variants(font weights)` by using javascript.
All codes work without any error. I put the `<?php echo selected($YPE_font['my_option'], $item['family'], false); ?>` for saving the first select box font names value in `my_option` array.
But I don't know how i can save the second select box values within javascript code in my plugin option name array
```
<?php
$YPE_font = get_option('my_option_name');
$items = $data['items'];
$jsItems = array();
foreach($items as $item) {
$family = $item['family'];
$jsItems[$family] = $item['variants'];
}
?>
<select id="fonts" name="my_option[<?php echo $id1; ?>]" class="form-control">
<?php foreach($items as $item): ?>
<option value="<?php echo $item['family']; ?>" <?php echo selected($YPE_font[id1], $item['family'], false); ?>><?php echo $item['family']; ?></option>
<?php endforeach;?>
</select>
<select id="variants" name="my_option[<?php echo $id2; ?>]" class="form-control">
</select>
<script>
jQuery(document).ready(function($){
var items = <?php echo json_encode($jsItems);?>;
$("#fonts").change(function(){
var selectedFont = $(this).val();
var variants = items[selectedFont];
for (i = 0; i < variants.length; i++){
$("#variants").append('<option value="'+variants[i]+'">'+variants[i]+'</option>');
}
})
});
</script>
``` | This depends on what is it that you are trying to do/use. In theory the protocol used to communicate with memcached server is not very complex and can be implemented in PHP, and therefor as a plugin. In practice you might want to prevent collisions of multiple processes writing at the same time to the cahce which will most likely require the access to the multi tasking API of the OS, something that is not built-in in the default PHP modules and will require you to use additional modules in any case. (there is also probably some performance argument that can be made here between running C and PHP code, but I am not sure how important it is).
Having it as module also let you as the server admin "break out" of whatever restrictions you put on the PHP code in the php.ini and other setting files (in theory you can block the ability of the PHP application to connect anywhere, although I never heard of anyone doing that) |
240,970 | <p>I need to run a query (via <code>functions.php</code>) and find all posts with a certain tag and add those posts to a category.</p>
<p><strong>example:</strong> </p>
<p>Find all posts with tag <strong>"car"</strong> and add them to category <strong>"transportation"</strong>.</p>
<p><strong>EDIT:</strong> STILL NOT WORKING, BUT...</p>
<p>This is what I have so far thanks to <a href="https://wordpress.stackexchange.com/questions/240970/add-category-to-posts-with-tag-wordpress#240973">@benoti's answer</a> (bellow):</p>
<pre><code>$args = array(
'post_type'=>'post',
'tax_query' => array(
'taxonomy' => 'tag',
'field' => 'slug',
'terms' => 'car',
),
);
$posts = get_posts($args);
foreach ($posts as $post) :
//do stuff
$cat_id = 1669; // the ID of category transportation
$append = true; // If true, terms will be appended to the object. If false, terms will replace existing terms
// make some verif that's better
wp_set_object_terms($post->ID, $cat_id, 'category', $append);
endforeach;
</code></pre>
<p>...but it's not working.</p>
<p><strong>Also, to clarify</strong>: </p>
<p>I need to add a category to all posts that contain the <strong>"car "</strong> tag, but I do not know in what category they (the posts) are in.</p>
<p>How can I safely do this without break my site?</p>
| [
{
"answer_id": 240973,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>This is just an example to get all posts in the category transportation with the tag car :</p>\n\n<pre><code>$... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/240970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18693/"
] | I need to run a query (via `functions.php`) and find all posts with a certain tag and add those posts to a category.
**example:**
Find all posts with tag **"car"** and add them to category **"transportation"**.
**EDIT:** STILL NOT WORKING, BUT...
This is what I have so far thanks to [@benoti's answer](https://wordpress.stackexchange.com/questions/240970/add-category-to-posts-with-tag-wordpress#240973) (bellow):
```
$args = array(
'post_type'=>'post',
'tax_query' => array(
'taxonomy' => 'tag',
'field' => 'slug',
'terms' => 'car',
),
);
$posts = get_posts($args);
foreach ($posts as $post) :
//do stuff
$cat_id = 1669; // the ID of category transportation
$append = true; // If true, terms will be appended to the object. If false, terms will replace existing terms
// make some verif that's better
wp_set_object_terms($post->ID, $cat_id, 'category', $append);
endforeach;
```
...but it's not working.
**Also, to clarify**:
I need to add a category to all posts that contain the **"car "** tag, but I do not know in what category they (the posts) are in.
How can I safely do this without break my site? | This is just an example to get all posts in the category transportation with the tag car :
```
$args = array(
'post_type'=>'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'transportation' ),
),
array(
'taxonomy' => 'tag',
'field' => 'slug',
'terms' => array( 'car' ),
'operator' => 'IN',
),
);
$posts = get_posts($args);
```
**EDIT :** for a simple tax\_query
```
'tax_query' => array(
array(
'taxonomy' => 'tag',
'field' => 'slug',
'terms' => 'car'
)
)
```
You can grab more details and it for your case here <https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters>
This will not get the posts tag 'car' and add category 'transportation' to them, but you need first to get posts.
With this result you can loop through it and use `wp_set_object_terms( $object_id, $terms, $taxonomy, $append );` in this loop to add your category to the tagged posts.
```
foreach($posts as $post){
$append = true; // If true, terms will be appended to the object. If false, terms will replace existing terms
// make some verif that's better
wp_set_object_terms($post->ID, 'transportation', 'category', $append);
}
```
the best it to read <https://codex.wordpress.org/Function_Reference/wp_set_object_terms>
I hope you get it ! |
240,974 | <p>I created an input field in general - settings. It's in a plugin for a for a local ngo network site. </p>
<p>It looks like this, and it works great.</p>
<pre><code>$ngob_sitelist_slug = new ngob_sitelist_slug();
class ngob_sitelist_slug {
function ngob_sitelist_slug( ) {
add_filter( 'admin_init' , array( &$this , 'ngob_register_slug' ) );
}
function ngob_register_slug() {
register_setting( 'general', 'sitelist_slug', 'esc_attr' );
add_settings_field('sitelist_slug', '<label for="sitelist_slug">'.__('Slug för site-lista' , 'ngo-branding' ).'</label>' , array(&$this, 'ngob_slug_html') , 'general' );
}
function ngob_slug_html() {
$value = get_option( 'sitelist_slug', '' );
echo '<input type="text" id="sitelist_slug" name="sitelist_slug" value="' . $value . '" />';
}
}
</code></pre>
<p>However I only want it to be created for the network (main) site on a WPMU installation.</p>
<p>So I did this;</p>
<pre><code> // Get site id
$blog_id = get_current_blog_id();
// Check if we are on network site
if( is_main_site( $blog_id ) ) {
$ngob_sitelist_slug = new ngob_sitelist_slug();
class ngob_sitelist_slug {
function ngob_sitelist_slug( ) {
add_filter( 'admin_init' , array( &$this , 'ngob_register_slug' ) );
}
function ngob_register_slug() {
register_setting( 'general', 'sitelist_slug', 'esc_attr' );
add_settings_field('sitelist_slug', '<label for="sitelist_slug">'.__('Slug för site-lista' , 'ngo-branding' ).'</label>' , array(&$this, 'ngob_slug_html') , 'general' );
}
function ngob_slug_html() {
$value = get_option( 'sitelist_slug', '' );
echo '<input type="text" id="sitelist_slug" name="sitelist_slug" value="' . $value . '" />';
}
}
}
</code></pre>
<p>However, I get this error when reloading the page:</p>
<pre><code>Fatal error: Uncaught Error: Class 'ngob_sitelist_slug' not found...(shortened the output, since it's mostly path:s)
</code></pre>
<p>Why is that? Im fairly novis on classes to start with, but when <em>not</em> on network site, the class doesn't get executed, so no problem, as expected.
But when <em>on</em> network site, I get above error..</p>
<p>How to mend this so I can get that input field, but only on the main (network) site?</p>
<p>I don't fully understand what the problem is, and it seems hard to find anything on google about this. I guess you can't wrap a class in an if? But why not, and mostly, how to solve the issue?</p>
| [
{
"answer_id": 240976,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 2,
"selected": false,
"text": "<p>How are you invoking <code>ngob_sitelist_slug</code>?</p>\n\n<p>I'm gonna guess that you are doing something... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/240974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97904/"
] | I created an input field in general - settings. It's in a plugin for a for a local ngo network site.
It looks like this, and it works great.
```
$ngob_sitelist_slug = new ngob_sitelist_slug();
class ngob_sitelist_slug {
function ngob_sitelist_slug( ) {
add_filter( 'admin_init' , array( &$this , 'ngob_register_slug' ) );
}
function ngob_register_slug() {
register_setting( 'general', 'sitelist_slug', 'esc_attr' );
add_settings_field('sitelist_slug', '<label for="sitelist_slug">'.__('Slug för site-lista' , 'ngo-branding' ).'</label>' , array(&$this, 'ngob_slug_html') , 'general' );
}
function ngob_slug_html() {
$value = get_option( 'sitelist_slug', '' );
echo '<input type="text" id="sitelist_slug" name="sitelist_slug" value="' . $value . '" />';
}
}
```
However I only want it to be created for the network (main) site on a WPMU installation.
So I did this;
```
// Get site id
$blog_id = get_current_blog_id();
// Check if we are on network site
if( is_main_site( $blog_id ) ) {
$ngob_sitelist_slug = new ngob_sitelist_slug();
class ngob_sitelist_slug {
function ngob_sitelist_slug( ) {
add_filter( 'admin_init' , array( &$this , 'ngob_register_slug' ) );
}
function ngob_register_slug() {
register_setting( 'general', 'sitelist_slug', 'esc_attr' );
add_settings_field('sitelist_slug', '<label for="sitelist_slug">'.__('Slug för site-lista' , 'ngo-branding' ).'</label>' , array(&$this, 'ngob_slug_html') , 'general' );
}
function ngob_slug_html() {
$value = get_option( 'sitelist_slug', '' );
echo '<input type="text" id="sitelist_slug" name="sitelist_slug" value="' . $value . '" />';
}
}
}
```
However, I get this error when reloading the page:
```
Fatal error: Uncaught Error: Class 'ngob_sitelist_slug' not found...(shortened the output, since it's mostly path:s)
```
Why is that? Im fairly novis on classes to start with, but when *not* on network site, the class doesn't get executed, so no problem, as expected.
But when *on* network site, I get above error..
How to mend this so I can get that input field, but only on the main (network) site?
I don't fully understand what the problem is, and it seems hard to find anything on google about this. I guess you can't wrap a class in an if? But why not, and mostly, how to solve the issue? | How are you invoking `ngob_sitelist_slug`?
I'm gonna guess that you are doing something like `$my_class = new ngob_sitelist_slug;`. Doing it this way would require that your class have a [constructor](http://php.net/manual/en/language.oop5.decon.php). if it doesn't, you'll get an error.
You could still call your class methods statically:
```
$my_thing = ngob_sitelist_slug::my_method();
```
Though technically you should add the `static` keyword to your methods in this case.
Also I see that in your case you are using $this, so you really need a constructor.
EDIT:
I now realize you do have a constructor - albeit a deprecated one. |
240,983 | <p>I am creating a plugin for Wordpress, I have a script that runs perfectly to part to make ajax request to write some data in the database. The code works until the part to display the text within the `` div<code>passo2form</code> which is initially empty and after clicking on the text button is inserted into it. But the data are not recorded in the database. My code looks like this:</p>
<p>main html:</p>
<pre><code><div class='principal-form'>
<input type='text' name='nome' id='nome' class='campo-form' placeholder='Nome' maxlength='50'><br>
<input type='email' name='email' id='email' class='campo-form' placeholder='Email' maxlength='120'/>
<button type='submit' id='enviarform' class='botao-enviar'>Efetuar Simulação</button>
</div>
<div id='passo2form' class='passo2form'></div>
</code></pre>
<p>Javascript file that runs:</p>
<pre><code>jQuery('#enviarform').click(function(){
var nome = document.getElementById('nome').value;
var email = document.getElementById('email').value;
jQuery( "#passo2form" ).html("<div class='col-md-35 padding-top-15'><div class='texto-ola'><p>Olá <span class='cor-vermelho'>" + nome + "</span>,</p><p>Estaremos enviando em breve sua cotação para o email <span class='cor-vermelho'>" + email + " </span></p></div></div>");
var formData = {
'nome' : jQuery('input[name=nome]').val(),
'email' : jQuery('input[name=email]').val()
};
// process the form
jQuery.ajax({
type : 'POST',
url : 'processa.php',
data : formData,
dataType : 'json'
})
.done(function(data) {
console.log(data);
});
});
</code></pre>
<p>I tested the <code>processa.php</code> file and works perfectly making the insertion of data in the database. But the following code:</p>
<pre><code><?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-config.php' );
global $wpdb;
$nome = trim($_POST['nome']);
$email = trim($_POST['email']);
$wpdb->insert(
wp_formclientes,
array(
'nome' => $_POST['nome'],
'email' => $_POST['email']
)
);
$wpdb->show_errors();
?>
</code></pre>
| [
{
"answer_id": 240986,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>That not really the right to do it with WordPress (wp_localize_script, admin_url, wp_ajax_no_priv...).</p>\n\n... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/240983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103909/"
] | I am creating a plugin for Wordpress, I have a script that runs perfectly to part to make ajax request to write some data in the database. The code works until the part to display the text within the `` div`passo2form` which is initially empty and after clicking on the text button is inserted into it. But the data are not recorded in the database. My code looks like this:
main html:
```
<div class='principal-form'>
<input type='text' name='nome' id='nome' class='campo-form' placeholder='Nome' maxlength='50'><br>
<input type='email' name='email' id='email' class='campo-form' placeholder='Email' maxlength='120'/>
<button type='submit' id='enviarform' class='botao-enviar'>Efetuar Simulação</button>
</div>
<div id='passo2form' class='passo2form'></div>
```
Javascript file that runs:
```
jQuery('#enviarform').click(function(){
var nome = document.getElementById('nome').value;
var email = document.getElementById('email').value;
jQuery( "#passo2form" ).html("<div class='col-md-35 padding-top-15'><div class='texto-ola'><p>Olá <span class='cor-vermelho'>" + nome + "</span>,</p><p>Estaremos enviando em breve sua cotação para o email <span class='cor-vermelho'>" + email + " </span></p></div></div>");
var formData = {
'nome' : jQuery('input[name=nome]').val(),
'email' : jQuery('input[name=email]').val()
};
// process the form
jQuery.ajax({
type : 'POST',
url : 'processa.php',
data : formData,
dataType : 'json'
})
.done(function(data) {
console.log(data);
});
});
```
I tested the `processa.php` file and works perfectly making the insertion of data in the database. But the following code:
```
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-config.php' );
global $wpdb;
$nome = trim($_POST['nome']);
$email = trim($_POST['email']);
$wpdb->insert(
wp_formclientes,
array(
'nome' => $_POST['nome'],
'email' => $_POST['email']
)
);
$wpdb->show_errors();
?>
``` | Try like this
Main HTML:
```
<form class="home_footer" method="post" id="home_conct_form" action="">
<input type="text" name="fname" class="txt" />
<input type="text" name="lname" class="txt" />
<input type="button" name="home_submit" id="home_submit" value="Get In Touch"/>
</form>
```
Add on same page:
```
<script>
$('#home_submit').click(function(){
var formData = $("#home_conct_form").serialize()
$.ajax({
type: 'POST',
url: '<?php echo home_url('/'); ?>wp-admin/admin-ajax.php?action=footerFrm',
data: formData,
beforeSend: function(){
$('.progloader').show();
$('#home_submit').hide();
},
success:function(data) {
console.log(data);
}
});
});
</script>
```
Add blow code in Function.php
```
add_action('wp_ajax_footerFrm' , 'footerFrm');
add_action('wp_ajax_nopriv_footerFrm' , 'footerFrm');
function footerFrm() {
print_r($_POST);
die();
}
``` |
241,000 | <p>I'm using the Slick slider in my theme <a href="https://kenwheeler.github.io/slick/" rel="nofollow">https://kenwheeler.github.io/slick/</a> and Material design lite <a href="https://getmdl.io/" rel="nofollow">https://getmdl.io/</a></p>
<p>Problem I am having is that the transforms used here are conflicting with the Wordpress admin bar and causing it to disappear. If I comment these out it works better, but still disappears if the slide is in transition to the next slide. </p>
<pre><code>.slick-slider .slick-list, .slick-slider .slick-track {
-webkit-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
</code></pre>
<p>}</p>
<p>I've tried setting useTransform to false on slick but that didn't help.</p>
| [
{
"answer_id": 241005,
"author": "Andrew Welch",
"author_id": 17862,
"author_profile": "https://wordpress.stackexchange.com/users/17862",
"pm_score": 1,
"selected": false,
"text": "<p>Adding a css rule for #wpadminbar:</p>\n\n<pre><code>transform: translate3d(0,0,0);\nbackground: black;\... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/241000",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17862/"
] | I'm using the Slick slider in my theme <https://kenwheeler.github.io/slick/> and Material design lite <https://getmdl.io/>
Problem I am having is that the transforms used here are conflicting with the Wordpress admin bar and causing it to disappear. If I comment these out it works better, but still disappears if the slide is in transition to the next slide.
```
.slick-slider .slick-list, .slick-slider .slick-track {
-webkit-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
```
}
I've tried setting useTransform to false on slick but that didn't help. | Adding a css rule for #wpadminbar:
```
transform: translate3d(0,0,0);
background: black;
width: 100%;
```
Makes the bar appear and
I added z-index: 0; to .mdl-layout\_\_header to make the dropdowns appear.
Not the prettiest. |
241,002 | <p>I've created a custom field 'entity_person_relevance' ranging from 1 to 3 in order to sort the results by relevance. The problem is that there are already more than 300 posts and the following query only shows posts with this custom field already set:</p>
<pre><code>$query = ( array (
'post_type' => 'entity',
'posts_per_page' => 20,
'meta_query' => array(
array(
'key' => 'entity_person_profile_type',
'value' => $term->term_id,
'compare' => '='
)
),
'orderby' => 'meta_value_num',
'meta_key' => 'entity_person_relevance',
'order' => 'DESC',
'paged' => $paged
)
);
</code></pre>
<p>I'd like to show also the posts which doesn't have the custom field already set. </p>
| [
{
"answer_id": 241005,
"author": "Andrew Welch",
"author_id": 17862,
"author_profile": "https://wordpress.stackexchange.com/users/17862",
"pm_score": 1,
"selected": false,
"text": "<p>Adding a css rule for #wpadminbar:</p>\n\n<pre><code>transform: translate3d(0,0,0);\nbackground: black;\... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/241002",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90416/"
] | I've created a custom field 'entity\_person\_relevance' ranging from 1 to 3 in order to sort the results by relevance. The problem is that there are already more than 300 posts and the following query only shows posts with this custom field already set:
```
$query = ( array (
'post_type' => 'entity',
'posts_per_page' => 20,
'meta_query' => array(
array(
'key' => 'entity_person_profile_type',
'value' => $term->term_id,
'compare' => '='
)
),
'orderby' => 'meta_value_num',
'meta_key' => 'entity_person_relevance',
'order' => 'DESC',
'paged' => $paged
)
);
```
I'd like to show also the posts which doesn't have the custom field already set. | Adding a css rule for #wpadminbar:
```
transform: translate3d(0,0,0);
background: black;
width: 100%;
```
Makes the bar appear and
I added z-index: 0; to .mdl-layout\_\_header to make the dropdowns appear.
Not the prettiest. |
241,017 | <p>How would i add is-active class to the first <code><li></code> generated by the query ? thank you I appreciate it.</p>
<pre><code><?php
$_terms = get_terms( array('claim-accordion-type') );
foreach ($_terms as $term) :
$term_slug = $term->slug;
$_posts = new WP_Query( array(
'post_type' => 'claims_accordion',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'claim-accordion-type',
'field' => 'slug',
'terms' => $term_slug,
),
),
));
if( $_posts->have_posts() ) :
echo'<li class="accordion-item " data-accordion-item>';
echo'<a href="#" class="accordion-title">';
echo ''. $term->name .'';
echo'</a>';
while ( $_posts->have_posts() ) : $_posts->the_post();
?>
<div class="accordion-content" data-tab-content>
<a data-open="exampleModal1">
<h4><?php the_title(); ?></h4></a>
</div>
<div class="reveal" id="exampleModal1" data-reveal>
<?php the_content(); ?>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">&times;</span>
</button>
</div>
<?php
endwhile;
echo '</li>';
endif;
wp_reset_postdata();
endforeach;
?>
</ul>
</code></pre>
| [
{
"answer_id": 241026,
"author": "Ahmed Fouad",
"author_id": 102371,
"author_profile": "https://wordpress.stackexchange.com/users/102371",
"pm_score": 3,
"selected": true,
"text": "<pre><code><?php\n $_terms = get_terms( array('claim-accordion-type') );\n $i = 0;\n foreach ($... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/241017",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67512/"
] | How would i add is-active class to the first `<li>` generated by the query ? thank you I appreciate it.
```
<?php
$_terms = get_terms( array('claim-accordion-type') );
foreach ($_terms as $term) :
$term_slug = $term->slug;
$_posts = new WP_Query( array(
'post_type' => 'claims_accordion',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'claim-accordion-type',
'field' => 'slug',
'terms' => $term_slug,
),
),
));
if( $_posts->have_posts() ) :
echo'<li class="accordion-item " data-accordion-item>';
echo'<a href="#" class="accordion-title">';
echo ''. $term->name .'';
echo'</a>';
while ( $_posts->have_posts() ) : $_posts->the_post();
?>
<div class="accordion-content" data-tab-content>
<a data-open="exampleModal1">
<h4><?php the_title(); ?></h4></a>
</div>
<div class="reveal" id="exampleModal1" data-reveal>
<?php the_content(); ?>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<?php
endwhile;
echo '</li>';
endif;
wp_reset_postdata();
endforeach;
?>
</ul>
``` | ```
<?php
$_terms = get_terms( array('claim-accordion-type') );
$i = 0;
foreach ($_terms as $term) :
$term_slug = $term->slug;
$_posts = new WP_Query( array( 'post_type' => 'claims_accordion', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'claim-accordion-type', 'field' => 'slug', 'terms' => $term_slug, ), ), ));
if( $_posts->have_posts() ) :
$i++;
if ( $i == 1 ) {
$class = 'is-active';
} else {
$class = null;
}
echo'<li class="accordion-item ' . $class . '" data-accordion-item>';
echo'<a href="#" class="accordion-title">';
echo ''. $term->name .'';
echo'</a>';
while ( $_posts->have_posts() ) :
$_posts->the_post();
?>
<div class="accordion-content" data-tab-content>
<a data-open="exampleModal1">
<h4><?php the_title(); ?></h4></a>
</div>
<div class="reveal" id="exampleModal1" data-reveal>
<?php the_content(); ?>
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<?php
endwhile;
echo '</li>';
endif;
wp_reset_postdata();
endforeach;
?>
</ul>
?>
``` |
241,020 | <p>I am creating a plugin in WordPress that will send some data via email. When I activate the plugin, I'm getting a white screen.</p>
<p>I set <code>define('WP_DEBUG', true);</code> in <code>wp-config.php</code> but no error messages are displayed.</p>
<p>Here is the code for my plugin:</p>
<pre><code><?php
/*
Plugin Name: Formulario Cotação
Plugin URI: http://solutionsagencia.com.br
Description: Plugin para cotação em 2 passos.
Version: 0.0.1
Author: Wendell Christian
Author URI: http://solutionsagencia.com.br
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
// Verifica se não existe nenhum classe com o mesmo nome
if ( ! class_exists('FormularioCotacao') ) {
class FormularioCotacao
{
public function __construct() {
/* Adiciona o shortcode */
add_shortcode( 'cotacao', array( $this, 'ExibirTexto' ) );
}
/**
* Este é um método simples que irá exibir o texto do nosso shortcode
*/
public function ExibirTexto () {
$FormularioCotacaoURL = WP_CONTENT_URL;
$FormularioCotacaoURL = WP_CONTENT_URL.'/plugins/'.plugin_basename( dirname(__FILE__)).'/';
return "<div class='principal-form' id='principal-form'>
<form type='post' action='' id='cadastraForm'>
<div class='col-md-65'><div class='col-md-34'><input type='text' name='nome' id='nome' class='campo-form' placeholder='Nome' maxlength='50'></div>
<div class='col-md-34-2'><input type='email' name='email' id='email' class='campo-form' placeholder='Email' maxlength='120'/></div>
<input type='hidden' name='action' value='addCustomer'/>
<div class='col-md-30'><button type='submit' id='enviarform' class='botao-enviar'><span class='icone-cadastrar'></span>Efetue sua simulação</button>
</div>
</div>
</div>
<div id='feedback'></div>
<div id='passo2form' class='passo2form'></div>
";
}
}
/* Carrega a classe */
$FormularioCotacao_settings = new FormularioCotacao();
} // class_exists
function addCustomer(){
global $wpdb;
$nome = trim($_POST['nome']);
$email = trim($_POST['email']);
if($wpdb->insert('wp_formclientes',array(
'nome'=>$nome,
'email'=>$email
))===FALSE){
echo "Error";
}
else {
//mensagem de sucesso
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer'); // not really needed
/*Enviando email completo*/
if( isset($_POST['nome']) && ($_POST['email'])){
$para = "email@email.com";
$assunto = "Assunto" . $nome;
$conteudo =
"<b>Nome:</b> {$nome}" .
"<b>Email:</b> {$email}" .
$headers = array(
'Reply-To' => $name . '<' . $email . '>',
);
}
add_filter( 'wp_mail_content_type', 'set_html_content_type' );
require('http://solutionsagencia.com.br/comparasaude/wp-load.php');
$status = wp_mail( $para, $assunto, $conteudo );
remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
function set_html_content_type() {
return 'text/html';
}
if ( $status ){
echo "sucesso";
} else {
}
function FormularioCotacao_addJS() {
$FormularioCotacaoURL = WP_CONTENT_URL.'/plugins/'.plugin_basename( dirname(__FILE__)).'/';
wp_register_style('estilo', $FormularioCotacaoURL . 'css/estilo.css');
wp_enqueue_style('estilo', $FormularioCotacaoURL . 'css/estilo.css');
}
add_action('wp_print_scripts', 'FormularioCotacao_addJS');
</code></pre>
| [
{
"answer_id": 241022,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure to <a href=\"http://php.net/manual/en/function.error-reporting.php\" rel=\"nofollow\">configure P... | 2016/09/29 | [
"https://wordpress.stackexchange.com/questions/241020",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103909/"
] | I am creating a plugin in WordPress that will send some data via email. When I activate the plugin, I'm getting a white screen.
I set `define('WP_DEBUG', true);` in `wp-config.php` but no error messages are displayed.
Here is the code for my plugin:
```
<?php
/*
Plugin Name: Formulario Cotação
Plugin URI: http://solutionsagencia.com.br
Description: Plugin para cotação em 2 passos.
Version: 0.0.1
Author: Wendell Christian
Author URI: http://solutionsagencia.com.br
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
// Verifica se não existe nenhum classe com o mesmo nome
if ( ! class_exists('FormularioCotacao') ) {
class FormularioCotacao
{
public function __construct() {
/* Adiciona o shortcode */
add_shortcode( 'cotacao', array( $this, 'ExibirTexto' ) );
}
/**
* Este é um método simples que irá exibir o texto do nosso shortcode
*/
public function ExibirTexto () {
$FormularioCotacaoURL = WP_CONTENT_URL;
$FormularioCotacaoURL = WP_CONTENT_URL.'/plugins/'.plugin_basename( dirname(__FILE__)).'/';
return "<div class='principal-form' id='principal-form'>
<form type='post' action='' id='cadastraForm'>
<div class='col-md-65'><div class='col-md-34'><input type='text' name='nome' id='nome' class='campo-form' placeholder='Nome' maxlength='50'></div>
<div class='col-md-34-2'><input type='email' name='email' id='email' class='campo-form' placeholder='Email' maxlength='120'/></div>
<input type='hidden' name='action' value='addCustomer'/>
<div class='col-md-30'><button type='submit' id='enviarform' class='botao-enviar'><span class='icone-cadastrar'></span>Efetue sua simulação</button>
</div>
</div>
</div>
<div id='feedback'></div>
<div id='passo2form' class='passo2form'></div>
";
}
}
/* Carrega a classe */
$FormularioCotacao_settings = new FormularioCotacao();
} // class_exists
function addCustomer(){
global $wpdb;
$nome = trim($_POST['nome']);
$email = trim($_POST['email']);
if($wpdb->insert('wp_formclientes',array(
'nome'=>$nome,
'email'=>$email
))===FALSE){
echo "Error";
}
else {
//mensagem de sucesso
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer'); // not really needed
/*Enviando email completo*/
if( isset($_POST['nome']) && ($_POST['email'])){
$para = "email@email.com";
$assunto = "Assunto" . $nome;
$conteudo =
"<b>Nome:</b> {$nome}" .
"<b>Email:</b> {$email}" .
$headers = array(
'Reply-To' => $name . '<' . $email . '>',
);
}
add_filter( 'wp_mail_content_type', 'set_html_content_type' );
require('http://solutionsagencia.com.br/comparasaude/wp-load.php');
$status = wp_mail( $para, $assunto, $conteudo );
remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
function set_html_content_type() {
return 'text/html';
}
if ( $status ){
echo "sucesso";
} else {
}
function FormularioCotacao_addJS() {
$FormularioCotacaoURL = WP_CONTENT_URL.'/plugins/'.plugin_basename( dirname(__FILE__)).'/';
wp_register_style('estilo', $FormularioCotacaoURL . 'css/estilo.css');
wp_enqueue_style('estilo', $FormularioCotacaoURL . 'css/estilo.css');
}
add_action('wp_print_scripts', 'FormularioCotacao_addJS');
``` | you should remove:
```
require('http://solutionsagencia.com.br/comparasaude/wp-load.php');
```
and use:
```
require(ABSPATH.'wp-includes/pluggable.php');
```
p.s. I advice you, these executions should be hooked in 'init', like:
```
add_action('init', function(){
$para = "email@email.com";
$assunto = "Assunto" . $nome;
$conteudo =
"<b>Nome:</b> {$nome}" .
"<b>Email:</b> {$email}" .
$headers = array(
'Reply-To' => $name . '<' . $email . '>',
);
$status = wp_mail( $para, $assunto, $conteudo );
remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
if ( $status ){
echo "sucesso";
} else {
}
});
``` |
241,035 | <p>I've created some additional tables for a plugin I'm developing and need to add indexes to these tables. </p>
<p>What's the WordPress way to do this? </p>
<p>Using <a href="https://developer.wordpress.org/reference/functions/dbdelta/" rel="noreferrer"><code>dbDelta()</code></a> doesn't seem to be working, and I'm not seeing any error in the logs. </p>
| [
{
"answer_id": 259270,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 4,
"selected": true,
"text": "<p>You can execute <em>arbitrary</em> SQL statements with <a href=\"https://developer.wordpre... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103259/"
] | I've created some additional tables for a plugin I'm developing and need to add indexes to these tables.
What's the WordPress way to do this?
Using [`dbDelta()`](https://developer.wordpress.org/reference/functions/dbdelta/) doesn't seem to be working, and I'm not seeing any error in the logs. | You can execute *arbitrary* SQL statements with [wpdb::query()](https://developer.wordpress.org/reference/classes/wpdb/query/), including Data Definition Statements, e.g.
```
function
create_index ()
{
global $wpdb ;
$sql = "CREATE INDEX my_index ON {$wpdb->prefix}my_table (my_column)" ;
$wpdb->query ($sql) ;
return ;
}
```
**Note:** Because `$wpdb->query()` can execute *arbitrary* SQL, if the statement you pass to it contains **ANY** user input, then you should use [wpdb::prepare()](https://developer.wordpress.org/reference/classes/wpdb/prepare/) to protect against SQL Injection attacks.
But this raises the question: how did you create your plugin-specific tables? "Manually" or programmatically? If programmatically, did you not use `$wpdb->query()`? If you did it "manually", then you really should create the tables (and their indexes) upon plugin activation.
See the excellent answer to [this other WPSE question](https://wordpress.stackexchange.com/questions/25910/uninstall-activate-deactivate-a-plugin-typical-features-how-to/25979#25979) for how to hook into plugin activation (and/or deactivation and uninstall) to do things like create private tables. |
241,056 | <pre><code>add_action( 'init', 'create_topics_nonhierarchical_taxonomy', 0 );
function create_topics_nonhierarchical_taxonomy() {
// Labels part for the GUI
$labels = array(
'name' => _x( 'Blog Tags', 'taxonomy general name' ),
'singular_name' => _x( 'Blog Tag', 'taxonomy singular name' ),
'search_items' => __( 'Search blog_tags' ),
'popular_items' => __( 'Popular blog_tags' ),
'all_items' => __( 'All blog_tags' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit blog_tags' ),
'update_item' => __( 'Update blog_tags' ),
'add_new_item' => __( 'Add New blog_tags' ),
'new_item_name' => __( 'New blog_tags Name' ),
'separate_items_with_commas' => __( 'Separate blog_tags with commas' ),
'add_or_remove_items' => __( 'Add or remove blog_tags' ),
'choose_from_most_used' => __( 'Choose from the most used blog_tags' ),
'menu_name' => __( 'Blog Tags' ),
);
// Now register the non-hierarchical taxonomy like tag
register_taxonomy('blog_tags','blog_tags',array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'blog_tags' ),
));
}
</code></pre>
| [
{
"answer_id": 259270,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 4,
"selected": true,
"text": "<p>You can execute <em>arbitrary</em> SQL statements with <a href=\"https://developer.wordpre... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241056",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103945/"
] | ```
add_action( 'init', 'create_topics_nonhierarchical_taxonomy', 0 );
function create_topics_nonhierarchical_taxonomy() {
// Labels part for the GUI
$labels = array(
'name' => _x( 'Blog Tags', 'taxonomy general name' ),
'singular_name' => _x( 'Blog Tag', 'taxonomy singular name' ),
'search_items' => __( 'Search blog_tags' ),
'popular_items' => __( 'Popular blog_tags' ),
'all_items' => __( 'All blog_tags' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit blog_tags' ),
'update_item' => __( 'Update blog_tags' ),
'add_new_item' => __( 'Add New blog_tags' ),
'new_item_name' => __( 'New blog_tags Name' ),
'separate_items_with_commas' => __( 'Separate blog_tags with commas' ),
'add_or_remove_items' => __( 'Add or remove blog_tags' ),
'choose_from_most_used' => __( 'Choose from the most used blog_tags' ),
'menu_name' => __( 'Blog Tags' ),
);
// Now register the non-hierarchical taxonomy like tag
register_taxonomy('blog_tags','blog_tags',array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'blog_tags' ),
));
}
``` | You can execute *arbitrary* SQL statements with [wpdb::query()](https://developer.wordpress.org/reference/classes/wpdb/query/), including Data Definition Statements, e.g.
```
function
create_index ()
{
global $wpdb ;
$sql = "CREATE INDEX my_index ON {$wpdb->prefix}my_table (my_column)" ;
$wpdb->query ($sql) ;
return ;
}
```
**Note:** Because `$wpdb->query()` can execute *arbitrary* SQL, if the statement you pass to it contains **ANY** user input, then you should use [wpdb::prepare()](https://developer.wordpress.org/reference/classes/wpdb/prepare/) to protect against SQL Injection attacks.
But this raises the question: how did you create your plugin-specific tables? "Manually" or programmatically? If programmatically, did you not use `$wpdb->query()`? If you did it "manually", then you really should create the tables (and their indexes) upon plugin activation.
See the excellent answer to [this other WPSE question](https://wordpress.stackexchange.com/questions/25910/uninstall-activate-deactivate-a-plugin-typical-features-how-to/25979#25979) for how to hook into plugin activation (and/or deactivation and uninstall) to do things like create private tables. |
241,060 | <p>I have the following problem:</p>
<p>I have created a custom post type <code>matratze</code> and currently besides the custom posts no other posts exist. Hence, nothing is being displayed under the recent posts. </p>
<p>The custom post type looks like the following:</p>
<p>[custom post]</p>
<p>My recent posts do not get displayed:</p>
<p>[main homepage]</p>
<p>I tried the following:</p>
<pre><code>add_filter( 'pre_get_posts', 'my_get_posts' );
function my_get_posts( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'page', 'matratze' ) );
return $query;
}
</code></pre>
<p>Any suggestions what I am doing wrong?</p>
<p>I appreciate your replies!</p>
| [
{
"answer_id": 241076,
"author": "C Sabhar",
"author_id": 103830,
"author_profile": "https://wordpress.stackexchange.com/users/103830",
"pm_score": 2,
"selected": false,
"text": "<p>Wordpress provides <a href=\"https://developer.wordpress.org/reference/functions/wp_get_recent_posts/\" re... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241060",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48703/"
] | I have the following problem:
I have created a custom post type `matratze` and currently besides the custom posts no other posts exist. Hence, nothing is being displayed under the recent posts.
The custom post type looks like the following:
[custom post]
My recent posts do not get displayed:
[main homepage]
I tried the following:
```
add_filter( 'pre_get_posts', 'my_get_posts' );
function my_get_posts( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'page', 'matratze' ) );
return $query;
}
```
Any suggestions what I am doing wrong?
I appreciate your replies! | Wordpress provides [`wp_get_recent_posts()`](https://developer.wordpress.org/reference/functions/wp_get_recent_posts/) function to retrive a number of recent posts from any post types. you can pass your custom post type as an arguments to retrieve recent posts lists.
```
$args = array(
'numberposts' => '5',
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'matratze',
'post_status' => 'publish'
);
$recent_posts = wp_get_recent_posts( $args );
```
**Wordpress Core Recent Posts widget does not provide feature to list posts from custom post type. If you want to list post using Widget, you can use [Posts in Sidebar](https://wordpress.org/plugins/posts-in-sidebar/) Plugin.** This plugins i very powerful and provides you many options to show posts based on many criteria including recent posts from custom post types.
**UPDATE:**
Here is code you can use for your specific case:
You are using Tab Widget to display recent posts which uses WP\_Query. So you can use pre\_get\_posts to set post type filter.
```
function filter_recent_get_posts($query) {
if (isset($_POST['tab']) && ($_POST['tab'] == 'recent')) {
$query->set('post_type', 'matratze');
}
}
add_action( 'pre_get_posts', 'filter_recent_get_posts' );
``` |
241,069 | <p>Im trying to show a box on left sidebar with links of current page's sub menus. but order is not applying same as menu! whats the problem?</p>
<pre><code><div class="sidebar-box">
<div class="sidebar-box-title">
<h4><?php echo get_the_title($post->post_parent); ?></h4>
</div>
<ul class="links">
<?php wp_list_pages('sort_order=asc&title_li=&sort_column=menu_order&depth=1&child_of='.$post->post_parent); ?>
</ul>
</div>
</code></pre>
<p>DEMO: <a href="http://www.testhosting.co.uk/speedshealthcare/healthcare-supplies/care-home-pharmacy/" rel="nofollow">http://www.testhosting.co.uk/speedshealthcare/healthcare-supplies/care-home-pharmacy/</a></p>
| [
{
"answer_id": 241081,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>Because you are ordering <em>only</em> by <code>menu_order</code>, rather than <code>menu_order post_title... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241069",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8124/"
] | Im trying to show a box on left sidebar with links of current page's sub menus. but order is not applying same as menu! whats the problem?
```
<div class="sidebar-box">
<div class="sidebar-box-title">
<h4><?php echo get_the_title($post->post_parent); ?></h4>
</div>
<ul class="links">
<?php wp_list_pages('sort_order=asc&title_li=&sort_column=menu_order&depth=1&child_of='.$post->post_parent); ?>
</ul>
</div>
```
DEMO: <http://www.testhosting.co.uk/speedshealthcare/healthcare-supplies/care-home-pharmacy/> | Because you are ordering *only* by `menu_order`, rather than `menu_order post_title`. In fact, you can just get rid of your `sort_*` arguments as `wp_list_pages` will output the correct natural order by default. |
241,094 | <p>I want to create a child theme for TwentyFifteen theme, which will customize a lot of things, including translation. When I install WordPress in my language (Farsi), it includes TwentyFifteen language files in <code>wp-content/languages/themes</code></p>
<p>So when I create a <code>languages</code> folder in my child theme and add customized language files to it and add <code>load_theme_textdomain( 'twentyfifteen', get_stylesheet_directory() . '/languages' )</code> to my child theme's <code>functions.php</code> my customized language files do not load and instead the files in <code>wp-content/languages/themes</code> load. What can I do to override those files?</p>
| [
{
"answer_id": 241116,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a quote from the <a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/l10n.php#L502... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103967/"
] | I want to create a child theme for TwentyFifteen theme, which will customize a lot of things, including translation. When I install WordPress in my language (Farsi), it includes TwentyFifteen language files in `wp-content/languages/themes`
So when I create a `languages` folder in my child theme and add customized language files to it and add `load_theme_textdomain( 'twentyfifteen', get_stylesheet_directory() . '/languages' )` to my child theme's `functions.php` my customized language files do not load and instead the files in `wp-content/languages/themes` load. What can I do to override those files? | Since WP 4.6 `load_theme_textdomain()` (and consequently `load_child_theme_textdomain()`) will give priority to .mo files downloaded from WP's online translation platform (translate.wordpress.org). Due to some new code ([here, on line 769](https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/l10n.php#L755)) these functions will completely ignore your local .mo files if the textdomain is found in the general *languages/* directory.
You can, however, use the more basic `load_textdomain()` function to directly load your .mo file and override strings from the original domain, like this:
```
$domain = 'textdomain-to-override';
$path = get_stylesheet_directory() . '/languages/'; // adjust to the location of your .mo file
$locale = apply_filters( 'theme_locale', get_locale(), $domain );
load_textdomain( $domain, $path . $locale . '.mo' );
``` |
241,096 | <p>Is it possible to customize AJAX response when using filters such as <code>check_admin_referer</code> and <code>check_ajax_referer</code> ?</p>
<p>I've done some tweaks (with those filters) to prevent users from deleting some terms that are really important and MUST not be deleted. But it keeps telling me "unknown error" which is far from being clear.</p>
<p>Any hint would be cool.</p>
<p>For now I'm using wp_die( 'This term cannot be deleted' ) and I wonder how to inject this message in AJAX response.</p>
| [
{
"answer_id": 242359,
"author": "stims",
"author_id": 104727,
"author_profile": "https://wordpress.stackexchange.com/users/104727",
"pm_score": 0,
"selected": false,
"text": "<p>This is my first answer, hope it helps.</p>\n\n<p>If I understand your question correctly, you are wondering ... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241096",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31376/"
] | Is it possible to customize AJAX response when using filters such as `check_admin_referer` and `check_ajax_referer` ?
I've done some tweaks (with those filters) to prevent users from deleting some terms that are really important and MUST not be deleted. But it keeps telling me "unknown error" which is far from being clear.
Any hint would be cool.
For now I'm using wp\_die( 'This term cannot be deleted' ) and I wonder how to inject this message in AJAX response. | Wait for WordPress 4.7 on 6th December. It has this almost built-in.
If I got it right, then you'll want to prevent some terms from deletion.
I already made a snippet for that which works with WP 4.7
```
add_filter(
'user_has_cap',
function ( $allcaps, $caps, $args ) {
if ( ! isset( $args[0] ) || 'delete_term' != $args[0] ) {
// not the deletion process => ignore
return $allcaps;
}
$term = get_term( $args[2] );
// HERE YOU'LL LIKE TO PUT YOUR LOGIC INSTEAD OF THIS:
if ( $term->count <= 0 ) {
return $allcaps;
}
// for all other cases => reject deletion
return [ ];
},
10,
3
);
```
For more details read <https://wp-includes.org/536/capabilities-taxonomies-terms/#Preventnon-empty_categories_from_deletion> |
241,119 | <p>I currently have a parent page with some child pages. I am able to list these child pages but would like to insert a custom li class. The <code>wp_list_pages</code> outputs <code><li class="page-item number"></li></code>. I would like for it to output <code><li class="hvr-underline"></li></code>. Here is the code I have so far:</p>
<pre><code>$children = wp_list_pages( 'title_li=&child_of='.$post->ID.'&echo=0' );
if ( $children) : ?>
<ul class="menu ">
<?php echo $children; ?>
</ul>
<?php endif;
</code></pre>
| [
{
"answer_id": 242359,
"author": "stims",
"author_id": 104727,
"author_profile": "https://wordpress.stackexchange.com/users/104727",
"pm_score": 0,
"selected": false,
"text": "<p>This is my first answer, hope it helps.</p>\n\n<p>If I understand your question correctly, you are wondering ... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241119",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67512/"
] | I currently have a parent page with some child pages. I am able to list these child pages but would like to insert a custom li class. The `wp_list_pages` outputs `<li class="page-item number"></li>`. I would like for it to output `<li class="hvr-underline"></li>`. Here is the code I have so far:
```
$children = wp_list_pages( 'title_li=&child_of='.$post->ID.'&echo=0' );
if ( $children) : ?>
<ul class="menu ">
<?php echo $children; ?>
</ul>
<?php endif;
``` | Wait for WordPress 4.7 on 6th December. It has this almost built-in.
If I got it right, then you'll want to prevent some terms from deletion.
I already made a snippet for that which works with WP 4.7
```
add_filter(
'user_has_cap',
function ( $allcaps, $caps, $args ) {
if ( ! isset( $args[0] ) || 'delete_term' != $args[0] ) {
// not the deletion process => ignore
return $allcaps;
}
$term = get_term( $args[2] );
// HERE YOU'LL LIKE TO PUT YOUR LOGIC INSTEAD OF THIS:
if ( $term->count <= 0 ) {
return $allcaps;
}
// for all other cases => reject deletion
return [ ];
},
10,
3
);
```
For more details read <https://wp-includes.org/536/capabilities-taxonomies-terms/#Preventnon-empty_categories_from_deletion> |
241,137 | <p>Recently I realized that you could include a db-error.php file in your <code>wp-content</code> directory from "<a href="https://wordpress.stackexchange.com/questions/239310/how-to-monitor-server-for-error-establishing-a-database-connection">How to monitor server for error establishing a database connection</a>" that would replace the existing WordPress database error message with something custom. I thought about doing a redirect in db-error.php like:</p>
<pre><code>header("Location: http://vader.com/saber.html");
exit();
</code></pre>
<p>but I wanted to replace <code>http://vader.com</code> with the site URL so this could be portable but after researching I didn't see a way to obtain the site URL without the connection and I per discussions I was told you want to do minimal modifications to the wp.config file. Is there a way to get the site URL without a database connection that could be used in the header redirect?</p>
| [
{
"answer_id": 241140,
"author": "EAMann",
"author_id": 46,
"author_profile": "https://wordpress.stackexchange.com/users/46",
"pm_score": 3,
"selected": true,
"text": "<p>One option is setting the site's URL in the <code>wp-config.php</code> file itself. This effectively overrides the <c... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] | Recently I realized that you could include a db-error.php file in your `wp-content` directory from "[How to monitor server for error establishing a database connection](https://wordpress.stackexchange.com/questions/239310/how-to-monitor-server-for-error-establishing-a-database-connection)" that would replace the existing WordPress database error message with something custom. I thought about doing a redirect in db-error.php like:
```
header("Location: http://vader.com/saber.html");
exit();
```
but I wanted to replace `http://vader.com` with the site URL so this could be portable but after researching I didn't see a way to obtain the site URL without the connection and I per discussions I was told you want to do minimal modifications to the wp.config file. Is there a way to get the site URL without a database connection that could be used in the header redirect? | One option is setting the site's URL in the `wp-config.php` file itself. This effectively overrides the `siteurl` option that's otherwise stored in the database, but it also means you can reference the URL without doing a query.
From [the Codex](https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php):
>
> It is possible to set the site URL manually in the wp-config.php file.
>
>
> Add these two lines to your wp-config.php, where "example.com" is the correct location of your site.
>
>
>
> ```
> define('WP_HOME','http://example.com');
> define('WP_SITEURL','http://example.com');
>
> ```
>
>
After that, using code in a regular theme that checks the `siteurl` or `home` option will pull from the constant rather than the database (hence my note on the override above). But in your default error script, you can reference `WP_SITEURL` directly to build a redirect URL. |
241,152 | <p>Have a SQL dataset like this:</p>
<pre><code> Title Author Device1 Device2 Device3
Title1 j cool inputA inputA inputB
Title2 l maker inputA inputB inputC
Title3 m smith inputB inputB inputB
</code></pre>
<p>Want to display like this:</p>
<pre><code> Title Author header1 header2 header3
Title1 j cool inputA: inputB:
Device1 Device3
Device2
Title2 l maker inputA: inputB: inputC:
Device1 Device2 Device3
Title3 m smith inputB:
Device1
Device2
Device3
</code></pre>
<p>Have the following php, along with some HTML inside a table, to transliterate into <a href="https://codex.wordpress.org/Class_Reference/wpdb" rel="nofollow"><code>wpdb</code></a>:</p>
<pre><code> $sqlSelect = "SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title";
$myquery = $mysqli->query ($sqlSelect);
if ($myquery = $mysqli->query ($sqlSelect)) {
$result = array();
while($row = mysqli_fetch_assoc($myquery)){
$tmp = array();
foreach (array('device1', 'device2', 'device3', 'device4') as $key) {
if (!isset($tmp[$row[$key]])) $tmp[$row[$key]] = array();
$tmp[$row[$key]][] = $key;
}
$result[$row['title'] . "</td><td>" . $row['author']] = $tmp;
}
$max = 0;
foreach ($result as $data => $inputs) {
$max = max($max, count($inputs));
}
// looping rows begins here
foreach ($result as $data => $inputs) {
print('<tr><td>' . $data . '</td>');
foreach ($inputs as $input => $devices) {
print('<td>' . $input . ':<br/>' . implode('<br/>', $devices) . '</td>');
}
//next two lines are for displaying no cells where there is no $data
for ($i = 0; $i < $max - count($inputs); ++$i) {
print('<td class="db"></td>');
}
print('</tr>');
</code></pre>
<p>Tried this:</p>
<pre><code> $mydb = new wpdb('user','password','database','server');
$results = $mydb -> get_results("SELECT * FROM titles WHERE `active` = 1 ORDER BY author, title");
$result = array();
while ($result = $row) { //this doesn't work; and only one row without data except all devices displays without it
$tmp = array(); //ditto to the end
</code></pre>
<p>WordPress doesn't seem to like <code>$data</code>. Is there a way to do this with <code>wpdb</code>?</p>
| [
{
"answer_id": 241162,
"author": "motorbaby",
"author_id": 103935,
"author_profile": "https://wordpress.stackexchange.com/users/103935",
"pm_score": 0,
"selected": false,
"text": "<p>Got it working by installing the WP DB Driver plugin and skipping <code>wpdb</code> altogether. However, ... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103935/"
] | Have a SQL dataset like this:
```
Title Author Device1 Device2 Device3
Title1 j cool inputA inputA inputB
Title2 l maker inputA inputB inputC
Title3 m smith inputB inputB inputB
```
Want to display like this:
```
Title Author header1 header2 header3
Title1 j cool inputA: inputB:
Device1 Device3
Device2
Title2 l maker inputA: inputB: inputC:
Device1 Device2 Device3
Title3 m smith inputB:
Device1
Device2
Device3
```
Have the following php, along with some HTML inside a table, to transliterate into [`wpdb`](https://codex.wordpress.org/Class_Reference/wpdb):
```
$sqlSelect = "SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title";
$myquery = $mysqli->query ($sqlSelect);
if ($myquery = $mysqli->query ($sqlSelect)) {
$result = array();
while($row = mysqli_fetch_assoc($myquery)){
$tmp = array();
foreach (array('device1', 'device2', 'device3', 'device4') as $key) {
if (!isset($tmp[$row[$key]])) $tmp[$row[$key]] = array();
$tmp[$row[$key]][] = $key;
}
$result[$row['title'] . "</td><td>" . $row['author']] = $tmp;
}
$max = 0;
foreach ($result as $data => $inputs) {
$max = max($max, count($inputs));
}
// looping rows begins here
foreach ($result as $data => $inputs) {
print('<tr><td>' . $data . '</td>');
foreach ($inputs as $input => $devices) {
print('<td>' . $input . ':<br/>' . implode('<br/>', $devices) . '</td>');
}
//next two lines are for displaying no cells where there is no $data
for ($i = 0; $i < $max - count($inputs); ++$i) {
print('<td class="db"></td>');
}
print('</tr>');
```
Tried this:
```
$mydb = new wpdb('user','password','database','server');
$results = $mydb -> get_results("SELECT * FROM titles WHERE `active` = 1 ORDER BY author, title");
$result = array();
while ($result = $row) { //this doesn't work; and only one row without data except all devices displays without it
$tmp = array(); //ditto to the end
```
WordPress doesn't seem to like `$data`. Is there a way to do this with `wpdb`? | I see no reason to use wpdb for this, unless your table is in the Wordpress database. Also your code would be much clearer (and therefore less prone to errors) if you separate the fetching of the result into an array, and the processing of this array for transformation, from the generation of the final html output. Separate logic from presentation.
So, first put all data into an array in the standard way:
```
$query = ("SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title");
$results_array = array();
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
$results_array[] = $row;
}
```
The first row of this array, i.e. `$results_array[0]`, for example, will be the array `('Title' => 'Title 1','Author' => 'j cool', 'Device1' => 'inputA',...)`
**Edit**: Alternatively, if you insist on using the wpdb class, replace the above code by:
```
$mydb = new wpdb('user','password','database','server');
$results_array = $mydb->get_results("SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title",ARRAY_A);
```
`$results_array` has the same content with both approaches. The rest of the code doesn't change.
**End edit**
You want to obtain from `$results_array` an associative array that associates to each Author a table mapping input to devices, like this:
```
array('j cool' => array('inputA' => array('Device1', 'Device2'),
'inputB' => array('Device3')),
'l maker' => array('inputA' => array('Device1'),
'inputB' => array('Device2'),
'inputC' => array('Device3')),
'm this' => ...)
```
The following code assumes you know all possible values of inputs in advance, and that these do not match exactly authors or titles.
```
$inputs = array('inputA','inputB','inputC');
$input_table = array();
foreach ($results_array as $row) {
$row_inputs = array();
foreach ($inputs as $in) {
//get all keys (devices) in $row that have input $in as value
$devices = array_keys($row,$in);
if (!empty($devices))
$row_inputs[$in] = $devices;
}
$input_table[$row['Author']] = $row_inputs;
}
```
This generates an array where each row, indexed by the Author, is an array like the example above. Now we add the title:
```
$final_table = array();
foreach ($results_array as $row) {
$final_table[] = array('Title' => $row['Title'],
'Author' => $row['Author'],
'Inputs' => $input_table[$row['Author']]);
}
```
Finally, display the resulting array in html:
```
$html = '';
//$html .= '<html><body>';
$html .= "<table>"; //add here code for table headers too
foreach ($final_table as $row) {
//first row for author
$html .= '<tr><td>'. $row['Title'] . '</td><td>' . $row['Author'] . '</td>';
foreach (array_keys($row['Inputs']) as $in) {
//output input names for this author
$html .= '<td>'.$in.'</td>';
}
$html .= '</tr><td></td><td></td>';
//second row for author, starting in third column
foreach ($row['Inputs'] as $in => $devices) {
$html .= '<td>'.implode(" ",$devices).'</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
// $html .= </body></html>
echo $html;
```
Fine-tune the presentation at your liking... |
241,161 | <p>I am using WordPress 4.6.1. What tactics can I apply to find all available shortcodes that come with WordPress OOTB. I am having trouble find this information on the web. various guides in the codex and outside of it use simple examples like [gallery], but I am curious to knowing what is my full available list.</p>
<p>Thanks</p>
| [
{
"answer_id": 241162,
"author": "motorbaby",
"author_id": 103935,
"author_profile": "https://wordpress.stackexchange.com/users/103935",
"pm_score": 0,
"selected": false,
"text": "<p>Got it working by installing the WP DB Driver plugin and skipping <code>wpdb</code> altogether. However, ... | 2016/09/30 | [
"https://wordpress.stackexchange.com/questions/241161",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
] | I am using WordPress 4.6.1. What tactics can I apply to find all available shortcodes that come with WordPress OOTB. I am having trouble find this information on the web. various guides in the codex and outside of it use simple examples like [gallery], but I am curious to knowing what is my full available list.
Thanks | I see no reason to use wpdb for this, unless your table is in the Wordpress database. Also your code would be much clearer (and therefore less prone to errors) if you separate the fetching of the result into an array, and the processing of this array for transformation, from the generation of the final html output. Separate logic from presentation.
So, first put all data into an array in the standard way:
```
$query = ("SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title");
$results_array = array();
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
$results_array[] = $row;
}
```
The first row of this array, i.e. `$results_array[0]`, for example, will be the array `('Title' => 'Title 1','Author' => 'j cool', 'Device1' => 'inputA',...)`
**Edit**: Alternatively, if you insist on using the wpdb class, replace the above code by:
```
$mydb = new wpdb('user','password','database','server');
$results_array = $mydb->get_results("SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title",ARRAY_A);
```
`$results_array` has the same content with both approaches. The rest of the code doesn't change.
**End edit**
You want to obtain from `$results_array` an associative array that associates to each Author a table mapping input to devices, like this:
```
array('j cool' => array('inputA' => array('Device1', 'Device2'),
'inputB' => array('Device3')),
'l maker' => array('inputA' => array('Device1'),
'inputB' => array('Device2'),
'inputC' => array('Device3')),
'm this' => ...)
```
The following code assumes you know all possible values of inputs in advance, and that these do not match exactly authors or titles.
```
$inputs = array('inputA','inputB','inputC');
$input_table = array();
foreach ($results_array as $row) {
$row_inputs = array();
foreach ($inputs as $in) {
//get all keys (devices) in $row that have input $in as value
$devices = array_keys($row,$in);
if (!empty($devices))
$row_inputs[$in] = $devices;
}
$input_table[$row['Author']] = $row_inputs;
}
```
This generates an array where each row, indexed by the Author, is an array like the example above. Now we add the title:
```
$final_table = array();
foreach ($results_array as $row) {
$final_table[] = array('Title' => $row['Title'],
'Author' => $row['Author'],
'Inputs' => $input_table[$row['Author']]);
}
```
Finally, display the resulting array in html:
```
$html = '';
//$html .= '<html><body>';
$html .= "<table>"; //add here code for table headers too
foreach ($final_table as $row) {
//first row for author
$html .= '<tr><td>'. $row['Title'] . '</td><td>' . $row['Author'] . '</td>';
foreach (array_keys($row['Inputs']) as $in) {
//output input names for this author
$html .= '<td>'.$in.'</td>';
}
$html .= '</tr><td></td><td></td>';
//second row for author, starting in third column
foreach ($row['Inputs'] as $in => $devices) {
$html .= '<td>'.implode(" ",$devices).'</td>';
}
$html .= '</tr>';
}
$html .= '</table>';
// $html .= </body></html>
echo $html;
```
Fine-tune the presentation at your liking... |
241,184 | <p>I am currently looking into passing a single query into multiple widgets on a template without running multiple queries. The obvious goal is speed and efficiency.</p>
<p>I have a widget that will deliver specific aspects of the same object with different instances of the widget in the template. Widget instances are a <strong>must</strong>, but the object instance should remain unchanged. Is there a sweet spot in the template run of actions and filters I should look for in my widget?</p>
<p>For example, I want <code>object->title</code> to show in my widget at the top of the page, so I check that box and so to show in that area. Then I have another instance of the widget where I check <code>object->content</code> to show in that area.</p>
<p>That's very easy inside of the widget, however, very inefficient because I just ran two queries for the same object, because of my widgets being two different objects unto themselves.</p>
<p>How can my widget not attempt the same query twice in this situation? Will <code>get_queried_object</code> run a query for both of those widget instances? </p>
| [
{
"answer_id": 241188,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>I suggest to use the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\" rel=\"nofollow\">... | 2016/10/01 | [
"https://wordpress.stackexchange.com/questions/241184",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27196/"
] | I am currently looking into passing a single query into multiple widgets on a template without running multiple queries. The obvious goal is speed and efficiency.
I have a widget that will deliver specific aspects of the same object with different instances of the widget in the template. Widget instances are a **must**, but the object instance should remain unchanged. Is there a sweet spot in the template run of actions and filters I should look for in my widget?
For example, I want `object->title` to show in my widget at the top of the page, so I check that box and so to show in that area. Then I have another instance of the widget where I check `object->content` to show in that area.
That's very easy inside of the widget, however, very inefficient because I just ran two queries for the same object, because of my widgets being two different objects unto themselves.
How can my widget not attempt the same query twice in this situation? Will `get_queried_object` run a query for both of those widget instances? | I suggest to use the [Object Cache API](https://codex.wordpress.org/Class_Reference/WP_Object_Cache) or [Transients API](https://codex.wordpress.org/Transients_API), whatever fits better your needs.
A very quick example with object cache:
```
// helper function
function get_my_object() {
$object = wp_cache_get( 'my_object' );
if ( false === $object ) {
$args = array( .... );
$object = new WP_Query( $args );
wp_cache_set( 'my_object', $object );
}
return $object;
}
class cyb_my_widget extends WP_Widget {
function __construct() {
// ...
}
function widget( $args, $instance ) {
// ...
$object = get_my_object();
}
function update( $new_instance, $old_instance ) {
// ...
}
function form( $instance ) {
// ...
}
}
``` |
241,267 | <p>I’m having a complex content issue. Each page can have multiple sections (unknown number), each section can have multiple containers, each container can have multiple content blocks (either 1, 2 or 3).</p>
<p>I’ve currently got a theoretical solution with shortcodes, but I would like to solve this with the UI if possible by providing wysiwyg editors for each content block.</p>
<p>Sections: There can be any number of sections (a realistic/acceptable maximum would be 10).
Containers: A section can contain any number of rows (a realistic/acceptable maximum would be 5).
Containers: A row must know how many columns it needs to contain.
Content blocks: A row can contain 1, 2 or 3 columns.</p>
<p>The shortcode solution looks something like this:</p>
<pre><code>[section id="summary"] //id is required but can be anything (no spaces)
[container blocks="1"] //row can have 1, 2 or 3 columns
[block]
.content-block
[/block]
[/container]
[/section]
[section id="find us"] //id is required but can be anything (no spaces)
[container blocks="3"] //row can have 1, 2 or 3 columns
[block]
.content-block
[/block]
[block]
.content-block
[/block]
[block]
.content-block
[/block]
[/container]
[/section]
[section id="team"] //id is required but can be anything (no spaces)
[container blocks="2"] //row can have 1, 2 or 3 columns
[block]
.content-block
[/block]
[block]
.content-block
[/block]
[/container]
[/section]
</code></pre>
<p>Does anyone have any suggestions on how I can go about this?</p>
<p>Thanks,
Josh</p>
| [
{
"answer_id": 241281,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>It's easier to code the Visual Editor so your content editors can highlight parts of the post con... | 2016/10/02 | [
"https://wordpress.stackexchange.com/questions/241267",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104083/"
] | I’m having a complex content issue. Each page can have multiple sections (unknown number), each section can have multiple containers, each container can have multiple content blocks (either 1, 2 or 3).
I’ve currently got a theoretical solution with shortcodes, but I would like to solve this with the UI if possible by providing wysiwyg editors for each content block.
Sections: There can be any number of sections (a realistic/acceptable maximum would be 10).
Containers: A section can contain any number of rows (a realistic/acceptable maximum would be 5).
Containers: A row must know how many columns it needs to contain.
Content blocks: A row can contain 1, 2 or 3 columns.
The shortcode solution looks something like this:
```
[section id="summary"] //id is required but can be anything (no spaces)
[container blocks="1"] //row can have 1, 2 or 3 columns
[block]
.content-block
[/block]
[/container]
[/section]
[section id="find us"] //id is required but can be anything (no spaces)
[container blocks="3"] //row can have 1, 2 or 3 columns
[block]
.content-block
[/block]
[block]
.content-block
[/block]
[block]
.content-block
[/block]
[/container]
[/section]
[section id="team"] //id is required but can be anything (no spaces)
[container blocks="2"] //row can have 1, 2 or 3 columns
[block]
.content-block
[/block]
[block]
.content-block
[/block]
[/container]
[/section]
```
Does anyone have any suggestions on how I can go about this?
Thanks,
Josh | This sounds to me like a perfect use of [Advanced Custom Fields "flexible content"](https://www.advancedcustomfields.com/resources/flexible-content/) feature to me. Flexible content fields allow you to define multiple layouts, and then add them to a page or post one by one, in any order or combination you need. Each layout can be a combination of text fields, images, wysiwyg editors, and other field types.
It's a brilliant UI on the client side, and easy to build a custom front-end in your template once you get the hang of it.
It's a premium plugin, but I've been building these kinds of interfaces for many years and it works really well. I haven't found anything else quite like it. |
241,269 | <p>I have a plugin which requires a style sheet for the widget. I am trying to register the stylesheet when the widget is created, however the style sheet is not being queued and the styles ignored. The code I am using follows, with commented lines demonstrating some other options I have tried:</p>
<p>organiser.php</p>
<pre><code>class Organiser extends WP_Widget {
...
public function widget( $args, $instance ) {
add_action( 'wp_enqueue_scripts', array('Organiser', 'register_plugin_styles') );
include(dirname(__FILE__)."/organiserWidget.php");
}
function register_plugin_styles() {
wp_register_style( 'organiserStyle', plugins_url( 'organiser/css/organiserStyle.css' ) );
wp_enqueue_style( 'organiserStyle' );
// wp_register_style( 'organiserStyle', plugin_dir_url( __FILE__ ) . 'css/organiserStyle.css' );
// wp_enqueue_style( 'organiserStyle', plugin_dir_url( __FILE__ ) . 'css/organiserStyle.css');
}
....
}
</code></pre>
<p>organiserWidget.php</p>
<pre><code><div id="organiser">
</div>
</code></pre>
<p>css/organiserStyle.css</p>
<pre><code>@import "mobile-layout.css";
</code></pre>
<p>css/mobile-layout.css</p>
<pre><code>@media screen and (max-width: 420px) {
div#organiser {
width: 100%;
height: 240px;
}
}
</code></pre>
<p>As far as I can see, this is following what the documentation recommends and I so far haven't been able to find anything to suggest that I am doing something wrong.</p>
| [
{
"answer_id": 241281,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>It's easier to code the Visual Editor so your content editors can highlight parts of the post con... | 2016/10/02 | [
"https://wordpress.stackexchange.com/questions/241269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104085/"
] | I have a plugin which requires a style sheet for the widget. I am trying to register the stylesheet when the widget is created, however the style sheet is not being queued and the styles ignored. The code I am using follows, with commented lines demonstrating some other options I have tried:
organiser.php
```
class Organiser extends WP_Widget {
...
public function widget( $args, $instance ) {
add_action( 'wp_enqueue_scripts', array('Organiser', 'register_plugin_styles') );
include(dirname(__FILE__)."/organiserWidget.php");
}
function register_plugin_styles() {
wp_register_style( 'organiserStyle', plugins_url( 'organiser/css/organiserStyle.css' ) );
wp_enqueue_style( 'organiserStyle' );
// wp_register_style( 'organiserStyle', plugin_dir_url( __FILE__ ) . 'css/organiserStyle.css' );
// wp_enqueue_style( 'organiserStyle', plugin_dir_url( __FILE__ ) . 'css/organiserStyle.css');
}
....
}
```
organiserWidget.php
```
<div id="organiser">
</div>
```
css/organiserStyle.css
```
@import "mobile-layout.css";
```
css/mobile-layout.css
```
@media screen and (max-width: 420px) {
div#organiser {
width: 100%;
height: 240px;
}
}
```
As far as I can see, this is following what the documentation recommends and I so far haven't been able to find anything to suggest that I am doing something wrong. | This sounds to me like a perfect use of [Advanced Custom Fields "flexible content"](https://www.advancedcustomfields.com/resources/flexible-content/) feature to me. Flexible content fields allow you to define multiple layouts, and then add them to a page or post one by one, in any order or combination you need. Each layout can be a combination of text fields, images, wysiwyg editors, and other field types.
It's a brilliant UI on the client side, and easy to build a custom front-end in your template once you get the hang of it.
It's a premium plugin, but I've been building these kinds of interfaces for many years and it works really well. I haven't found anything else quite like it. |
241,271 | <p>I'm using <a href="https://wordpress.org/plugins/json-rest-api/" rel="noreferrer">wp-rest api</a> to get posts information.
I also use <a href="https://github.com/bueltge/wp-rest-api-filter-items" rel="noreferrer">wp rest api filter items</a> to filter fields and summarize the result:</p>
<p>When I call <code>http://example.com/wp-json/wp/v2/posts?items=id,title,featured_media</code> it returns results like this:</p>
<pre><code>[
{
"id": 407,
"title": {
"rendered": "Title 1"
},
"featured_media": 399
},
{
"id": 403,
"title": {
"rendered": "Title 2"
},
"featured_media": 401
}
]
</code></pre>
<p>The question is how can I generate featured media url using this id? By default calling <code>http://example.com/wp-json/wp/v2/media/401</code> returns a new json which have all details about url of different sizes of source image:</p>
<pre><code>{
"id": 401,
"date": "2016-06-03T17:29:09",
"date_gmt": "2016-06-03T17:29:09",
"guid": {
"rendered": "http://example.com/wp-content/uploads/my-image-name.png"
},
"modified": "2016-06-03T17:29:09",
"modified_gmt": "2016-06-03T17:29:09",
"slug": "my-image-name",
"type": "attachment",
"link": "http://example.com/my-post-url",
"title": {
"rendered": "my-image-name"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"alt_text": "",
"caption": "",
"description": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 550,
"height": 250,
"file": "my-image-name.png",
"sizes": {
"thumbnail": {
"file": "my-image-name-150x150.png",
"width": 150,
"height": 150,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-150x150.png"
},
"medium": {
"file": "my-image-name-300x136.png",
"width": 300,
"height": 136,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-300x136.png"
},
"one-paze-port-thumb": {
"file": "my-image-name-363x250.png",
"width": 363,
"height": 250,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-363x250.png"
},
"one-paze-blog-thumb": {
"file": "my-image-name-270x127.png",
"width": 270,
"height": 127,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-270x127.png"
},
"one-paze-team-thumb": {
"file": "my-image-name-175x175.png",
"width": 175,
"height": 175,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-175x175.png"
},
"one-paze-testimonial-thumb": {
"file": "my-image-name-79x79.png",
"width": 79,
"height": 79,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-79x79.png"
},
"one-paze-blog-medium-image": {
"file": "my-image-name-380x250.png",
"width": 380,
"height": 250,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-380x250.png"
},
"full": {
"file": "my-image-name.png",
"width": 550,
"height": 250,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0",
"keywords": [ ]
}
},
"post": 284,
"source_url": "http://example.com/wp-content/uploads/my-image-name.png",
"_links": {
"self": [
{
"href": "http://example.com/wp-json/wp/v2/media/401"
}
],
"collection": [
{
"href": "http://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"href": "http://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"embeddable": true,
"href": "http://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"embeddable": true,
"href": "http://example.com/wp-json/wp/v2/comments?post=401"
}
]
}
}
</code></pre>
<p>But consider the case when I want to get list of posts and their thumbnails. One time I should call <code>http://example.com/wp-json/wp/v2/posts?items=id,title,featured_media</code> then I should call <code>http://example.com/wp-json/wp/v2/media/id</code> 10 times for each media id and then parse the results and get final url of media thumbnail. So it needs 11 request for get details of 10 post (one for list,10 for thumbnails).
Is it possible to get this results in one request?</p>
| [
{
"answer_id": 241422,
"author": "Jesús Franco",
"author_id": 16301,
"author_profile": "https://wordpress.stackexchange.com/users/16301",
"pm_score": 4,
"selected": false,
"text": "<p>Just add the <code>_embed</code> query argument to your URL asking for the posts, and every post object,... | 2016/10/02 | [
"https://wordpress.stackexchange.com/questions/241271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86163/"
] | I'm using [wp-rest api](https://wordpress.org/plugins/json-rest-api/) to get posts information.
I also use [wp rest api filter items](https://github.com/bueltge/wp-rest-api-filter-items) to filter fields and summarize the result:
When I call `http://example.com/wp-json/wp/v2/posts?items=id,title,featured_media` it returns results like this:
```
[
{
"id": 407,
"title": {
"rendered": "Title 1"
},
"featured_media": 399
},
{
"id": 403,
"title": {
"rendered": "Title 2"
},
"featured_media": 401
}
]
```
The question is how can I generate featured media url using this id? By default calling `http://example.com/wp-json/wp/v2/media/401` returns a new json which have all details about url of different sizes of source image:
```
{
"id": 401,
"date": "2016-06-03T17:29:09",
"date_gmt": "2016-06-03T17:29:09",
"guid": {
"rendered": "http://example.com/wp-content/uploads/my-image-name.png"
},
"modified": "2016-06-03T17:29:09",
"modified_gmt": "2016-06-03T17:29:09",
"slug": "my-image-name",
"type": "attachment",
"link": "http://example.com/my-post-url",
"title": {
"rendered": "my-image-name"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"alt_text": "",
"caption": "",
"description": "",
"media_type": "image",
"mime_type": "image/png",
"media_details": {
"width": 550,
"height": 250,
"file": "my-image-name.png",
"sizes": {
"thumbnail": {
"file": "my-image-name-150x150.png",
"width": 150,
"height": 150,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-150x150.png"
},
"medium": {
"file": "my-image-name-300x136.png",
"width": 300,
"height": 136,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-300x136.png"
},
"one-paze-port-thumb": {
"file": "my-image-name-363x250.png",
"width": 363,
"height": 250,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-363x250.png"
},
"one-paze-blog-thumb": {
"file": "my-image-name-270x127.png",
"width": 270,
"height": 127,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-270x127.png"
},
"one-paze-team-thumb": {
"file": "my-image-name-175x175.png",
"width": 175,
"height": 175,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-175x175.png"
},
"one-paze-testimonial-thumb": {
"file": "my-image-name-79x79.png",
"width": 79,
"height": 79,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-79x79.png"
},
"one-paze-blog-medium-image": {
"file": "my-image-name-380x250.png",
"width": 380,
"height": 250,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name-380x250.png"
},
"full": {
"file": "my-image-name.png",
"width": 550,
"height": 250,
"mime_type": "image/png",
"source_url": "http://example.com/wp-content/uploads/my-image-name.png"
}
},
"image_meta": {
"aperture": "0",
"credit": "",
"camera": "",
"caption": "",
"created_timestamp": "0",
"copyright": "",
"focal_length": "0",
"iso": "0",
"shutter_speed": "0",
"title": "",
"orientation": "0",
"keywords": [ ]
}
},
"post": 284,
"source_url": "http://example.com/wp-content/uploads/my-image-name.png",
"_links": {
"self": [
{
"href": "http://example.com/wp-json/wp/v2/media/401"
}
],
"collection": [
{
"href": "http://example.com/wp-json/wp/v2/media"
}
],
"about": [
{
"href": "http://example.com/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"embeddable": true,
"href": "http://example.com/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"embeddable": true,
"href": "http://example.com/wp-json/wp/v2/comments?post=401"
}
]
}
}
```
But consider the case when I want to get list of posts and their thumbnails. One time I should call `http://example.com/wp-json/wp/v2/posts?items=id,title,featured_media` then I should call `http://example.com/wp-json/wp/v2/media/id` 10 times for each media id and then parse the results and get final url of media thumbnail. So it needs 11 request for get details of 10 post (one for list,10 for thumbnails).
Is it possible to get this results in one request? | Ah I just had this problem myself! And while `_embed` is great, in my experience it is very slow, and the point of JSON is to be fast :D
I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's `function.php` file.
`php`
```
add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field(
'post', // Where to add the field (Here, blog posts. Could be an array)
'featured_image_src', // Name of new field (You can call this anything)
array(
'get_callback' => 'get_image_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_image_src( $object, $field_name, $request ) {
$feat_img_array = wp_get_attachment_image_src(
$object['featured_media'], // Image attachment ID
'thumbnail', // Size. Ex. "thumbnail", "large", "full", etc..
true // Whether the image should be treated as an icon.
);
return $feat_img_array[0];
}
```
Now in your JSON response you should see a new field called `"featured_image_src":` containing a url to the thumbnail.
Read more about modifying responses here:
<http://v2.wp-api.org/extending/modifying/>
And here's more information on the`register_rest_field` and `wp_get_attachment_image_src()` functions:
1.) <https://developer.wordpress.org/reference/functions/register_rest_field/>
2.) <https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/>
\*\*Note: Don't forget `<?php ?>` tags if this is a new php file! |
241,287 | <p>To get with the time and improve my coding practices, I'm starting to implementing <a href="https://secure.php.net/manual/en/language.namespaces.php" rel="nofollow">namespaces</a> in my own plugins moving forward since there are some advantages, <a href="https://stackoverflow.com/q/5393108/6579923">such as eliminating ambiguity</a>.</p>
<p>I found a <a href="https://wordpress.stackexchange.com/q/193997/98212">similar question</a> to help me set up my plugin template which worked for me. However, I've since modified it slightly. This is my setup:</p>
<p>In <code>wp-plugin-template/wp-plugin-template.php</code>:</p>
<pre><code><?php
/**
* Plugin Name: WP Plugin Template
*/
# If accessed directly, exit
if ( ! defined( 'ABSPATH' ) ) exit;
# Call the autoloader
require_once( 'autoloader.php' );
use PluginTemplate\admin\Plugin_Meta;
new Plugin_Meta;
</code></pre>
<p>In <code>wp-plugin-template/autoloader.php</code>:</p>
<pre><code><?php
spl_autoload_register( 'autoload_function' );
function autoload_function( $classname ) {
$class = str_replace( '\\', DIRECTORY_SEPARATOR, str_replace( '_', '-', strtolower($classname) ) );
# Create the actual file-path
$path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $class . '.php';
# Check if the file exists
if ( file_exists( $path ) ) {
# Require once on the file
require_once $path;
}
}
</code></pre>
<p>In <code>wp-plugin-template/admin/plugin-meta.php</code>:</p>
<pre><code><?php
namespace PluginTemplate\admin;
class Plugin_Meta {
public function __construct() {
add_action( 'plugins_loaded', array($this, 'test' ) );
}
public function test() {
echo 'It works!';
}
}
</code></pre>
<p>When I try to activate the plugin template for testing, I get the following error:</p>
<blockquote>
<p><strong>Fatal error</strong>: Class <code>PluginTemplate\admin\Plugin_Meta</code> not found in <code>wp-content/plugins/wp-plugin-template/wp-plugin-template.php</code> on <em>line 11</em></p>
</blockquote>
<p>In this case, line 11 is:</p>
<pre><code>new Plugin_Meta;
</code></pre>
<p>I think this is due to me having the namespace named <code>PluginTemplate</code>? What am I doing wrong? Just to reiterate, <a href="https://wordpress.stackexchange.com/q/193997/98212">the previous question that I mentioned</a> worked for me before I started to rename my files and directories.</p>
| [
{
"answer_id": 241294,
"author": "C Sabhar",
"author_id": 103830,
"author_profile": "https://wordpress.stackexchange.com/users/103830",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is with your Autoloader set-up. You need to convert your Camelcase namespacese to dashes for lo... | 2016/10/02 | [
"https://wordpress.stackexchange.com/questions/241287",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | To get with the time and improve my coding practices, I'm starting to implementing [namespaces](https://secure.php.net/manual/en/language.namespaces.php) in my own plugins moving forward since there are some advantages, [such as eliminating ambiguity](https://stackoverflow.com/q/5393108/6579923).
I found a [similar question](https://wordpress.stackexchange.com/q/193997/98212) to help me set up my plugin template which worked for me. However, I've since modified it slightly. This is my setup:
In `wp-plugin-template/wp-plugin-template.php`:
```
<?php
/**
* Plugin Name: WP Plugin Template
*/
# If accessed directly, exit
if ( ! defined( 'ABSPATH' ) ) exit;
# Call the autoloader
require_once( 'autoloader.php' );
use PluginTemplate\admin\Plugin_Meta;
new Plugin_Meta;
```
In `wp-plugin-template/autoloader.php`:
```
<?php
spl_autoload_register( 'autoload_function' );
function autoload_function( $classname ) {
$class = str_replace( '\\', DIRECTORY_SEPARATOR, str_replace( '_', '-', strtolower($classname) ) );
# Create the actual file-path
$path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $class . '.php';
# Check if the file exists
if ( file_exists( $path ) ) {
# Require once on the file
require_once $path;
}
}
```
In `wp-plugin-template/admin/plugin-meta.php`:
```
<?php
namespace PluginTemplate\admin;
class Plugin_Meta {
public function __construct() {
add_action( 'plugins_loaded', array($this, 'test' ) );
}
public function test() {
echo 'It works!';
}
}
```
When I try to activate the plugin template for testing, I get the following error:
>
> **Fatal error**: Class `PluginTemplate\admin\Plugin_Meta` not found in `wp-content/plugins/wp-plugin-template/wp-plugin-template.php` on *line 11*
>
>
>
In this case, line 11 is:
```
new Plugin_Meta;
```
I think this is due to me having the namespace named `PluginTemplate`? What am I doing wrong? Just to reiterate, [the previous question that I mentioned](https://wordpress.stackexchange.com/q/193997/98212) worked for me before I started to rename my files and directories. | The problem is with your Autoloader set-up. You need to convert your Camelcase namespacese to dashes for locating files as per your current folder structure.
I have added convert function and updated your autoloader function.
In `wp-plugin-template/autoloader.php`:
```
<?php
spl_autoload_register( 'autoload_function' );
function autoload_function( $classname ) {
$class = str_replace( '\\', DIRECTORY_SEPARATOR, str_replace( '_', '-', strtolower(convert($classname)) ) );
# Create the actual file-path
$path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $class . '.php';
# Check if the file exists
if ( file_exists( $path ) ) {
# Require once on the file
require_once $path;
}
}
function convert($class){
$class = preg_replace('#([A-Z\d]+)([A-Z][a-z])#','\1_\2', $class);
$class = preg_replace('#([a-z\d])([A-Z])#', '\1_\2', $class);
return $class;
}
```
Also you have to update your top level namespace to `WpPluginTemplate` in both `wp-plugin-template.php` and `admin/plugin-meta.php` as you are using wp-plugin-template as your plugin folder name.
UPDATE:
When autoloader tries to find `Plugin_Meta` class, it will look into YOUR\_PLUGIN\_DIR/wp-plugin-template/admin/plugin-meta.php
In `wp-plugin-template.php`
```
<?php
/**
* Plugin Name: WP Plugin Template
*/
# If accessed directly, exit
if ( ! defined( 'ABSPATH' ) ) exit;
# Call the autoloader
require_once( 'autoloader.php' );
use WpPluginTemplate\admin\Plugin_Meta;
new Plugin_Meta;
```
In `wp-plugin-template/admin/plugin-meta.php`
```
<?php
namespace WpPluginTemplate\admin;
class Plugin_Meta {
public function __construct() {
add_action( 'plugins_loaded', array($this, 'test' ) );
}
public function test() {
echo 'It works!';
}
}
``` |
241,303 | <p>Our WordPress website has a static html home page. A request for the domain returns the <code>index.html</code> page.</p>
<p>This has served our purposes well, but has caused a problem when trying to preview a post or page during editing. Since the preview URLs do not include <code>index.php</code> all preview requests display the static home page; e.g., </p>
<pre><code>http://www.example.com/?page_id=7848&preview=true
</code></pre>
<p>OR</p>
<pre><code>http://www.example.com/?post_type=solution&p=6480&preview_id=6480&preview_nonce=730eb2844c&preview=true
</code></pre>
<p>Both display the home page. Manually inserting <code>index.php</code> between <code>www.example.com/</code> and <code>?<querystring></code> works and display the page preview, but it is a pain.</p>
<p>I have tried the following in <code>functions.php</code>, which does update the <code>.htaccess</code> file, but the home page still appears.</p>
<pre><code>function custom_rewrite_preview( )
{
add_rewrite_rule(
'(.*)\?(.+)&preview=true$',
'$1index.php?$2&preview=false',
'bottom'
);
}
add_action( 'init', 'custom_rewrite_preview' );
</code></pre>
<p>I am unsure whether the function and/or regex are wrong, or that the rewrite needs to occur at a different time.</p>
| [
{
"answer_id": 241304,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>You can add the following rewrite rule in your <code>.htaccess</code>:</p>\n\n<pre><code><IfModul... | 2016/10/02 | [
"https://wordpress.stackexchange.com/questions/241303",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104100/"
] | Our WordPress website has a static html home page. A request for the domain returns the `index.html` page.
This has served our purposes well, but has caused a problem when trying to preview a post or page during editing. Since the preview URLs do not include `index.php` all preview requests display the static home page; e.g.,
```
http://www.example.com/?page_id=7848&preview=true
```
OR
```
http://www.example.com/?post_type=solution&p=6480&preview_id=6480&preview_nonce=730eb2844c&preview=true
```
Both display the home page. Manually inserting `index.php` between `www.example.com/` and `?<querystring>` works and display the page preview, but it is a pain.
I have tried the following in `functions.php`, which does update the `.htaccess` file, but the home page still appears.
```
function custom_rewrite_preview( )
{
add_rewrite_rule(
'(.*)\?(.+)&preview=true$',
'$1index.php?$2&preview=false',
'bottom'
);
}
add_action( 'init', 'custom_rewrite_preview' );
```
I am unsure whether the function and/or regex are wrong, or that the rewrite needs to occur at a different time. | Don't change your rewrites. Put the content of the HTML file into a front-page.php template file in your theme. |
241,326 | <p>I have a simple plugin which adds a signature at the end of each post. But it also appears after user comment section. How to avoid the latter?</p>
<p><strong>Update</strong></p>
<p>I have tried to run the function once by adding a static variable. Now signature is just adding to comment section. I need exactly the reverse. Hope this helps.</p>
<pre><code><?php
/*
header...
*/
if( !function_exists("add_signature")){
function add_signature($content){
/* code related to update
static $once;
if ( $once !== null )
return $content;
else
$once = 'done';
*/
if( !is_page() )
return $content . "signature";
}
add_filter('the_content', 'add_signature');
}
?>
</code></pre>
| [
{
"answer_id": 241304,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>You can add the following rewrite rule in your <code>.htaccess</code>:</p>\n\n<pre><code><IfModul... | 2016/10/03 | [
"https://wordpress.stackexchange.com/questions/241326",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32602/"
] | I have a simple plugin which adds a signature at the end of each post. But it also appears after user comment section. How to avoid the latter?
**Update**
I have tried to run the function once by adding a static variable. Now signature is just adding to comment section. I need exactly the reverse. Hope this helps.
```
<?php
/*
header...
*/
if( !function_exists("add_signature")){
function add_signature($content){
/* code related to update
static $once;
if ( $once !== null )
return $content;
else
$once = 'done';
*/
if( !is_page() )
return $content . "signature";
}
add_filter('the_content', 'add_signature');
}
?>
``` | Don't change your rewrites. Put the content of the HTML file into a front-page.php template file in your theme. |
241,353 | <p>I want to add a new image size option to the contents image editor. The code below is what I currently have but for some reason I am not seeing the option (as shown in the image below) in the editor. I am using WordPress Version 4.6.1. What could be the problem? Thanks in advance.</p>
<p><a href="https://i.stack.imgur.com/HqWsm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HqWsm.png" alt="enter image description here"></a></p>
<pre><code> add_image_size( 'activity-image', 300, 300, array( 'center', 'center' ) );
// Add new image sizes to post or page editor
function new_image_sizes($sizes) {
return array_merge( $sizes, array(
'activity-image' => __( 'Activity Image' ),
) );
}
add_filter('image_size_names_chooser', 'new_image_sizes');
</code></pre>
| [
{
"answer_id": 241358,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>You need to register the image size first using <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-creat... | 2016/10/03 | [
"https://wordpress.stackexchange.com/questions/241353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99178/"
] | I want to add a new image size option to the contents image editor. The code below is what I currently have but for some reason I am not seeing the option (as shown in the image below) in the editor. I am using WordPress Version 4.6.1. What could be the problem? Thanks in advance.
[](https://i.stack.imgur.com/HqWsm.png)
```
add_image_size( 'activity-image', 300, 300, array( 'center', 'center' ) );
// Add new image sizes to post or page editor
function new_image_sizes($sizes) {
return array_merge( $sizes, array(
'activity-image' => __( 'Activity Image' ),
) );
}
add_filter('image_size_names_chooser', 'new_image_sizes');
``` | You need to register the image size first using [`add_image_size()`](http://www.wpbeginner.com/wp-tutorials/how-to-create-additional-image-sizes-in-wordpress/), for example:
```
add_action( 'after_setup_theme', 'cyb_add_image_sizes' );
function cyb_add_image_sizes() {
add_image_size( 'my-image-size-name', 120, 120, true );
}
```
Then, you can use the `image_size_names_choose` filter (you have misspelled it with `image_size_names_chooser`):
```
add_filter( 'image_size_names_choose', 'rudr_new_image_sizes' );
function rudr_new_image_sizes( $sizes ) {
$addsizes = array(
"my-image-size-name" => 'Misha size'
);
$newsizes = array_merge( $sizes, $addsizes );
return $newsizes;
}
``` |
241,361 | <p>I have a template with 4 css files: <code>rtl.css</code>, <code>style.css</code>, <code>main.css</code>, <code>bootstrap.css</code>.</p>
<p><code>rtl.css</code> and <code>style.css</code> are located in my template root, for example:
<code>my_template_root/style.css</code>.</p>
<p><code>main.css</code> and <code>bootstrap.css</code> are located, for example:
<code>my_template_root/assets/stylesheet/main.css</code></p>
<p><code>functions.php</code> code is:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_directory_directory_uri() . 'style.css' );
}
</code></pre>
<p>This <code>functions.php</code> code apply correctly only for <code>rtl.css</code> and <code>style.css</code> but my changes in <code>main.css</code> and <code>bootstrap.css</code> don't work anyway.</p>
| [
{
"answer_id": 241363,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming that your css files are correctly uploaded to your server, the most likely cause for the changes not s... | 2016/10/03 | [
"https://wordpress.stackexchange.com/questions/241361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104076/"
] | I have a template with 4 css files: `rtl.css`, `style.css`, `main.css`, `bootstrap.css`.
`rtl.css` and `style.css` are located in my template root, for example:
`my_template_root/style.css`.
`main.css` and `bootstrap.css` are located, for example:
`my_template_root/assets/stylesheet/main.css`
`functions.php` code is:
```
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_directory_directory_uri() . 'style.css' );
}
```
This `functions.php` code apply correctly only for `rtl.css` and `style.css` but my changes in `main.css` and `bootstrap.css` don't work anyway. | You are calling your css files with wrong function like in following line of your code
```
wp_enqueue_style( 'parent-style', get_directory_directory_uri() . 'style.css' );
```
You are using `get_directory_directory_uri()` function to call files which is not event a function in wordpress.
Files must be called with one of the following two functions
1. **get\_stylesheeet\_directory\_uri()** : This function will search files in your active theme's folder. By active theme means, theme that is activated by user from `dashboard -> appearace -> theme`. In your case child theme is active, so it will search file in your child theme folder.
2. **get\_template\_directory\_uri()** : This function will search files in your parent theme's folder.
If your files are present in child theme's folder then add this code in `functions.php` to call your css files
```
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_stylesheet_uri() ); //It will call your style.css file
wp_enqueue_style( 'style1', get_stylesheeet_directory_uri() . '/rtl.css' );
wp_enqueue_style( 'style2', get_stylesheeet_directory_uri() . '/assets/stylesheet/main.css' );
wp_enqueue_style( 'style3', get_stylesheeet_directory_uri() . '/assets/stylesheet/bootstrap.css' );
}
```
In the above code `parent-style`, `style1`,`style2`,`style1` are the user assign name and that name must be unique.
And in one line only one file will be called, so if you wanna call 4 files then you have to specify path of all files in different lines.
**Note**: If your files are present in Parent theme's then you need to replace `get_stylesheeet_directory_uri` with `get_template_directory_uri` in above code.
For more detail read this [article](https://developer.wordpress.org/themes/basics/including-css-javascript/). |
241,376 | <p>I am using the following code in a page template</p>
<pre><code><?php
$args=array(
'post_parent' => 27641,
'post_type' => 'page',
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
</code></pre>
<p>to get a list of direct child pages for a product listing page.</p>
<p>What do I do if I want all child pages and all grandchildren too? I want to list the children of child pages as well as the direct children.</p>
<p>The obvious answer would be:</p>
<pre><code>'post_ancestor' => 27641,
</code></pre>
<p>or</p>
<pre><code>'post_grandparent' => 27641,
</code></pre>
<p>but unfotunately it's not that simple.</p>
| [
{
"answer_id": 241363,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming that your css files are correctly uploaded to your server, the most likely cause for the changes not s... | 2016/10/03 | [
"https://wordpress.stackexchange.com/questions/241376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94003/"
] | I am using the following code in a page template
```
<?php
$args=array(
'post_parent' => 27641,
'post_type' => 'page',
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
```
to get a list of direct child pages for a product listing page.
What do I do if I want all child pages and all grandchildren too? I want to list the children of child pages as well as the direct children.
The obvious answer would be:
```
'post_ancestor' => 27641,
```
or
```
'post_grandparent' => 27641,
```
but unfotunately it's not that simple. | You are calling your css files with wrong function like in following line of your code
```
wp_enqueue_style( 'parent-style', get_directory_directory_uri() . 'style.css' );
```
You are using `get_directory_directory_uri()` function to call files which is not event a function in wordpress.
Files must be called with one of the following two functions
1. **get\_stylesheeet\_directory\_uri()** : This function will search files in your active theme's folder. By active theme means, theme that is activated by user from `dashboard -> appearace -> theme`. In your case child theme is active, so it will search file in your child theme folder.
2. **get\_template\_directory\_uri()** : This function will search files in your parent theme's folder.
If your files are present in child theme's folder then add this code in `functions.php` to call your css files
```
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_stylesheet_uri() ); //It will call your style.css file
wp_enqueue_style( 'style1', get_stylesheeet_directory_uri() . '/rtl.css' );
wp_enqueue_style( 'style2', get_stylesheeet_directory_uri() . '/assets/stylesheet/main.css' );
wp_enqueue_style( 'style3', get_stylesheeet_directory_uri() . '/assets/stylesheet/bootstrap.css' );
}
```
In the above code `parent-style`, `style1`,`style2`,`style1` are the user assign name and that name must be unique.
And in one line only one file will be called, so if you wanna call 4 files then you have to specify path of all files in different lines.
**Note**: If your files are present in Parent theme's then you need to replace `get_stylesheeet_directory_uri` with `get_template_directory_uri` in above code.
For more detail read this [article](https://developer.wordpress.org/themes/basics/including-css-javascript/). |
241,386 | <p>I made custom post type with one taxonomy. Everything was good except pagination on taxonomy. Firstly, without any changes, I was able to switch pages on main custom post type archive:</p>
<pre><code>website.com/custom_post_type_name/page/x
</code></pre>
<p>But when I wanted to jump to taxonomy and switch pages I got 404 error.</p>
<pre><code>website.com/custom_post_type_name/taxonomy_slug/page/x
</code></pre>
<p>I tried doing regex from answer from StackExchange but it won't work at all.</p>
<pre><code>add_filter( 'rewrite_rules_array', 'my_insert_rewrite_rules' );
function my_insert_rewrite_rules( $rules ) {
$newrules = array();
$newrules['promocje(/[a-z]+)(/page/([0-9]+))?'] =
'index.php?post_type=promocje'
. '&shop=$matches[1]&paged=$matches[3]';
return $newrules + $rules;
}
</code></pre>
<ul>
<li><code>promocje</code> is the name of the post type.</li>
<li><code>shop</code> is the name of the taxonomy.</li>
</ul>
<p>After that, I was able to switch pages on taxonomy pages, but I had 404 error when paginating the custom post type.</p>
<p>Code of custom post type and taxonomy:</p>
<pre><code> $args = array(
'labels' => $labels,
'hierarchical' => false,
'description' => 'Promocje filtrowane przez sklep',
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'trackbacks', 'custom-fields', 'comments', 'page-attributes' ),
'taxonomies' => array( 'shop'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-audio',
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'query_var' => true,
'can_export' => true,
'capability_type' => 'post',
'register_meta_box_cb' => 'add_promo_metaboxes',
'rewrite' => array( 'slug' => 'promocje/%shop%', 'with_front' => false ),
'has_archive' => 'promocje',
);
function wpa_show_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'promocje' ){
$terms = wp_get_object_terms( $post->ID, 'shop' );
if( $terms ){
return str_replace( '%shop%' , $terms[0]->slug , $post_link);
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );
</code></pre>
<p>And taxonomy:</p>
<pre><code>register_taxonomy(
'shop',
'promocje',
array(
'hierarchical' => true,
'label' => 'Sklep',
'query_var' => true,
'rewrite' => array(
'slug' => 'promocje',
'with_front' => false
)
)
);
</code></pre>
<p>Any help would be appreciated. I've been trying to solve this for more than a week.</p>
| [
{
"answer_id": 241646,
"author": "Zaid Sameer",
"author_id": 28376,
"author_profile": "https://wordpress.stackexchange.com/users/28376",
"pm_score": 1,
"selected": false,
"text": "<p>From the Admin Dashboard, Go to <strong>Permalink Settings</strong> and hit <strong>Save Changes</strong>... | 2016/10/03 | [
"https://wordpress.stackexchange.com/questions/241386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104146/"
] | I made custom post type with one taxonomy. Everything was good except pagination on taxonomy. Firstly, without any changes, I was able to switch pages on main custom post type archive:
```
website.com/custom_post_type_name/page/x
```
But when I wanted to jump to taxonomy and switch pages I got 404 error.
```
website.com/custom_post_type_name/taxonomy_slug/page/x
```
I tried doing regex from answer from StackExchange but it won't work at all.
```
add_filter( 'rewrite_rules_array', 'my_insert_rewrite_rules' );
function my_insert_rewrite_rules( $rules ) {
$newrules = array();
$newrules['promocje(/[a-z]+)(/page/([0-9]+))?'] =
'index.php?post_type=promocje'
. '&shop=$matches[1]&paged=$matches[3]';
return $newrules + $rules;
}
```
* `promocje` is the name of the post type.
* `shop` is the name of the taxonomy.
After that, I was able to switch pages on taxonomy pages, but I had 404 error when paginating the custom post type.
Code of custom post type and taxonomy:
```
$args = array(
'labels' => $labels,
'hierarchical' => false,
'description' => 'Promocje filtrowane przez sklep',
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'trackbacks', 'custom-fields', 'comments', 'page-attributes' ),
'taxonomies' => array( 'shop'),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-audio',
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'query_var' => true,
'can_export' => true,
'capability_type' => 'post',
'register_meta_box_cb' => 'add_promo_metaboxes',
'rewrite' => array( 'slug' => 'promocje/%shop%', 'with_front' => false ),
'has_archive' => 'promocje',
);
function wpa_show_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'promocje' ){
$terms = wp_get_object_terms( $post->ID, 'shop' );
if( $terms ){
return str_replace( '%shop%' , $terms[0]->slug , $post_link);
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );
```
And taxonomy:
```
register_taxonomy(
'shop',
'promocje',
array(
'hierarchical' => true,
'label' => 'Sklep',
'query_var' => true,
'rewrite' => array(
'slug' => 'promocje',
'with_front' => false
)
)
);
```
Any help would be appreciated. I've been trying to solve this for more than a week. | I solved it!
You need to var\_dump wp\_query on 1st page and on 404 page
```
add_action( 'pre_get_posts', 'elo_jlb' );
function elo_jlb($query)
{
if(!is_admin())
{
$query->set('paged', $query->get('page'));
$query->set('HERE_POST_TYPE_NAME', '');
}
}
``` |
241,398 | <p>When using this code below with <code>wp_mail()</code> I always get in the header
wordpress@mydomainname.nl. And in Thunderbird in column Correspondents: Wordpress.
But I need: 'From: "Klantenservice"<' . $emailTo . '>'</p>
<p>In <a href="https://developer.wordpress.org/reference/functions/wp_mail/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/wp_mail/</a> and other pages I can not find a solution for this.</p>
<pre><code> $body = __('Name:', 'Avada')." $user_name \n\n";
$body .= __('Email:', 'Avada')." $user_email \n\n";
$body .= __('Telefoon:', 'Avada')." $telephone \n\n";
$body .= __('Betreft:', 'Avada')." $subject \n\n";
$body .= __('Bericht:', 'Avada')."\n $message";
$headers = 'From: "Klantenservice"<' . $emailTo . '>' . "\r\n";
$emailTo = 'info@mydomainname.nl';
//$mail = wp_mail($user_email, $subject, $body, $headers);
$mail = wp_mail($emailTo, 'Contact verzoek', $body, '');
</code></pre>
<p>How can I get this correct?</p>
<p><strong>Here the solution add this in functions.php</strong>:</p>
<pre><code>add_filter( 'wp_mail_from_name', 'my_mail_from_name' );
function my_mail_from_name( $name )
{
return "My Name";
}
</code></pre>
| [
{
"answer_id": 241434,
"author": "Jeff Mattson",
"author_id": 93714,
"author_profile": "https://wordpress.stackexchange.com/users/93714",
"pm_score": 3,
"selected": true,
"text": "<p>It looks like you are setting the <code>$emailto</code> variable after the place you are using it.</p>\n"... | 2016/10/03 | [
"https://wordpress.stackexchange.com/questions/241398",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78746/"
] | When using this code below with `wp_mail()` I always get in the header
wordpress@mydomainname.nl. And in Thunderbird in column Correspondents: Wordpress.
But I need: 'From: "Klantenservice"<' . $emailTo . '>'
In <https://developer.wordpress.org/reference/functions/wp_mail/> and other pages I can not find a solution for this.
```
$body = __('Name:', 'Avada')." $user_name \n\n";
$body .= __('Email:', 'Avada')." $user_email \n\n";
$body .= __('Telefoon:', 'Avada')." $telephone \n\n";
$body .= __('Betreft:', 'Avada')." $subject \n\n";
$body .= __('Bericht:', 'Avada')."\n $message";
$headers = 'From: "Klantenservice"<' . $emailTo . '>' . "\r\n";
$emailTo = 'info@mydomainname.nl';
//$mail = wp_mail($user_email, $subject, $body, $headers);
$mail = wp_mail($emailTo, 'Contact verzoek', $body, '');
```
How can I get this correct?
**Here the solution add this in functions.php**:
```
add_filter( 'wp_mail_from_name', 'my_mail_from_name' );
function my_mail_from_name( $name )
{
return "My Name";
}
``` | It looks like you are setting the `$emailto` variable after the place you are using it. |
241,424 | <p>Is there a way to add an "incorrect password" error message on password protected pages?</p>
<p>I've looked everywhere and the closest thing I can find is from here: <a href="https://wordpress.stackexchange.com/questions/71284/add-error-message-on-password-protected-page">Add error message on password protected page</a></p>
<p>The problem is that the error persists even when you navigate away from the page because it's based on cookies.</p>
<p>Something that seemed so simple is taking me hours to find a solution =\</p>
| [
{
"answer_id": 241426,
"author": "Nuno Sarmento",
"author_id": 75461,
"author_profile": "https://wordpress.stackexchange.com/users/75461",
"pm_score": -1,
"selected": false,
"text": "<p>I have not tested the code but it seems this is what you are looking for - add the snippet on your fun... | 2016/10/03 | [
"https://wordpress.stackexchange.com/questions/241424",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41083/"
] | Is there a way to add an "incorrect password" error message on password protected pages?
I've looked everywhere and the closest thing I can find is from here: [Add error message on password protected page](https://wordpress.stackexchange.com/questions/71284/add-error-message-on-password-protected-page)
The problem is that the error persists even when you navigate away from the page because it's based on cookies.
Something that seemed so simple is taking me hours to find a solution =\ | Here's a combination of these two great answers ([21697](https://wordpress.stackexchange.com/questions/21697/password-protected-post-or-page-error-message-by-wrong-password) & [71284](https://wordpress.stackexchange.com/questions/71284/add-error-message-on-password-protected-page)) to similar questions.
`wpse241424_check_post_pass()` runs early on the `wp` hook on single password protected pages. If an invalid password is entered, the `INVALID_POST_PASS` constant is set for use later in the form, and the password entry error cookie is removed to prevent the error message from being visible each time.
`wpse241424_post_password_message()` is run right before rendering the password form. It checks for the `INVALID_POST_PASS` constant that it set earlier when an invalid password is encountered, and adds the error message to the form.
```
function wpse241424_check_post_pass() {
if ( ! is_single() || ! post_password_required() ) {
return;
}
if ( isset( $_COOKIE['wp-postpass_' . COOKIEHASH ] ) ) {
define( 'INVALID_POST_PASS', true );
// Tell the browser to remove the cookie so the message doesn't show up every time
setcookie( 'wp-postpass_' . COOKIEHASH, NULL, -1, COOKIEPATH );
}
}
add_action( 'wp', 'wpse241424_check_post_pass' );
/**
* Add a message to the password form if an invalid password has been entered.
*
* @wp-hook the_password_form
* @param string $form
* @return string
*/
function wpse241424_post_password_message( $form ) {
if ( ! defined( 'INVALID_POST_PASS' ) ) {
return $form;
}
// Translate and escape.
$msg = esc_html__( 'Sorry, your password is wrong.', 'your_text_domain' );
// We have a cookie, but it doesn’t match the password.
$msg = "<p class='custom-password-message'>$msg</p>";
return $msg . $form;
}
add_filter( 'the_password_form', 'wpse241424_post_password_message' );
``` |
241,453 | <p>I am planning to make a website where non website members should see a different view of the footer.</p>
<p>Is this possible using css only?</p>
| [
{
"answer_id": 241455,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>If your theme is decently made, there will be a <a href=\"https://developer.wordpress.org/reference/functions/bo... | 2016/10/04 | [
"https://wordpress.stackexchange.com/questions/241453",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101629/"
] | I am planning to make a website where non website members should see a different view of the footer.
Is this possible using css only? | When a user is logged in, WordPress adds the class logged-in to the body tag, so you can target CSS differently for logged in users.
```
body > footer {
background: black;
}
body.logged-in > footer {
background: red;
}
```
for example.
This is only good for cosmetic changes though. Don't try to use it to hide information from non-logged in users as the content is still in the HTML. |
241,476 | <p>I have this function hardcoded into content-single-product.php (WooCommerce) and it works to show 3 random products from <strong>categories ID 64 and 72</strong>:</p>
<pre><code>$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '3',
'orderby' => 'rand',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => array( 64, 72 ),
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
</code></pre>
<p>Now, instead of hardcoding the category ID, I added a custom field to the product <code>MyCustomField</code> and wrote <strong>64,72</strong> in it. Then I tried to modify the above code to be populated dynamically:</p>
<pre><code>$MyCustomField = get_post_meta($post->ID, 'MyCustomField', true);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '3',
'orderby' => 'rand',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => array( $MyCustomField ),
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
</code></pre>
<p>Unfortunately, this doesn't work correctly:</p>
<p><code>'terms' => array( $MyCustomField )</code></p>
<p>because it only displays products from the first category (ID 64), and not from both, as I want.</p>
<p>I'm a newbie programmer so what did I do wrong? Thanks!</p>
| [
{
"answer_id": 241481,
"author": "ClemC",
"author_id": 73239,
"author_profile": "https://wordpress.stackexchange.com/users/73239",
"pm_score": 4,
"selected": true,
"text": "<p>I suspect the problem is coming from <code>$MyCustomField</code> which you enter as such in: </p>\n\n<pre><code... | 2016/10/04 | [
"https://wordpress.stackexchange.com/questions/241476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101024/"
] | I have this function hardcoded into content-single-product.php (WooCommerce) and it works to show 3 random products from **categories ID 64 and 72**:
```
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '3',
'orderby' => 'rand',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => array( 64, 72 ),
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
```
Now, instead of hardcoding the category ID, I added a custom field to the product `MyCustomField` and wrote **64,72** in it. Then I tried to modify the above code to be populated dynamically:
```
$MyCustomField = get_post_meta($post->ID, 'MyCustomField', true);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '3',
'orderby' => 'rand',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => array( $MyCustomField ),
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
```
Unfortunately, this doesn't work correctly:
`'terms' => array( $MyCustomField )`
because it only displays products from the first category (ID 64), and not from both, as I want.
I'm a newbie programmer so what did I do wrong? Thanks! | I suspect the problem is coming from `$MyCustomField` which you enter as such in:
```
'terms' => array( $MyCustomField ),
```
The query consider it as only one value: `'64,72'`, a string.
So try:
```
$MyCustomFieldValues = array_map( 'intval', explode( ',', $MyCustomField ) );
```
This will also ensure your values are integers.
Then:
```
'terms' => $MyCustomFieldValues,
``` |
241,477 | <p>My custom made plugin has "a new version available", also the "view details" link links to a completely unrelated plugin.</p>
<p>The plugin files begins with:</p>
<pre><code><?php
/*
Plugin Name: Simple Contact Form
Plugin URI: http://www.wilcoverhoeven.com
Description: Simple contact form
Version: 1
Author: Wilco Verhoeven
Author URI: http://www.wilcoverhoeven.com
*/
</code></pre>
<p>How can I prevent this?</p>
| [
{
"answer_id": 241478,
"author": "FaCE",
"author_id": 96768,
"author_profile": "https://wordpress.stackexchange.com/users/96768",
"pm_score": 5,
"selected": true,
"text": "<p>I think you've got a naming conflict there -- assuming that your plugin is linking to <a href=\"https://en-gb.wor... | 2016/10/04 | [
"https://wordpress.stackexchange.com/questions/241477",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103917/"
] | My custom made plugin has "a new version available", also the "view details" link links to a completely unrelated plugin.
The plugin files begins with:
```
<?php
/*
Plugin Name: Simple Contact Form
Plugin URI: http://www.wilcoverhoeven.com
Description: Simple contact form
Version: 1
Author: Wilco Verhoeven
Author URI: http://www.wilcoverhoeven.com
*/
```
How can I prevent this? | I think you've got a naming conflict there -- assuming that your plugin is linking to [this](https://en-gb.wordpress.org/plugins/simple-contact-form/) Simple Contact Form -- try changing the name to something like "Wilco's Simple Contact Form".
You'll need to update the plugin folder name and the main plugin file name as well.
**Update**
As [Aniket](https://wordpress.stackexchange.com/users/104130/aniket) points out, you might need to force an update check on your site to get rid of the notice. You can do this by going to `http://yourwebsite.com/wp-admin/update-core.php?force-check=1` |
241,504 | <p>I'm trying to add a PureCSS class to the <code><form></code> tag in the default comments template, but the class isn't being added. Here's what I've done so far:</p>
<pre><code>function pwp_comments_form_pure($output) {
$output = preg_replace('/class="comment-form"/', 'class="comment-form pure-form"', $output);
return $output;
}
add_filter('comments_template', 'pwp_comments_form_pure');
</code></pre>
<p>I know the <code>preg_replace</code> approach works, because I did the same for the default search form and it worked without any problems:</p>
<pre><code>function pwp_search_form_pure($output) {
$output = preg_replace('/class="searchform"/', 'class="searchform pure-form"', $output);
return $output;
}
add_filter('get_search_form', 'pwp_search_form_pure');
</code></pre>
<p>I've triple-checked the class names and hyphenation, and they all match up.</p>
<p>I've also tried adding a priority parameter of 1 and 100 to the <code>comments_template</code> filter, but it didn't make a difference.</p>
<p>Is there an override somewhere in the WordPress defaults that I'm not aware of?</p>
| [
{
"answer_id": 241506,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 3,
"selected": true,
"text": "<p>Any <code>comments_template</code> filter should return <a href=\"https://codex.wordpress.org/Plugin_API/Fi... | 2016/10/04 | [
"https://wordpress.stackexchange.com/questions/241504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19608/"
] | I'm trying to add a PureCSS class to the `<form>` tag in the default comments template, but the class isn't being added. Here's what I've done so far:
```
function pwp_comments_form_pure($output) {
$output = preg_replace('/class="comment-form"/', 'class="comment-form pure-form"', $output);
return $output;
}
add_filter('comments_template', 'pwp_comments_form_pure');
```
I know the `preg_replace` approach works, because I did the same for the default search form and it worked without any problems:
```
function pwp_search_form_pure($output) {
$output = preg_replace('/class="searchform"/', 'class="searchform pure-form"', $output);
return $output;
}
add_filter('get_search_form', 'pwp_search_form_pure');
```
I've triple-checked the class names and hyphenation, and they all match up.
I've also tried adding a priority parameter of 1 and 100 to the `comments_template` filter, but it didn't make a difference.
Is there an override somewhere in the WordPress defaults that I'm not aware of? | Any `comments_template` filter should return [an absolute filepath to the comments template](https://codex.wordpress.org/Plugin_API/Filter_Reference/comments_template) - use `comment_form_defaults` and set the `class_form` argument:
```
add_filter( 'comment_form_defaults', function ( $args ) {
$args['class_form'] = 'my form classes';
return $args;
});
``` |
241,530 | <p>I am working on a plugin that posts an XML request to a vendor's shipping API to get shipping quotes. The XML is stored in a string called $xml. I can post the XML request successfully with curl using these parameters:</p>
<pre><code>$curl = curl_init( $this->settings['api_url'] );
curl_setopt( $curl, CURLOPT_HEADER, 0 );
curl_setopt( $curl, CURLOPT_POST, 1 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 45 );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $xml );
$result = curl_exec( $curl );
curl_close( $curl );
</code></pre>
<p>My question is, how can I do the same thing with WordPress HTTP API? I want to maximize compatibility for those that may not have curl on their servers.</p>
<p>Here is the HTTP API attempt I have made:</p>
<pre><code>$result = wp_remote_post(
$this->settings['api_url'],
array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.1',
'headers' => array(
'Content-Type' => 'text/xml'
),
'body' => array(
'postdata' => $xml
),
'sslverify' => 'false'
)
);
</code></pre>
<p>I have tried changing the body to just:</p>
<pre><code>'body' => array( $xml ),
</code></pre>
<p>I have tried converting the $xml to a php associative array with simple xml and json.</p>
<p>With all of my attempts, I keep getting back an error in my vendor's response: "Content is not allowed in prolog." It would seem that the XML is either not being posted properly or HTTP API is maybe including a Byte Order Mark (BOM).</p>
<p>Hoping someone can help. Thanks.</p>
| [
{
"answer_id": 241538,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should have <code>body</code> like this:</p>\n\n<pre><code>'body' => array( 'username' => '... | 2016/10/04 | [
"https://wordpress.stackexchange.com/questions/241530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104148/"
] | I am working on a plugin that posts an XML request to a vendor's shipping API to get shipping quotes. The XML is stored in a string called $xml. I can post the XML request successfully with curl using these parameters:
```
$curl = curl_init( $this->settings['api_url'] );
curl_setopt( $curl, CURLOPT_HEADER, 0 );
curl_setopt( $curl, CURLOPT_POST, 1 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 45 );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $xml );
$result = curl_exec( $curl );
curl_close( $curl );
```
My question is, how can I do the same thing with WordPress HTTP API? I want to maximize compatibility for those that may not have curl on their servers.
Here is the HTTP API attempt I have made:
```
$result = wp_remote_post(
$this->settings['api_url'],
array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.1',
'headers' => array(
'Content-Type' => 'text/xml'
),
'body' => array(
'postdata' => $xml
),
'sslverify' => 'false'
)
);
```
I have tried changing the body to just:
```
'body' => array( $xml ),
```
I have tried converting the $xml to a php associative array with simple xml and json.
With all of my attempts, I keep getting back an error in my vendor's response: "Content is not allowed in prolog." It would seem that the XML is either not being posted properly or HTTP API is maybe including a Byte Order Mark (BOM).
Hoping someone can help. Thanks. | I tried some more trial and error and managed to get it to work by simply putting $xml as the body without specifying it as an array. The function reference says, "Post data should be sent in the body as an array," so I'm not sure why it worked.
Here is the working code in case it helps someone else:
```
// Sends the xml request to the API
$result = wp_remote_post(
$this->settings['api_url'],
array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.1',
'headers' => array(
'Content-Type' => 'text/xml'
),
'body' => $xml,
'sslverify' => 'false'
)
);
``` |
241,542 | <p>Learning PHP and a little stuck on a fairly straight forward issue.
I am trying to edit my WooCommerce invoice</p>
<p>This code <code><?php echo $sign.number_format($order->get_subtotal(),2); ?></code> Returns $50.98</p>
<p>This code <code>$first_number = $order->get_subtotal();</code> Returns a variable of 51, it rounds up as the <code>,2</code> is missing.
How do I add <code>(),2;</code> to the above code so it returns that variable just as a number with decimals so i can make calculations with it.</p>
<p>If I try this<code>$first_number = ($order->get_subtotal(),2);</code> It breaks as I obviously don't know the correct syntax.</p>
<p>Thanks for any pointers</p>
| [
{
"answer_id": 241552,
"author": "Jason",
"author_id": 104148,
"author_profile": "https://wordpress.stackexchange.com/users/104148",
"pm_score": 2,
"selected": true,
"text": "<p>Try</p>\n\n<pre><code>$first_number = number_format( $order->get_subtotal(), 2 );\n</code></pre>\n\n<p>numb... | 2016/10/04 | [
"https://wordpress.stackexchange.com/questions/241542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104225/"
] | Learning PHP and a little stuck on a fairly straight forward issue.
I am trying to edit my WooCommerce invoice
This code `<?php echo $sign.number_format($order->get_subtotal(),2); ?>` Returns $50.98
This code `$first_number = $order->get_subtotal();` Returns a variable of 51, it rounds up as the `,2` is missing.
How do I add `(),2;` to the above code so it returns that variable just as a number with decimals so i can make calculations with it.
If I try this`$first_number = ($order->get_subtotal(),2);` It breaks as I obviously don't know the correct syntax.
Thanks for any pointers | Try
```
$first_number = number_format( $order->get_subtotal(), 2 );
```
number\_format() is the php function that is setting the decimals in your first bit of code above.
See <http://php.net/manual/en/function.number-format.php> |
241,543 | <p>I would like to know how to bulk delete posts from a specific category using the <a href="http://wp-cli.org/" rel="nofollow">WP-CLI</a>, any tip?</p>
| [
{
"answer_id": 241558,
"author": "ClemC",
"author_id": 73239,
"author_profile": "https://wordpress.stackexchange.com/users/73239",
"pm_score": 5,
"selected": true,
"text": "<p>This should delete <strong>all</strong> posts in your category:</p>\n\n<pre><code>wp post delete $(wp post list ... | 2016/10/04 | [
"https://wordpress.stackexchange.com/questions/241543",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104229/"
] | I would like to know how to bulk delete posts from a specific category using the [WP-CLI](http://wp-cli.org/), any tip? | This should delete **all** posts in your category:
```
wp post delete $(wp post list --cat=your_category_ID --format=ids)
```
**Or** directly:
```
wp db query [<your_sql_query>]
```
For more info:
```
wp post delete --help
wp post list --help
wp db query --help
``` |
241,570 | <p>I have created a Custom Post Type <code>Projects</code>. Below is my code. Everything is working fine, but when I click on a Category of this Post Type it redirects me to the Homepage. I have tried all possible methods, but I am still unable to find the issue.</p>
<pre><code> add_action( 'init', 'create_posttype' );
function create_posttype() {
$args = array(
'labels' => array('name'=>__('Projects'), 'singular_name'=>__('Projects') ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' =>'projects','with_front'=>true ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
'taxonomies' => array( 'project_category','post_tag'),
);
register_post_type( 'Projects', $args );
}
</code></pre>
<p>Here is my code for registering the taxonomy, </p>
<pre><code>add_action( 'init', 'create_project_taxonomies', 0 );
function create_project_taxonomies() {
$labels = array(
'name' => _x( 'Project category', 'taxonomy general name', 'twentyfifteen' ),
'singular_name' => _x( 'Project catgeory', 'taxonomy singular name', 'twentyfifteen' ),
'search_items' => __( 'Search category', 'twentyfifteen' ),
'popular_items' => __( 'Popular Writers', 'twentyfifteen' ),
'all_items' => __( 'All Category', 'twentyfifteen' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit category', 'textdomain' ),
'update_item' => __( 'Update catrgory', 'textdomain' ),
'add_new_item' => __( 'Add New category', 'textdomain' ),
'new_item_name' => __( 'New category Name', 'textdomain' ),
'separate_items_with_commas' => __( 'Separate writers with commas', 'textdomain' ),
'add_or_remove_items' => __( 'Add or remove category', 'textdomain' ),
'choose_from_most_used' => __( 'Choose from the most used writers', 'textdomain' ),
'not_found' => __( 'No category found.', 'textdomain' ),
'menu_name' => __( 'Project Category', 'textdomain' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'public' => false,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'project_category'),
);
register_taxonomy( 'project_category', 'Projects', $args );
}
</code></pre>
<p>Please guys, help me.</p>
| [
{
"answer_id": 241558,
"author": "ClemC",
"author_id": 73239,
"author_profile": "https://wordpress.stackexchange.com/users/73239",
"pm_score": 5,
"selected": true,
"text": "<p>This should delete <strong>all</strong> posts in your category:</p>\n\n<pre><code>wp post delete $(wp post list ... | 2016/10/05 | [
"https://wordpress.stackexchange.com/questions/241570",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104241/"
] | I have created a Custom Post Type `Projects`. Below is my code. Everything is working fine, but when I click on a Category of this Post Type it redirects me to the Homepage. I have tried all possible methods, but I am still unable to find the issue.
```
add_action( 'init', 'create_posttype' );
function create_posttype() {
$args = array(
'labels' => array('name'=>__('Projects'), 'singular_name'=>__('Projects') ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' =>'projects','with_front'=>true ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'),
'taxonomies' => array( 'project_category','post_tag'),
);
register_post_type( 'Projects', $args );
}
```
Here is my code for registering the taxonomy,
```
add_action( 'init', 'create_project_taxonomies', 0 );
function create_project_taxonomies() {
$labels = array(
'name' => _x( 'Project category', 'taxonomy general name', 'twentyfifteen' ),
'singular_name' => _x( 'Project catgeory', 'taxonomy singular name', 'twentyfifteen' ),
'search_items' => __( 'Search category', 'twentyfifteen' ),
'popular_items' => __( 'Popular Writers', 'twentyfifteen' ),
'all_items' => __( 'All Category', 'twentyfifteen' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit category', 'textdomain' ),
'update_item' => __( 'Update catrgory', 'textdomain' ),
'add_new_item' => __( 'Add New category', 'textdomain' ),
'new_item_name' => __( 'New category Name', 'textdomain' ),
'separate_items_with_commas' => __( 'Separate writers with commas', 'textdomain' ),
'add_or_remove_items' => __( 'Add or remove category', 'textdomain' ),
'choose_from_most_used' => __( 'Choose from the most used writers', 'textdomain' ),
'not_found' => __( 'No category found.', 'textdomain' ),
'menu_name' => __( 'Project Category', 'textdomain' ),
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'public' => false,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'project_category'),
);
register_taxonomy( 'project_category', 'Projects', $args );
}
```
Please guys, help me. | This should delete **all** posts in your category:
```
wp post delete $(wp post list --cat=your_category_ID --format=ids)
```
**Or** directly:
```
wp db query [<your_sql_query>]
```
For more info:
```
wp post delete --help
wp post list --help
wp db query --help
``` |
241,601 | <p>I want to query posts where meta value is empty. for example, I want to get these three posts, with no meta values:
<a href="https://i.stack.imgur.com/9U69t.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/9U69t.jpg" alt="enter image description here"></a></p>
<p>Already tried:</p>
<pre><code>$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_wp_attachment_image_alt',
'value' => '',
'compare' => 'LIKE'
)
)
);
$attachments = new WP_Query($args);
</code></pre>
<p>and:</p>
<pre><code>$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_wp_attachment_image_alt',
'value' => null,
'compare' => 'LIKE'
)
)
);
</code></pre>
<p>But it doesn't work..</p>
<p>Any idea how to solve this?</p>
<p>Thank you</p>
| [
{
"answer_id": 241605,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I think you forgot about the <em>inherit</em> post status. The default one in <code>WP_Query</code> is <em>pub... | 2016/10/05 | [
"https://wordpress.stackexchange.com/questions/241601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70845/"
] | I want to query posts where meta value is empty. for example, I want to get these three posts, with no meta values:
[](https://i.stack.imgur.com/9U69t.jpg)
Already tried:
```
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_wp_attachment_image_alt',
'value' => '',
'compare' => 'LIKE'
)
)
);
$attachments = new WP_Query($args);
```
and:
```
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged,
'meta_query' => array(
array(
'key' => '_wp_attachment_image_alt',
'value' => null,
'compare' => 'LIKE'
)
)
);
```
But it doesn't work..
Any idea how to solve this?
Thank you | I think you forgot about the *inherit* post status. The default one in `WP_Query` is *publish*.
You should also use `=` instead of `LIKE`, to avoid using `LIKE '%%'` in the SQL query.
So try to add this:
```
'post_status' => 'inherit'
```
and
```
'compare' => '='
```
into your query arguments, to match the empty `_wp_attachment_image_alt` string values. |
241,612 | <p>I am attaching an image to a post with the media import command.</p>
<p>I know I can get the image id using the --porcelain option, but how can I get the image url from this id?</p>
<p>Or is there a way to display the featured image's url of a post (apparently the list command does allow this)?</p>
| [
{
"answer_id": 241621,
"author": "Javier Villanueva",
"author_id": 3893,
"author_profile": "https://wordpress.stackexchange.com/users/3893",
"pm_score": 2,
"selected": false,
"text": "<p>Media attachments are tricky to get through the cli because they are stored as a serialised array in ... | 2016/10/05 | [
"https://wordpress.stackexchange.com/questions/241612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44388/"
] | I am attaching an image to a post with the media import command.
I know I can get the image id using the --porcelain option, but how can I get the image url from this id?
Or is there a way to display the featured image's url of a post (apparently the list command does allow this)? | Assuming the attachment ID were in a variable of `$attachment_id` you could use the following command:
```
# get attachment URL
wp db query "SELECT guid FROM $(wp db tables *_posts) WHERE ID=\"$attachment_id\"" | head -n 2 | tail -1
```
I use the `$(wp db tables *_posts)` bit just in case the `wp_` table prefix is non-default. |
241,634 | <p>I tried to include shortcodes with a parameter in raw html output, like shown below:</p>
<pre><code><a href="https://example.com/folder/edit.php?action=someaction&id=[foocode parameter='value']&edittoken=[foocode parameter='othervalue']">linktext</a>
</code></pre>
<p>This crashes the PHP function <code>do_shortcode()</code>.</p>
<p>Is stuff like this really not possible with shortcodes?</p>
<p>The method description itself contains a warning:</p>
<blockquote>
<p>Users with <code>unfiltered_html</code> * capability may get unexpected output if
angle braces are nested in tags.</p>
</blockquote>
<p>However, PHP crashing is not the kind of unexpected output that should be able to happen.</p>
<p>PS: The function that is being called is</p>
<pre><code>function echocode( $atts ){
return "Hello World";
}
</code></pre>
<p>and added as</p>
<pre><code>add_shortcode("foocode", "echocode");
</code></pre>
<p>The function never runs. (No starting echocode is being printed)</p>
| [
{
"answer_id": 241637,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": false,
"text": "<p>shortcodes are not allowed in html attributes, shortcodes are not programing language, they are place hol... | 2016/10/05 | [
"https://wordpress.stackexchange.com/questions/241634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104289/"
] | I tried to include shortcodes with a parameter in raw html output, like shown below:
```
<a href="https://example.com/folder/edit.php?action=someaction&id=[foocode parameter='value']&edittoken=[foocode parameter='othervalue']">linktext</a>
```
This crashes the PHP function `do_shortcode()`.
Is stuff like this really not possible with shortcodes?
The method description itself contains a warning:
>
> Users with `unfiltered_html` \* capability may get unexpected output if
> angle braces are nested in tags.
>
>
>
However, PHP crashing is not the kind of unexpected output that should be able to happen.
PS: The function that is being called is
```
function echocode( $atts ){
return "Hello World";
}
```
and added as
```
add_shortcode("foocode", "echocode");
```
The function never runs. (No starting echocode is being printed) | shortcodes are not allowed in html attributes, shortcodes are not programing language, they are place holders to proper html content. |
241,677 | <p>I am developing a theme and am getting the following error "<code>Warning: trim() expects parameter 1 to be string, array given in C:\wamp\www\themes\wp-includes\query.php on line 1609</code>". I have tried everything I could think of and have Googled for longer than I'd like to admit trying to get it sorted out.</p>
<p><strong>The Issue</strong></p>
<p>I have created a form that allows users to submit a recipe and submit it to a custom post type using <code>wp_insert_post</code> on the front end of the site. The problem is with the repeating fields that I have set up. They are working fine in the Dashboard but had to obviously be modified. They submit to an array and are submitting correctly to my post type but keep throwing the error above.</p>
<p>I would be grateful if anyone could take a look and let me know what I could do to clean it up.</p>
<p><strong>Not sure if it matters but here is how I am duplicating the fields</strong></p>
<pre><code><script type="text/javascript">
jQuery(document).ready(function( $ ){
$( '#add-row' ).on('click', function() {
var row = $( '.empty-row.screen-reader-text' ).clone(true);
row.removeClass( 'empty-row screen-reader-text' );
row.insertBefore( '#repeatable-ingredient-set tbody>tr:last' );
return false;
});
$( '.remove-button' ).on('click', function() {
$(this).parents('tr').remove();
return false;
});
});
</script>
</code></pre>
<p><strong>Here is the section that's causing the issue</strong></p>
<pre><code><!-- Add the repeating ingredient fields -->
<tr>
<td><input type="text" class="widefat" name="name[]" /></td>
<td><input type="text" class="widefat" name="amount[]" /></td>
<td>
<select name="unit[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><a class="button remove-button" href="#">Remove</a></td>
</tr>
<!-- Hidden field group used when add button is pressed (jQuery) -->
<tr class="empty-row screen-reader-text">
<td><input type="text" class="widefat" name="name[]" /></td>
<td><input type="text" class="widefat" name="amount[]" /></td>
<td>
<select name="unit[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><a class="button remove-button" href="#">Remove</a></td>
</tr>
</code></pre>
<p><strong>Here is where it gets submitted</strong></p>
<pre><code>//* Create a blank array for the newly added ingredients
$ingredients = array();
//* Get the names
$names = $_POST['name'];
//* Get the measurements
$amounts = $_POST['amount'];
//* Get the units ($options)
$units = $_POST['unit'];
//* Find the number of ingredients by counting the names
$count = count( $names );
//* As long as there are ingredients then add them to the array
for ( $i = 0; $i < $count; $i++ ) {
if ( $names[$i] != '' ) :
$ingredients[$i]['name'] = stripslashes( strip_tags( $names[$i] ) );
$ingredients[$i]['amount'] = stripslashes( strip_tags( $amounts[$i] ) );
if ( in_array( $units[$i], $options ) )
$ingredients[$i]['unit'] = $units[$i];
else
$ingredients[$i]['unit'] = '';
endif;
}
//* If all requirements are met then proceed to build the new recipe
if ( isset($_POST['recipe_title']) && isset($_POST['recipe_content']) && ( isset($hasError) ==false )) {
global $wpdb;
//* Add all the information collected from the form
$new_post = array(
'post_title' => $recipe_title, //* Add the title
'post_content' => $recipe_content, //* Add the instructions
'meta_input' => array(
'cook_time_hour' => $cook_time_hour, //* Add the cook time hours
'cook_time_minute' => $cook_time_minute, //* Add the cook time minutes
'servings' => $servings, //* Add the servings
'calories' => $calories, //* Add the calories
'measurement_units' => $ingredients, //* Add the ingredients
),
'tax_input' => array(
'recipe_types' => array( $recipe_cat[0] ), //* Add the recipe type
),
'post_status' => 'pending', //* Set the new recipe as pending to be reviewed
'post_type' => 'recipes' //* Set it to the recipes post type
);
//* Get the post ID of the newly created recipe
$post_id = wp_insert_post($new_post);
</code></pre>
<p>I know that the name attributes, <code>name[]</code>, <code>amount[]</code>, and <code>unit[]</code>, are the problem but not sure if there is a way to fix this so that it plays nice with WordPress without heavy modifications.</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 241649,
"author": "Jonny Perl",
"author_id": 40765,
"author_profile": "https://wordpress.stackexchange.com/users/40765",
"pm_score": 0,
"selected": false,
"text": "<p>It would appear that you can do this quite easily via <a href=\"https://en-gb.wordpress.org/plugins/wp-lat... | 2016/10/05 | [
"https://wordpress.stackexchange.com/questions/241677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104314/"
] | I am developing a theme and am getting the following error "`Warning: trim() expects parameter 1 to be string, array given in C:\wamp\www\themes\wp-includes\query.php on line 1609`". I have tried everything I could think of and have Googled for longer than I'd like to admit trying to get it sorted out.
**The Issue**
I have created a form that allows users to submit a recipe and submit it to a custom post type using `wp_insert_post` on the front end of the site. The problem is with the repeating fields that I have set up. They are working fine in the Dashboard but had to obviously be modified. They submit to an array and are submitting correctly to my post type but keep throwing the error above.
I would be grateful if anyone could take a look and let me know what I could do to clean it up.
**Not sure if it matters but here is how I am duplicating the fields**
```
<script type="text/javascript">
jQuery(document).ready(function( $ ){
$( '#add-row' ).on('click', function() {
var row = $( '.empty-row.screen-reader-text' ).clone(true);
row.removeClass( 'empty-row screen-reader-text' );
row.insertBefore( '#repeatable-ingredient-set tbody>tr:last' );
return false;
});
$( '.remove-button' ).on('click', function() {
$(this).parents('tr').remove();
return false;
});
});
</script>
```
**Here is the section that's causing the issue**
```
<!-- Add the repeating ingredient fields -->
<tr>
<td><input type="text" class="widefat" name="name[]" /></td>
<td><input type="text" class="widefat" name="amount[]" /></td>
<td>
<select name="unit[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><a class="button remove-button" href="#">Remove</a></td>
</tr>
<!-- Hidden field group used when add button is pressed (jQuery) -->
<tr class="empty-row screen-reader-text">
<td><input type="text" class="widefat" name="name[]" /></td>
<td><input type="text" class="widefat" name="amount[]" /></td>
<td>
<select name="unit[]">
<?php foreach ( $options as $label => $value ) : ?>
<option value="<?php echo $value; ?>"><?php echo $label; ?></option>
<?php endforeach; ?>
</select>
</td>
<td><a class="button remove-button" href="#">Remove</a></td>
</tr>
```
**Here is where it gets submitted**
```
//* Create a blank array for the newly added ingredients
$ingredients = array();
//* Get the names
$names = $_POST['name'];
//* Get the measurements
$amounts = $_POST['amount'];
//* Get the units ($options)
$units = $_POST['unit'];
//* Find the number of ingredients by counting the names
$count = count( $names );
//* As long as there are ingredients then add them to the array
for ( $i = 0; $i < $count; $i++ ) {
if ( $names[$i] != '' ) :
$ingredients[$i]['name'] = stripslashes( strip_tags( $names[$i] ) );
$ingredients[$i]['amount'] = stripslashes( strip_tags( $amounts[$i] ) );
if ( in_array( $units[$i], $options ) )
$ingredients[$i]['unit'] = $units[$i];
else
$ingredients[$i]['unit'] = '';
endif;
}
//* If all requirements are met then proceed to build the new recipe
if ( isset($_POST['recipe_title']) && isset($_POST['recipe_content']) && ( isset($hasError) ==false )) {
global $wpdb;
//* Add all the information collected from the form
$new_post = array(
'post_title' => $recipe_title, //* Add the title
'post_content' => $recipe_content, //* Add the instructions
'meta_input' => array(
'cook_time_hour' => $cook_time_hour, //* Add the cook time hours
'cook_time_minute' => $cook_time_minute, //* Add the cook time minutes
'servings' => $servings, //* Add the servings
'calories' => $calories, //* Add the calories
'measurement_units' => $ingredients, //* Add the ingredients
),
'tax_input' => array(
'recipe_types' => array( $recipe_cat[0] ), //* Add the recipe type
),
'post_status' => 'pending', //* Set the new recipe as pending to be reviewed
'post_type' => 'recipes' //* Set it to the recipes post type
);
//* Get the post ID of the newly created recipe
$post_id = wp_insert_post($new_post);
```
I know that the name attributes, `name[]`, `amount[]`, and `unit[]`, are the problem but not sure if there is a way to fix this so that it plays nice with WordPress without heavy modifications.
Thanks in advance! | The Wordpress-produced plugin Jetpack has LaTeX support. See this [link](https://jetpack.com/support/beautiful-math-with-latex/). However, in my development, it didn't seem to work, so I've been using a plugin called MathJax-LaTeX. Yesterday, I discovered a plugin called WP QuickLaTeX, but I haven't been able to test it yet. Hope this helps. |
241,698 | <p>I have a custom post type called <code>laptop</code> with custom fields such as <code>CPU</code>, <code>OS</code>, <code>RAM</code> etc. creatied using the <code>Advanced Custom Fields</code> plugin.</p>
<p>I'm displaying a table of laptops, where the table header is a row of custom fields, and each following row is a laptop name and it's custom field values in each of the corresponding column cells.</p>
<p>I want to be able to sort the table by clicking on the table <code>TH</code> cell containing the custom field name.</p>
<p>I've been pointed to <a href="https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/" rel="nofollow">meta query clauses</a> by ACF support, but I'm out of my depth with those.</p>
<p>I'd really appreciate some help in generating URLs to wrap around the the custom field name in each <code>TH</code> element.</p>
| [
{
"answer_id": 242184,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Simple with this reference:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow n... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241698",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
] | I have a custom post type called `laptop` with custom fields such as `CPU`, `OS`, `RAM` etc. creatied using the `Advanced Custom Fields` plugin.
I'm displaying a table of laptops, where the table header is a row of custom fields, and each following row is a laptop name and it's custom field values in each of the corresponding column cells.
I want to be able to sort the table by clicking on the table `TH` cell containing the custom field name.
I've been pointed to [meta query clauses](https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/) by ACF support, but I'm out of my depth with those.
I'd really appreciate some help in generating URLs to wrap around the the custom field name in each `TH` element. | To follow up on @rock3t's comment, do you really have to query the backend whenever a user clicks on a column header?
Have you looking into using the jQuery [tablesorter](https://plugins.jquery.com/tablesorter/)? It allows an end-user to sort an HTML table by doing DOM manipulations.
I've never used it in a WP project, but I have used it extensively in other projects I've built and it works great. It's **very** configurable, so I'm sure it will satisfy your needs.
tablesorter is **not** one of the jQuery plugins included with WP Core. So you'll have to download it (from the above link), include it in your plugin/theme somewhere and enqueue it. Then, enqueue a simple JS file that would like something like:
```
(function ($) {
$(document).ready (function () {
$('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ;
}) ;
})(jQuery) ;
```
You can read more about how to use tablesort in their [docs](https://mottie.github.io/tablesorter/docs/index.html), including various other parms to the `tablesorter()` method. |
241,707 | <p>Is any way to don`t display shrort description in a single entry page?</p>
<p>It is necessary to be able to write any text, then paste the tag "more". This content should be displayed only on the list of records page. But it should not be displayed on the single entry page.</p>
| [
{
"answer_id": 242184,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Simple with this reference:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow n... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83974/"
] | Is any way to don`t display shrort description in a single entry page?
It is necessary to be able to write any text, then paste the tag "more". This content should be displayed only on the list of records page. But it should not be displayed on the single entry page. | To follow up on @rock3t's comment, do you really have to query the backend whenever a user clicks on a column header?
Have you looking into using the jQuery [tablesorter](https://plugins.jquery.com/tablesorter/)? It allows an end-user to sort an HTML table by doing DOM manipulations.
I've never used it in a WP project, but I have used it extensively in other projects I've built and it works great. It's **very** configurable, so I'm sure it will satisfy your needs.
tablesorter is **not** one of the jQuery plugins included with WP Core. So you'll have to download it (from the above link), include it in your plugin/theme somewhere and enqueue it. Then, enqueue a simple JS file that would like something like:
```
(function ($) {
$(document).ready (function () {
$('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ;
}) ;
})(jQuery) ;
```
You can read more about how to use tablesort in their [docs](https://mottie.github.io/tablesorter/docs/index.html), including various other parms to the `tablesorter()` method. |
241,711 | <p>I tried to change the caption "related posts" of <a href="https://wordpress.org/plugins/related-posts-thumbnails/" rel="nofollow">https://wordpress.org/plugins/related-posts-thumbnails/</a> to something else.</p>
<p>I tried to change the value of <code>$top_text</code> to <code><h3>THIS IS NEW CAPTION:</h3></code> but it does not work. Why ? </p>
<pre><code> <?php
/**
* Plugin Name: Related Posts Thumbnails
* Plugin URI: http://wordpress.shaldybina.com/plugins/related-posts-thumbnails/
* Description: Showing related posts thumbnails under the post.
* Version: 1.5.2
* Author: Maria Shaldybina
* Author URI: http://shaldybina.com/
*/
/*
Copyright 2010 Maria I Shaldybina
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
class RelatedPostsThumbnails {
/* Default values. PHP 4 compatible */
var $single_only = '1';
var $auto = '1';
var $top_text = '<h3>NEW CAPTION:</h3>';
var $number = 3;
var $relation = 'categories';
var $poststhname = 'thumbnail';
var $background = '#FFFFFF';
var $hoverbackground = '#EEEEEF';
var $border_color = '#DDDDDD';
var $font_color = '#333333';
var $font_family = 'Arial';
var $font_size = '12';
var $text_length = '100';
var $excerpt_length = '0';
var $custom_field = '';
var $custom_height = '100';
var $custom_width = '100';
var $text_block_height = '75';
var $thsource = 'post-thumbnails';
var $categories_all = '1';
var $devmode = '0';
var $output_style = 'div';
var $post_types = array( 'post' );
var $custom_taxonomies = array();
protected $wp_kses_rp_args = array(
'h1' => array(),
'h2' => array(),
'h3' => array(),
'h4' => array(),
'h5' => array(),
'h6' => array(),
'strong' => array(),
);
function __construct() {
// initialization
load_plugin_textdomain( 'related-posts-thumbnails', false, basename( dirname( __FILE__ ) ) . '/locale' );
$this->default_image = esc_url( plugins_url( 'img/default.png', __FILE__ ) );
// Compatibility for old default image path.
if ( $this->is_old_default_img() )
update_option( 'relpoststh_default_image', $this->default_image );
if ( get_option( 'relpoststh_auto', $this->auto ) ) {
add_filter( 'the_content', array( $this, 'auto_show' ) );
}
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
add_shortcode( 'related-posts-thumbnails' , array( $this, 'get_html' ) );
$this->wp_version = get_bloginfo( 'version' );
}
</code></pre>
| [
{
"answer_id": 242184,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Simple with this reference:\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow n... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241711",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4078/"
] | I tried to change the caption "related posts" of <https://wordpress.org/plugins/related-posts-thumbnails/> to something else.
I tried to change the value of `$top_text` to `<h3>THIS IS NEW CAPTION:</h3>` but it does not work. Why ?
```
<?php
/**
* Plugin Name: Related Posts Thumbnails
* Plugin URI: http://wordpress.shaldybina.com/plugins/related-posts-thumbnails/
* Description: Showing related posts thumbnails under the post.
* Version: 1.5.2
* Author: Maria Shaldybina
* Author URI: http://shaldybina.com/
*/
/*
Copyright 2010 Maria I Shaldybina
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
class RelatedPostsThumbnails {
/* Default values. PHP 4 compatible */
var $single_only = '1';
var $auto = '1';
var $top_text = '<h3>NEW CAPTION:</h3>';
var $number = 3;
var $relation = 'categories';
var $poststhname = 'thumbnail';
var $background = '#FFFFFF';
var $hoverbackground = '#EEEEEF';
var $border_color = '#DDDDDD';
var $font_color = '#333333';
var $font_family = 'Arial';
var $font_size = '12';
var $text_length = '100';
var $excerpt_length = '0';
var $custom_field = '';
var $custom_height = '100';
var $custom_width = '100';
var $text_block_height = '75';
var $thsource = 'post-thumbnails';
var $categories_all = '1';
var $devmode = '0';
var $output_style = 'div';
var $post_types = array( 'post' );
var $custom_taxonomies = array();
protected $wp_kses_rp_args = array(
'h1' => array(),
'h2' => array(),
'h3' => array(),
'h4' => array(),
'h5' => array(),
'h6' => array(),
'strong' => array(),
);
function __construct() {
// initialization
load_plugin_textdomain( 'related-posts-thumbnails', false, basename( dirname( __FILE__ ) ) . '/locale' );
$this->default_image = esc_url( plugins_url( 'img/default.png', __FILE__ ) );
// Compatibility for old default image path.
if ( $this->is_old_default_img() )
update_option( 'relpoststh_default_image', $this->default_image );
if ( get_option( 'relpoststh_auto', $this->auto ) ) {
add_filter( 'the_content', array( $this, 'auto_show' ) );
}
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
add_shortcode( 'related-posts-thumbnails' , array( $this, 'get_html' ) );
$this->wp_version = get_bloginfo( 'version' );
}
``` | To follow up on @rock3t's comment, do you really have to query the backend whenever a user clicks on a column header?
Have you looking into using the jQuery [tablesorter](https://plugins.jquery.com/tablesorter/)? It allows an end-user to sort an HTML table by doing DOM manipulations.
I've never used it in a WP project, but I have used it extensively in other projects I've built and it works great. It's **very** configurable, so I'm sure it will satisfy your needs.
tablesorter is **not** one of the jQuery plugins included with WP Core. So you'll have to download it (from the above link), include it in your plugin/theme somewhere and enqueue it. Then, enqueue a simple JS file that would like something like:
```
(function ($) {
$(document).ready (function () {
$('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ;
}) ;
})(jQuery) ;
```
You can read more about how to use tablesort in their [docs](https://mottie.github.io/tablesorter/docs/index.html), including various other parms to the `tablesorter()` method. |
241,741 | <p>For example, if I have a custom post type that are '<strong>Case Studies</strong>',</p>
<p>Firstly I need to be able to query the post types for a <strong>single</strong> specific case study, but then lets say there are a few <strong>variations</strong> of that single case study;</p>
<p>'Wales', 'England', 'Scotland'... . The correct one needs to be picked out depending on the category taxonomy for that post (of the same name).</p>
<p>When the specific case study and its variation has been found, let's say:</p>
<p>Case Study: Highest Mountain</p>
<p>Category (taxonomy) of custom post: Scotland</p>
<p>I need to then put this information into a html template, for example the output would be (data pulled from the custom post):</p>
<pre><code><h3>Highest Mountain</h3>
<p>Here would be the content specific to Scotland...</p>
</code></pre>
<p>So when the shortcode is entered into the_content textarea by the user, all they have to input is e.g.</p>
<pre><code>[casestudy study_type="mountain"]
</code></pre>
<p>When registering a new post for 'Case Studies', the category taxonomy (variation) would be selected. So if the Category chosen for the post was 'Scotland', and the user had this country selected in their user profile - it would pull the variation of that case study (e.g. mountain) specific to Scotland.</p>
<p>All help much appreciated, I haven't written a custom shortcode before - so the more explanation the better - thanks!</p>
| [
{
"answer_id": 241744,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>You have to create your own shortcodes to do this. Use <code>add_shortcode()</code>, create a fonction that ca... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98971/"
] | For example, if I have a custom post type that are '**Case Studies**',
Firstly I need to be able to query the post types for a **single** specific case study, but then lets say there are a few **variations** of that single case study;
'Wales', 'England', 'Scotland'... . The correct one needs to be picked out depending on the category taxonomy for that post (of the same name).
When the specific case study and its variation has been found, let's say:
Case Study: Highest Mountain
Category (taxonomy) of custom post: Scotland
I need to then put this information into a html template, for example the output would be (data pulled from the custom post):
```
<h3>Highest Mountain</h3>
<p>Here would be the content specific to Scotland...</p>
```
So when the shortcode is entered into the\_content textarea by the user, all they have to input is e.g.
```
[casestudy study_type="mountain"]
```
When registering a new post for 'Case Studies', the category taxonomy (variation) would be selected. So if the Category chosen for the post was 'Scotland', and the user had this country selected in their user profile - it would pull the variation of that case study (e.g. mountain) specific to Scotland.
All help much appreciated, I haven't written a custom shortcode before - so the more explanation the better - thanks! | From your supplied info, it's not all very clear to me. But as far as I've understood your problem, here's my approach.
Assuming we have the following shortcode that the user has put inside a **normal** post's content and that this shortcode will pull information from your custom post type `case_studies`:
```
[casestudy study_type="mountain"]
```
So firstly, your shortcode handler:
```
add_shortcode( 'casestudy', 'my_shortcode' );
function my_shortcode( $atts ) {
$a = shortcode_atts( array(
'study_type' => 'mountain',
), $atts );
$content = my_template( $a );
return $content;
}
```
Pay close attention to the [`shortocode_atts()`](https://codex.wordpress.org/Function_Reference/shortcode_atts) function. It's meant to filter the **accepted** parameters that your template function's query below will be able to handle.
Then, your template:
```
function my_template( $a ) {
/**
* I believe we should be in the loop already when this function is being called.
* So to get the category slug of the current post in which the user has put the shortcode, you can try this.
*/
$category_terms = get_the_category();
$args = array(
'post_type' => 'case_studies',
'name' => $a['study_type'],
'category_name' => $category_terms[0]->slug,
'posts_per_page' => 1,
);
$query = new WP_Query( $args );
ob_start();
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
the_post();
echo '<h3>' . get_the_title() . '</h3>';
echo '<p>' . get_the_content() . '</p>';
}
reset_postdata();
}
return ob_get_clean();
}
``` |
241,743 | <p>I want to include some HTML, spezific a bootstrap modal box.</p>
<p>This is my function with the HTML part:</p>
<pre><code>public function dmd_fav_modal_box() {
$content = '<div class="modal fade" id="dmd_favorite_modal" tabindex="-1" role="dialog" aria-labelledby="dmd_favorite_modalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
</div>
<div class="modal-body">
<p>Test</p>
</div>
<!--div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div-->
</div>
</div>
</div>';
return $content;
}
</code></pre>
<p>In my constructor I tried some filter and actions.</p>
<p>E.g.</p>
<pre><code>add_action( 'wp_head', array($this, 'dmd_fav_modal_box') );
add_filter( 'the_content', array($this, 'dmd_fav_modal_box') );
</code></pre>
<p>But nothing works. Can somebody help me?</p>
| [
{
"answer_id": 241745,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>You only need the_content filter to add the modal, but bootstrap.js is needed to make it work.</p>\n\n<pre><cod... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78481/"
] | I want to include some HTML, spezific a bootstrap modal box.
This is my function with the HTML part:
```
public function dmd_fav_modal_box() {
$content = '<div class="modal fade" id="dmd_favorite_modal" tabindex="-1" role="dialog" aria-labelledby="dmd_favorite_modalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p>Test</p>
</div>
<!--div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div-->
</div>
</div>
</div>';
return $content;
}
```
In my constructor I tried some filter and actions.
E.g.
```
add_action( 'wp_head', array($this, 'dmd_fav_modal_box') );
add_filter( 'the_content', array($this, 'dmd_fav_modal_box') );
```
But nothing works. Can somebody help me? | You only need the\_content filter to add the modal, but bootstrap.js is needed to make it work.
```
add_action('wp_enqueue_scripts', array($this, 'enqueue_bootstrap');
public function enqueue_bootstrap(){
wp_register_script( 'bootstrap', plugins_url( 'your-plugin/assets/js/bootstrap.min.js' ) );
wp_enqueue_script( 'bootstrap' );
}
```
EDIT:
You need to add $content argument to your function.
As the codex says
>
> Note that the filter function must return the content after it is finished processing, or site visitors will see a blank page and other plugins also filtering the content may generate errors.
>
>
>
in your case:
```
public function dmd_fav_modal_box($content) {
$modal = '<div class="modal fade" id="dmd_favorite_modal" tabindex="-1" role="dialog" aria-labelledby="dmd_favorite_modalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p>Test</p>
</div>
<!--div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div-->
</div>
</div>
</div>';
return $modal.$content;
``` |
241,790 | <p>The idea here is to be able to use the Link button to search through posts as usual, but, once selected, use the shortlink (with something like <code>wp_get_shortlink();</code>) instead of the permalink:</p>
<p><code><a href="http://example.com/?p=1234">The Link</a></code></p>
<p>Not sure if it would be easier to add this function to the existing button or add a new button with this dedicated behavior.</p>
| [
{
"answer_id": 241799,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>You'd go with new button, which will place i.e. <code>[post_shrtl]</code> anywhere in content area (or you ca... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241790",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86280/"
] | The idea here is to be able to use the Link button to search through posts as usual, but, once selected, use the shortlink (with something like `wp_get_shortlink();`) instead of the permalink:
`<a href="http://example.com/?p=1234">The Link</a>`
Not sure if it would be easier to add this function to the existing button or add a new button with this dedicated behavior. | If you mean the *link dialog*, then we can modify the *permalinks* with the [`wp_link_query`](https://developer.wordpress.org/reference/hooks/wp_link_query/) filter:
```
add_filter( 'wp_link_query', function( $results )
{
foreach( $results as &$result )
$result['permalink'] = wp_get_shortlink( $result['ID'] );
return $results;
} );
```
where we use [`wp_get_shortlink()`](https://codex.wordpress.org/Function_Reference/wp_get_shortlink) to get the *short links*. |
241,814 | <p>When you request posts using WP API's search mechanism, it returns tags as one of the post's properties, but it is an array of tag IDs, not tag names. Is there a way to make the API include the name of the tags without making subsequent requests to the API by tag ID for each one?</p>
<pre><code>tags: [
188,
30,
151,
189
]
</code></pre>
<p>I couldn't find any parameter in the API docs that does this, so I was thinking of creating a custom plugin to maybe filter and substitute the tag ID's for names before the response is sent back to the API caller. In that case, what action should I listen for?</p>
| [
{
"answer_id": 241819,
"author": "The Unknown Dev",
"author_id": 102669,
"author_profile": "https://wordpress.stackexchange.com/users/102669",
"pm_score": 4,
"selected": true,
"text": "<p>I figured something out based on what I found at this <a href=\"https://www.haselt.com/blog/wp-rest-... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102669/"
] | When you request posts using WP API's search mechanism, it returns tags as one of the post's properties, but it is an array of tag IDs, not tag names. Is there a way to make the API include the name of the tags without making subsequent requests to the API by tag ID for each one?
```
tags: [
188,
30,
151,
189
]
```
I couldn't find any parameter in the API docs that does this, so I was thinking of creating a custom plugin to maybe filter and substitute the tag ID's for names before the response is sent back to the API caller. In that case, what action should I listen for? | I figured something out based on what I found at this [post](https://www.haselt.com/blog/wp-rest-api-modifying-the-json-response).
Basically I need a plugin that listens for when the REST response is about to go out. The plugin code would be similar to the following:
```
function ag_filter_post_json($response, $post, $context) {
$tags = wp_get_post_tags($post->ID);
$response->data['tag_names'] = [];
foreach ($tags as $tag) {
$response->data['tag_names'][] = $tag->name;
}
return $response;
}
add_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 );
```
It adds the tag names as a new property called `tag_names`. The rest of the heavy lifting is done by the [`wp_get_post_tags`](https://codex.wordpress.org/Function_Reference/wp_get_post_tags) function. |
241,828 | <p>I need to create an excerpt that doesn't stop with an orphan word such as:</p>
<p><em>All I’ve got to do is pass as an ordinary human being. Simple. What could possibly go wrong? Did I mention we have comfy chairs? I’m the Doctor, I’m worse than everyone’s aunt. catches himself And that is not how I’m introducing myself.You hit me with a cricket bat. It’s more...Read More</em></p>
<p>I need it to end with <em>"You hit me with a cricket bat"</em> (the last complete sentence is where I want it to stop).</p>
<p>I found this on <a href="https://wordpress.stackexchange.com/a/108857/5549">another post</a>:</p>
<pre><code>add_filter('get_the_excerpt', 'end_with_sentence');
function end_with_sentence($excerpt) {
$allowed_end = array('.', '!', '?', '...');
$exc = explode( ' ', $excerpt );
$found = false;
$last = '';
while ( ! $found && ! empty($exc) ) {
$last = array_pop($exc);
$end = strrev( $last );
$found = in_array( $end{0}, $allowed_end );
}
return (! empty($exc)) ? $excerpt : rtrim(implode(' ', $exc) . ' ' .$last);
}
</code></pre>
<p>and then I add this to my template:</p>
<pre><code><?php get_the_excerpt(); ?>
</code></pre>
<p>But it doesn't seem to work. It doesn't display anything. </p>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 241836,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 1,
"selected": false,
"text": "<p>Use this function instead. Then put <code>the_excerpt();</code> in your template.</p>\n\n<pre><code>/**\n * Fin... | 2016/10/06 | [
"https://wordpress.stackexchange.com/questions/241828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56854/"
] | I need to create an excerpt that doesn't stop with an orphan word such as:
*All I’ve got to do is pass as an ordinary human being. Simple. What could possibly go wrong? Did I mention we have comfy chairs? I’m the Doctor, I’m worse than everyone’s aunt. catches himself And that is not how I’m introducing myself.You hit me with a cricket bat. It’s more...Read More*
I need it to end with *"You hit me with a cricket bat"* (the last complete sentence is where I want it to stop).
I found this on [another post](https://wordpress.stackexchange.com/a/108857/5549):
```
add_filter('get_the_excerpt', 'end_with_sentence');
function end_with_sentence($excerpt) {
$allowed_end = array('.', '!', '?', '...');
$exc = explode( ' ', $excerpt );
$found = false;
$last = '';
while ( ! $found && ! empty($exc) ) {
$last = array_pop($exc);
$end = strrev( $last );
$found = in_array( $end{0}, $allowed_end );
}
return (! empty($exc)) ? $excerpt : rtrim(implode(' ', $exc) . ' ' .$last);
}
```
and then I add this to my template:
```
<?php get_the_excerpt(); ?>
```
But it doesn't seem to work. It doesn't display anything.
What am I doing wrong? | Use this function instead. Then put `the_excerpt();` in your template.
```
/**
* Find the last period in the excerpt and remove everything after it.
* If no period is found, just return the entire excerpt.
*
* @param string $excerpt The post excerpt.
*/
function end_with_sentence( $excerpt ) {
if ( ( $pos = mb_strrpos( $excerpt, '.' ) ) !== false ) {
$excerpt = substr( $excerpt, 0, $pos + 1 );
}
return $excerpt;
}
add_filter( 'the_excerpt', 'end_with_sentence' );
``` |
241,837 | <p>This is the message that I got shortly after I clicked on the option to upgrade to the newest version of Wordpress. I made the mistake of NOT backing up my files somewhere and now I am wondering if I have to rebuild the site from scratch. I do not have direct access to the host server. What do you advise?</p>
<p>Fatal error: Call to undefined function wp_cache_get() in /home/andrewb/public_html/DanielaSzasz11.com/wp-includes/option.php on line 1117</p>
| [
{
"answer_id": 241836,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 1,
"selected": false,
"text": "<p>Use this function instead. Then put <code>the_excerpt();</code> in your template.</p>\n\n<pre><code>/**\n * Fin... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241837",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104412/"
] | This is the message that I got shortly after I clicked on the option to upgrade to the newest version of Wordpress. I made the mistake of NOT backing up my files somewhere and now I am wondering if I have to rebuild the site from scratch. I do not have direct access to the host server. What do you advise?
Fatal error: Call to undefined function wp\_cache\_get() in /home/andrewb/public\_html/DanielaSzasz11.com/wp-includes/option.php on line 1117 | Use this function instead. Then put `the_excerpt();` in your template.
```
/**
* Find the last period in the excerpt and remove everything after it.
* If no period is found, just return the entire excerpt.
*
* @param string $excerpt The post excerpt.
*/
function end_with_sentence( $excerpt ) {
if ( ( $pos = mb_strrpos( $excerpt, '.' ) ) !== false ) {
$excerpt = substr( $excerpt, 0, $pos + 1 );
}
return $excerpt;
}
add_filter( 'the_excerpt', 'end_with_sentence' );
``` |
241,854 | <p>I've implemented some AJAX functionality for my plugin and it works fine as long as I'm not logged in as admin - then <code>wp_verify_nonce</code> fails. It works for unauthorized users and authorized regular users too.</p>
<p>Here's my PHP class (I removed everything that is not relevant to the issue):</p>
<pre><code>class My_Ajax {
function __construct() {
add_action( 'wp_ajax_geoip_citylist', array($this, 'geoip_citylist') );
add_action( 'wp_ajax_nopriv_geoip_citylist', array($this, 'geoip_citylist') );
add_action( 'wp_enqueue_scripts', array($this, 'geoip_localize_js'), 11 );
}
function geoip_citylist() {
if ( ! wp_verify_nonce($_POST['geoipNonce'], 'my_geoip_nonce') ) {
exit('Wrong nonce: ' . $_POST['geoipNonce']);
}
}
function geoip_localize_js() {
wp_localize_script(
'my_custom_js', 'myGeoipAjaxObject',
array(
'myGeoipNonce' => wp_create_nonce('my_geoip_nonce')
)
);
}
}
</code></pre>
<p>And here's my Javascript:</p>
<pre><code>$.ajax({
url: myMainAjaxObject.ajaxUrl,
type: 'POST',
dataType: 'json',
data: {
geoipNonce: myGeoipAjaxObject.myGeoipNonce,
action: "geoip_citylist"
},
success: function(data) {
replacePhones(data.user_city, data.current_phone, data.city_list);
},
error: function(error) {
console.log(error);
}
});
</code></pre>
<p>The nonce in PHP error response seems to be correct, but it still doesn't validate for some reason.</p>
<p>I've spent days trying to figure out what's wrong and trying to google this in every possible way, but so far I couldn't find a solution that would work. There are unanswered questions with similar issues on stackoverflow, like <a href="https://stackoverflow.com/questions/7375058/wordpress-nonce-check-always-false#comment67104942_7375058">this one</a> which was created in 2011... I could just assume that nonces don't work with admin accounts in Wordpress, but I would like to at least get a confirmation before giving up.</p>
<p><strong>UPDATE:</strong>
I've tried to use just the code that I provided here and it still resulted with the same error (I also double checked the cache and it was refreshed).</p>
<p><strong>UPDATE 2:</strong>
<code>myMainAjaxObject</code> and its <code>ajaxUrl</code> are inserted in another script. Since AJAX URL is same for every AJAX request, I just use the global one instead of redefining it every time. So this is not what's causing the error. Also if it wouldn't be defined it would never work. Once again, it doesn't work only for the admin, for other users and unauthorized users it works fine. And I do get "Wrong nonce: 73dd02f662" in the server response when I'm logged as admin. So I'm 100% sure that URL is correct.</p>
| [
{
"answer_id": 241871,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>Ajax URL in WordPress is something like this <code>https://examle.com/wp-admin/admin-ajax.php</code>. When yo... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86509/"
] | I've implemented some AJAX functionality for my plugin and it works fine as long as I'm not logged in as admin - then `wp_verify_nonce` fails. It works for unauthorized users and authorized regular users too.
Here's my PHP class (I removed everything that is not relevant to the issue):
```
class My_Ajax {
function __construct() {
add_action( 'wp_ajax_geoip_citylist', array($this, 'geoip_citylist') );
add_action( 'wp_ajax_nopriv_geoip_citylist', array($this, 'geoip_citylist') );
add_action( 'wp_enqueue_scripts', array($this, 'geoip_localize_js'), 11 );
}
function geoip_citylist() {
if ( ! wp_verify_nonce($_POST['geoipNonce'], 'my_geoip_nonce') ) {
exit('Wrong nonce: ' . $_POST['geoipNonce']);
}
}
function geoip_localize_js() {
wp_localize_script(
'my_custom_js', 'myGeoipAjaxObject',
array(
'myGeoipNonce' => wp_create_nonce('my_geoip_nonce')
)
);
}
}
```
And here's my Javascript:
```
$.ajax({
url: myMainAjaxObject.ajaxUrl,
type: 'POST',
dataType: 'json',
data: {
geoipNonce: myGeoipAjaxObject.myGeoipNonce,
action: "geoip_citylist"
},
success: function(data) {
replacePhones(data.user_city, data.current_phone, data.city_list);
},
error: function(error) {
console.log(error);
}
});
```
The nonce in PHP error response seems to be correct, but it still doesn't validate for some reason.
I've spent days trying to figure out what's wrong and trying to google this in every possible way, but so far I couldn't find a solution that would work. There are unanswered questions with similar issues on stackoverflow, like [this one](https://stackoverflow.com/questions/7375058/wordpress-nonce-check-always-false#comment67104942_7375058) which was created in 2011... I could just assume that nonces don't work with admin accounts in Wordpress, but I would like to at least get a confirmation before giving up.
**UPDATE:**
I've tried to use just the code that I provided here and it still resulted with the same error (I also double checked the cache and it was refreshed).
**UPDATE 2:**
`myMainAjaxObject` and its `ajaxUrl` are inserted in another script. Since AJAX URL is same for every AJAX request, I just use the global one instead of redefining it every time. So this is not what's causing the error. Also if it wouldn't be defined it would never work. Once again, it doesn't work only for the admin, for other users and unauthorized users it works fine. And I do get "Wrong nonce: 73dd02f662" in the server response when I'm logged as admin. So I'm 100% sure that URL is correct. | I think the problem was that I manually deleted my cookies a few times while testing. Among them was a cookie called "wordpress\_logged\_in\_{token}" where {token} is an unique identifier. My best guess is that lack of this cookie caused issues with nonce creation or/and verification. It was hard to notice because I was still able to browse the admin panel (it looks like there WP is using a different cookie called "wordpress\_{token}") and on the front end this website doesn't show user status anywhere (accounts are not used there, however login functionality is there, just hidden from the view).
The solution was very simple - I just re-logged as admin and my AJAX started working for the admin as well. So if someone runs into a similar issue, make sure that when you clear cookies, you either delete only ones that you need to remove/regenerate or, if you delete all of them like I did, make sure to re-log as admin.
PS: I'm sorry I didn't provide all the details from the start, but I did try to provide as much information as necessary. I knew I was missing something and now I feel stupid for even asking this question. However, I'm not going to delete it so that maybe someone who runs into the same issue could save some time. |
241,867 | <p>many users would to allow the registration in a wp site without an username, just only with an email.</p>
<p>This is a core problem, so the solution (a trick) is to replace username with email.</p>
<p>If wp requires an username and an email for the registration, we can get email value and put it in username value. In the registration form users will see two fields: </p>
<ol>
<li>your email</li>
<li>repeat your email</li>
</ol>
<p>This is a trick, because for wp the real fields will be:
1. username (as your email)
2. your email (as repeat your email)</p>
<p>But there is another problem: is the <em>@</em> (at) an allowed character for username?</p>
<p>How can we do this?</p>
<p>Should we insert a code in <em>functions.php</em> file?.. something like this:</p>
<pre><code>add_action( 'wp_core_validate_user_signup', 'custom_validate_user_signup' );
function custom_validate_user_signup($result)
{
unset($result['errors']->errors['user_name']);
if(!empty($result['user_email']) && empty($result['errors']->errors['user_email']))
{
$result['user_name'] = md5($result['user_email']);
$_POST['signup_username'] = $result['user_name'];
}
return $result;
}
</code></pre>
<p>Thank you in advance!</p>
| [
{
"answer_id": 241882,
"author": "websupporter",
"author_id": 48693,
"author_profile": "https://wordpress.stackexchange.com/users/48693",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <code>@</code> and <code>.</code> in usernames, so there is no problem. Now you could create ... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104428/"
] | many users would to allow the registration in a wp site without an username, just only with an email.
This is a core problem, so the solution (a trick) is to replace username with email.
If wp requires an username and an email for the registration, we can get email value and put it in username value. In the registration form users will see two fields:
1. your email
2. repeat your email
This is a trick, because for wp the real fields will be:
1. username (as your email)
2. your email (as repeat your email)
But there is another problem: is the *@* (at) an allowed character for username?
How can we do this?
Should we insert a code in *functions.php* file?.. something like this:
```
add_action( 'wp_core_validate_user_signup', 'custom_validate_user_signup' );
function custom_validate_user_signup($result)
{
unset($result['errors']->errors['user_name']);
if(!empty($result['user_email']) && empty($result['errors']->errors['user_email']))
{
$result['user_name'] = md5($result['user_email']);
$_POST['signup_username'] = $result['user_name'];
}
return $result;
}
```
Thank you in advance! | You can use `@` and `.` in usernames, so there is no problem. Now you could create your own register form and use [`register_new_user()`](https://codex.wordpress.org/Function_Reference/register_new_user). You could even manipulate [`wp_registration_url()`](https://codex.wordpress.org/Function_Reference/wp_registration_url) with the filter [`register_url`](https://codex.wordpress.org/Plugin_API/Filter_Reference/register_url), so the register link would point to your new register page.
If you want to use it with the standard interface provided by *wp-login.php*, you would need some workarounds. Lets say, you only want to display the email input field for registration, you could simply (well, its a bit hacky though) hide the username field with something like this:
```
add_action( 'register_form', function() {
?><style>#registerform > p:first-child{display:none;}</style><?php
} );
```
Sidenote: There is also a possibility to enqueue stylesheets into the *wp-login.php* using the `login_enqueue_scripts` action.
But if you do so you will send an empty username, so you have to hook into two filters: [`sanitize_user`](https://codex.wordpress.org/Plugin_API/Filter_Reference/sanitize_user) and `validate_username`.
```
add_filter( 'sanitize_user', function( $sanitized_user, $raw_user, $strict ) {
if ( $raw_user != '' ) {
return $sanitized_user;
}
if ( ! empty ( $_REQUEST['action'] ) && $_REQUEST['action'] === 'register' && is_email( $_POST['user_email'] ) ) {
return $_POST['user_email'];
}
return $sanitized_user;
}, 10, 3 );
add_filter( 'validate_username', function( $valid, $username ) {
if ( $valid ) {
return $valid;
}
if ( ! empty ( $_REQUEST['action'] ) && $_REQUEST['action'] === 'register' && is_email( $_POST['user_email'] ) ) {
return true;
}
return is_email( $username );
}, 10, 2 );
```
In `sanitize_user` we replace the empty string with the email address. Later the username will be validated with `validate_username`, but again, the empty username will be used, so we need to catch this too.
But I think to create an own form would be preferred and less hacky. |
241,878 | <p>I have lots of Word documents that form training materials for work. I would like to develop a website to act as a repository for these documents. However, rather than just store them on a web server and provide links to the files, I would like (if possible) for the visitor to be able to view the documents via the website and print it from there (or choose to download the actual Word document if they so wish).</p>
<p>I know that you can 'save' a Word document as a .html page and then I could potentially upload them all but I was really hoping for something a bit less clunky. And also to embed the Word documents into my web pages with a custom header/footer so they looked like a normal page on the website and fitted in with everything else.</p>
<p>Is this possible?</p>
<p>Thanks.</p>
| [
{
"answer_id": 241896,
"author": "isaacsgraphic",
"author_id": 89562,
"author_profile": "https://wordpress.stackexchange.com/users/89562",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't need the users to be able to edit the word documents, it might be a good option to save th... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39292/"
] | I have lots of Word documents that form training materials for work. I would like to develop a website to act as a repository for these documents. However, rather than just store them on a web server and provide links to the files, I would like (if possible) for the visitor to be able to view the documents via the website and print it from there (or choose to download the actual Word document if they so wish).
I know that you can 'save' a Word document as a .html page and then I could potentially upload them all but I was really hoping for something a bit less clunky. And also to embed the Word documents into my web pages with a custom header/footer so they looked like a normal page on the website and fitted in with everything else.
Is this possible?
Thanks. | The real problem here is the download offer. Let's separate the two tasks first, to see that better.
Upload
------
### 1. … from Word directly
Word can communicate with WordPress directly per `xmlrpc.php`. When you ope a new file, select **Blog post** as template, then enter your user credentials once. Word will remember those. It might be useful to use a separate account for that, just in case MS is phoning home that too.
Now you can publish your Word text directly to WordPress. You can also edit them later, and even import existing blog posts for further editing. Keep in mind that Word will embed its own styles directly into the HTML code. This is rather ugly.
There is a [post on WPMU Dev about the details](https://premium.wpmudev.org/blog/how-to-use-microsoft-word-to-publish-directly-to-your-wordpress-site/).
2. … as PDF
-----------
There are many drivers for Windows which allow you to print a document as PDF. Either find one with a developer API and an event handling, so you can attach an upload handler to the print action, or write a custom shell script that is watching one directory on your hard drive and will upload the file whenever one is changed or replaced.
The tricky part here is that you cannot publish a PDF as blog post, and you have to add the file to the media library. The latter can be done per XML RPC too.
Download
--------
If your text is stored as HTML, like in the first option, you would have to convert the HTML back to Word again. There are many tools for that. You could try [PHPWord](https://github.com/PHPOffice/PHPWord).
The actual WordPress handler could listen on the actions in `wp-admin/admin-post.php` as described in Export data as [CSV in back end with proper HTTP headers](https://wordpress.stackexchange.com/a/102452/73):
```
if ( is_admin() )
{
$action = 'print_doc';
add_action( "admin_post_nopriv_{$action}", 'print_word' );
add_action( "admin_post_{$action}", 'print_word' );
}
function print_word()
{
$post_id = filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT );
if ( ! $post_id )
return;
$post = get_post( $post_id );
status_header( 200 );
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename=' . $post->post_name . '.docx');
header('Pragma: no-cache');
// Convert $post->post_content to Word
// Output the Word document
exit;
}
```
To create the link on the front end, you can filter `the_content`:
```
if ( ! is_admin() )
{
add_filter( 'the_content', function( $content ) {
if ( ! is_singular() )
return $content;
$post_id = get_the_ID();
$url = admin_url( 'admin-post.php' );
$link = sprintf(
'<p class="download-link"><a href="%s">Download</a></p>',
admin_url( 'admin-post.php' ) . '?action=print_doc&id=' . $post_id
);
return $content . $link;
});
}
```
If you have uploaded the file as PDF, use `get_attached_media()` here, filter its return value for PDF. and create the link the same way as above. |
241,879 | <p>I am trying to access data from another website to display on a WordPress Website I am developing. So far I have the following:</p>
<pre><code><?php
/*
Template Name: Testing remote data
*/
get_header();
<div class="main">
<div class="col-sm-12">
<header>
<h2>Testing remote data</h2>
</header>
</div>
<div class="container">
<div id="content" role="main">
<div class="col-sm-12">
<?php
$url = 'http://www.bbc.co.uk/news/';// this url is only for example purposes
$request = wp_remote_get( $url );
if(is_wp_error($request)) {
return false;
} else {
$body = $request['body'];
}
echo $body;
</div>
</div>
</div>
</div>
</code></pre>
<p>This works fine. However, I get the whole body content. How would I go about getting specific sections of the body? If any one could help me with this I would really appreciate it. Sorry if it's an obvious one but I am new to WordPress and I am still far from comfortable with it.</p>
| [
{
"answer_id": 264658,
"author": "Aishan",
"author_id": 89530,
"author_profile": "https://wordpress.stackexchange.com/users/89530",
"pm_score": 0,
"selected": false,
"text": "<p>you can access data from other website via RSS feed. \nYou can see the RSS feed of bbc news in the following u... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82982/"
] | I am trying to access data from another website to display on a WordPress Website I am developing. So far I have the following:
```
<?php
/*
Template Name: Testing remote data
*/
get_header();
<div class="main">
<div class="col-sm-12">
<header>
<h2>Testing remote data</h2>
</header>
</div>
<div class="container">
<div id="content" role="main">
<div class="col-sm-12">
<?php
$url = 'http://www.bbc.co.uk/news/';// this url is only for example purposes
$request = wp_remote_get( $url );
if(is_wp_error($request)) {
return false;
} else {
$body = $request['body'];
}
echo $body;
</div>
</div>
</div>
</div>
```
This works fine. However, I get the whole body content. How would I go about getting specific sections of the body? If any one could help me with this I would really appreciate it. Sorry if it's an obvious one but I am new to WordPress and I am still far from comfortable with it. | ```
// make request... (optionally save in transient for faster future fetches)
$dom = new DOMDocument();
$dom->loadHTML(wp_remote_retrieve_body($request));
$sections=$dom->getElementsByTagName("section");
foreach ($sections as $section) {
// Do something...
}
``` |
241,880 | <p>Before deciding to ask this question, I googled and searched this forum, but found no answer to my question, even though it may seem like a duplicate.</p>
<p>Anyway, I made custom post type that uses its featured image. Now, I would like to set if no featured image exists, show post content and by that I mean show whatever it is in my post ( in my case it is embedded youtube video).</p>
<p>So far I added to functions.php the following:</p>
<pre><code>function zm_get_backend_preview_thumb($post_ID) {
$post_thumbnail_id = get_post_thumbnail_id($post_ID);
if ($post_thumbnail_id) {
$post_thumbnail_img = wp_get_attachment_image_src($post_thumbnail_id, 'thumbnail');
return $post_thumbnail_img[0];
}
}
function zm_preview_thumb_column_head($defaults) {
$defaults['featured_image'] = 'Image';
return $defaults;
}
add_filter('manage_posts_columns', 'zm_preview_thumb_column_head');
function zm_preview_thumb_column($column_name, $post_ID) {
if ($column_name == 'featured_image') {
$post_featured_image = zm_get_backend_preview_thumb($post_ID);
if ($post_featured_image) {
echo '<img src="' . $post_featured_image . '" />';
}
}
}
add_action('manage_posts_custom_column', 'zm_preview_thumb_column', 10, 2);
}
</code></pre>
<p>And in my page where I would like to show the video instead featured image, I have the following code:</p>
<pre><code><?php
// WP_Query arguments
$args = array (
'post_type' => array( 'zm_gallery' ),
);
// The Query
$query_gallery = new WP_Query( $args );
// The Loop
if ( $query_gallery->have_posts() ) {
while ( $query_gallery->have_posts() ) {
$query_gallery->the_post();
echo '<ul>';
echo '<li>';
$name = get_post_meta($post->ID, 'ExternalUrl', true);
if( $name ) { ?>
<a href="<?php echo $name; ?>"target="_blank"><?php the_post_thumbnail(); ?></a>
<?php
} else {
the_post_thumbnail();
}
echo '</li>';
echo '</ul>';
}
} else {
if ( "" === $post->post_content ) {
the_post_thumbnail();
} else {
the_content();
}
}
// Restore original Post Data
wp_reset_postdata();
?>
</code></pre>
<p>Your help would be highly appreciated. Thank you all in advance.</p>
| [
{
"answer_id": 241885,
"author": "Nancy",
"author_id": 101279,
"author_profile": "https://wordpress.stackexchange.com/users/101279",
"pm_score": 0,
"selected": false,
"text": "<p>I managed to realize that I had two problems with my code on the page where I needed post content displayed:<... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101279/"
] | Before deciding to ask this question, I googled and searched this forum, but found no answer to my question, even though it may seem like a duplicate.
Anyway, I made custom post type that uses its featured image. Now, I would like to set if no featured image exists, show post content and by that I mean show whatever it is in my post ( in my case it is embedded youtube video).
So far I added to functions.php the following:
```
function zm_get_backend_preview_thumb($post_ID) {
$post_thumbnail_id = get_post_thumbnail_id($post_ID);
if ($post_thumbnail_id) {
$post_thumbnail_img = wp_get_attachment_image_src($post_thumbnail_id, 'thumbnail');
return $post_thumbnail_img[0];
}
}
function zm_preview_thumb_column_head($defaults) {
$defaults['featured_image'] = 'Image';
return $defaults;
}
add_filter('manage_posts_columns', 'zm_preview_thumb_column_head');
function zm_preview_thumb_column($column_name, $post_ID) {
if ($column_name == 'featured_image') {
$post_featured_image = zm_get_backend_preview_thumb($post_ID);
if ($post_featured_image) {
echo '<img src="' . $post_featured_image . '" />';
}
}
}
add_action('manage_posts_custom_column', 'zm_preview_thumb_column', 10, 2);
}
```
And in my page where I would like to show the video instead featured image, I have the following code:
```
<?php
// WP_Query arguments
$args = array (
'post_type' => array( 'zm_gallery' ),
);
// The Query
$query_gallery = new WP_Query( $args );
// The Loop
if ( $query_gallery->have_posts() ) {
while ( $query_gallery->have_posts() ) {
$query_gallery->the_post();
echo '<ul>';
echo '<li>';
$name = get_post_meta($post->ID, 'ExternalUrl', true);
if( $name ) { ?>
<a href="<?php echo $name; ?>"target="_blank"><?php the_post_thumbnail(); ?></a>
<?php
} else {
the_post_thumbnail();
}
echo '</li>';
echo '</ul>';
}
} else {
if ( "" === $post->post_content ) {
the_post_thumbnail();
} else {
the_content();
}
}
// Restore original Post Data
wp_reset_postdata();
?>
```
Your help would be highly appreciated. Thank you all in advance. | the\_post\_thumbnail will echo out the thumbnail so maybe try
```
if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else {
the_content();
}
```
Hope this helps |
241,903 | <p>I would like to update only themes in my WP without enabling maintenance mode. Is it possible?</p>
| [
{
"answer_id": 241904,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Sure, just upload them to their directories with ftp. After all, updating themes is not much more than copying t... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78021/"
] | I would like to update only themes in my WP without enabling maintenance mode. Is it possible? | 3 years later I solved this issue with this below shell script:
```
#Getting list of outdated themes
/usr/local/bin/wp theme list --update=available --allow-root --path=/var/www | sed -n '1!p' | awk '{print $1}' > /tmp/theme.list
#Update them one by one
while read -r themename
do
#Store the old version number of theme
OLDVER="$(grep Version: /var/www/wp-content/themes/"$themename"/style.css)"
#Download theme
wget -q https://downloads.wordpress.org/theme/"$themename".zip -P /tmp/
#Uncompress .zip file
unzip -oq /tmp/"$themename".zip -d /var/www/wp-content/themes/
#Store the new version number of theme
NEWVER="$(grep Version: /var/www/wp-content/themes/"$themename"/style.css)"
#Create simple log file of theme update
[[ "$OLDVER" != "$NEWVER" ]] && echo "$themename" >> /tmp/success.list || echo "$themename" >> /tmp/failed.list
#Remove downloaded theme file
rm /tmp/"$themename".zip
done < /tmp/theme.list
rm /tmp/theme.list
``` |
241,908 | <p>I have a WP Plugin where i use Font-Awesome Icons. I added the Font-Awesome folder to my Plugin Files and told WordPress to use them:</p>
<pre><code>// add font-awesome to admin area
function ecp_admin_enqueue($hook) {
// check if plugin page
global $ecp_settings_page;
if ( $hook != $ecp_settings_page ) {
return;
}
// add to wp
wp_register_style( 'ecp_admin_fontawesome', plugins_url('/font-awesome/css/font-awesome.min.css' , __FILE__) );
wp_enqueue_style( 'ecp_admin_fontawesome' );
}
add_action( 'admin_enqueue_scripts', 'ecp_admin_enqueue' );
</code></pre>
<p>The CSS is added by WordPress - this is from the Sourcecode of the Backend when i´m on the Plugin Settings-Page:</p>
<pre><code><link rel='stylesheet' id='ecp_admin_fontawesome-css' href='http://url.tld/path/to/plugins/my-plugin/inc/font-awesome/css/font-awesome.min.css?ver=4.6.1' type='text/css' media='all' />
</code></pre>
<p>Font-Awesome is working as it should BUT it changed the default Font from WordPress. How can i fix it or why does this happen?</p>
<p><a href="https://i.stack.imgur.com/Eqvoj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eqvoj.png" alt="enter image description here"></a>
On a WordPress Page like Dashboard</p>
<p><a href="https://i.stack.imgur.com/30cDx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/30cDx.png" alt="enter image description here"></a>
On Plugin Page with Font-Awesome loaded</p>
| [
{
"answer_id": 241922,
"author": "wassereimer",
"author_id": 54551,
"author_profile": "https://wordpress.stackexchange.com/users/54551",
"pm_score": 1,
"selected": true,
"text": "<p>It was not Font-Awesome that changed the default WordPress Style. I also use Bootstrap. One file called sc... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241908",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54551/"
] | I have a WP Plugin where i use Font-Awesome Icons. I added the Font-Awesome folder to my Plugin Files and told WordPress to use them:
```
// add font-awesome to admin area
function ecp_admin_enqueue($hook) {
// check if plugin page
global $ecp_settings_page;
if ( $hook != $ecp_settings_page ) {
return;
}
// add to wp
wp_register_style( 'ecp_admin_fontawesome', plugins_url('/font-awesome/css/font-awesome.min.css' , __FILE__) );
wp_enqueue_style( 'ecp_admin_fontawesome' );
}
add_action( 'admin_enqueue_scripts', 'ecp_admin_enqueue' );
```
The CSS is added by WordPress - this is from the Sourcecode of the Backend when i´m on the Plugin Settings-Page:
```
<link rel='stylesheet' id='ecp_admin_fontawesome-css' href='http://url.tld/path/to/plugins/my-plugin/inc/font-awesome/css/font-awesome.min.css?ver=4.6.1' type='text/css' media='all' />
```
Font-Awesome is working as it should BUT it changed the default Font from WordPress. How can i fix it or why does this happen?
[](https://i.stack.imgur.com/Eqvoj.png)
On a WordPress Page like Dashboard
[](https://i.stack.imgur.com/30cDx.png)
On Plugin Page with Font-Awesome loaded | It was not Font-Awesome that changed the default WordPress Style. I also use Bootstrap. One file called scaffolding.less overrides the WordPress defaults with:
```
// Body reset
html {
font-size: 10px;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
body {
font-family: @font-family-base;
font-size: @font-size-base;
line-height: @line-height-base;
color: @text-color;
background-color: @body-bg;
}
```
I just added this to my custom CSS File (original WordPress CSS) with !important:
```
/* Override Bootstrap Reset with WP default */
body {
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif !important;
}
```
Now WordPress looks like it should again. |
241,921 | <p>after <a href="https://stackoverflow.com/questions/39920420/wordpress-strange-permission-issue">this problem</a> I think that there is a problem if I have two wordpress installation on one pc. I've fallow <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-multiple-wordpress-sites-on-a-single-ubuntu-vps" rel="nofollow noreferrer">this instruction</a> and the only thing is that I've change the wp-contents folder like this</p>
<pre><code>* Default value for some constants if they have not yet been set
by the host-specific config files */
if (!defined('ABSPATH'))
define('ABSPATH', '/var/www/aniabuchi/');
if (!defined('WP_CORE_UPDATE'))
define('WP_CORE_UPDATE', false);
define('DB_HOST', 'localhost');
if (!defined('WP_CONTENT_DIR') && !defined('DONT_SET_WP_CONTENT_DIR'))
define('WP_CONTENT_DIR', '/var/www/aniabuchi/wp-content');
</code></pre>
<p>So the problem is that nothing I've install into the second wordpress is working correct or visible. I've upload Media, Install themes and plugins but I can't see their resources such as images and etc.
I think that this is Alias problem - I have the same alias into every site.conf under /etc/apache2/site-available
<br> first_site.conf -> Alias /wp-content /var/lib/wordpress/wp-content
<br> second_site.conf -> Alias /wp-content /var/www/aniabuchi/wp-content
<br> but how can I resolve it</p>
| [
{
"answer_id": 241931,
"author": "Vasil Ivanov",
"author_id": 104459,
"author_profile": "https://wordpress.stackexchange.com/users/104459",
"pm_score": -1,
"selected": false,
"text": "<p>So I was right and the problem was the alias so no one tell me how to resolve it. I thinking about ho... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241921",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104459/"
] | after [this problem](https://stackoverflow.com/questions/39920420/wordpress-strange-permission-issue) I think that there is a problem if I have two wordpress installation on one pc. I've fallow [this instruction](https://www.digitalocean.com/community/tutorials/how-to-set-up-multiple-wordpress-sites-on-a-single-ubuntu-vps) and the only thing is that I've change the wp-contents folder like this
```
* Default value for some constants if they have not yet been set
by the host-specific config files */
if (!defined('ABSPATH'))
define('ABSPATH', '/var/www/aniabuchi/');
if (!defined('WP_CORE_UPDATE'))
define('WP_CORE_UPDATE', false);
define('DB_HOST', 'localhost');
if (!defined('WP_CONTENT_DIR') && !defined('DONT_SET_WP_CONTENT_DIR'))
define('WP_CONTENT_DIR', '/var/www/aniabuchi/wp-content');
```
So the problem is that nothing I've install into the second wordpress is working correct or visible. I've upload Media, Install themes and plugins but I can't see their resources such as images and etc.
I think that this is Alias problem - I have the same alias into every site.conf under /etc/apache2/site-available
first\_site.conf -> Alias /wp-content /var/lib/wordpress/wp-content
second\_site.conf -> Alias /wp-content /var/www/aniabuchi/wp-content
but how can I resolve it | So I was right and the problem was the alias so no one tell me how to resolve it. I thinking about how can I rename the wp-content for the second wordpress installation. I found a simple tutorial [here](http://www.hongkiat.com/blog/renaming-wordpress-wp-content-folder/) and after made everything from tutorial with the rename procedure now all resources are available. |
241,934 | <p>I've <a href="https://wordpress.org/plugins/remove-http/" rel="nofollow">created a plugin</a> that turns all links into protocol relative URLs, like so:</p>
<pre><code>http://example.com -> //example.com
</code></pre>
<p>I'm also adding a function to force HTTPS only if SSL is enabled and set up properly on the website. The following function below will force HTTPS regardless if it has been set up correctly:</p>
<pre><code>add_action ( 'template_redirect', 'force_https', 1 );
function force_https() {
if ( ! is_ssl() ) {
wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit();
}
}
</code></pre>
<p>However, if SSL hasn't been configured for the website, it will cause a connection error and the user won't be able to access their website. This is where I want to put a check before it executes the <a href="https://developer.wordpress.org/reference/functions/wp_redirect/" rel="nofollow"><code>wp_redirect()</code></a>.</p>
<p>My idea is to check if the <a href="https://developer.wordpress.org/reference/functions/get_home_url/" rel="nofollow"><code>get_home_url()</code></a> option has <code>https://</code> in the URL:</p>
<pre><code>if ( preg_match( '/https:\/\//', site_url() ) && ! is_ssl() ) {
</code></pre>
<p>Is there a better way to check? Or is it not even necessary to force HTTPS if my first function from my plugin has made all of the links protocol-relative?</p>
| [
{
"answer_id": 241940,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>There is no fail proof way to know if the site support https without actually trying to send a request ov... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241934",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | I've [created a plugin](https://wordpress.org/plugins/remove-http/) that turns all links into protocol relative URLs, like so:
```
http://example.com -> //example.com
```
I'm also adding a function to force HTTPS only if SSL is enabled and set up properly on the website. The following function below will force HTTPS regardless if it has been set up correctly:
```
add_action ( 'template_redirect', 'force_https', 1 );
function force_https() {
if ( ! is_ssl() ) {
wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit();
}
}
```
However, if SSL hasn't been configured for the website, it will cause a connection error and the user won't be able to access their website. This is where I want to put a check before it executes the [`wp_redirect()`](https://developer.wordpress.org/reference/functions/wp_redirect/).
My idea is to check if the [`get_home_url()`](https://developer.wordpress.org/reference/functions/get_home_url/) option has `https://` in the URL:
```
if ( preg_match( '/https:\/\//', site_url() ) && ! is_ssl() ) {
```
Is there a better way to check? Or is it not even necessary to force HTTPS if my first function from my plugin has made all of the links protocol-relative? | Based on the comments, there is no foolproof way to check if someone's website has SSL set up correctly. Possible options include a setting in the plugin to have the user confirm that they have SSL set up.
However, one automated way is to check if the site URL has `https://` in it. This is assumed that SSL has been set up properly by the user since the website wouldn't load correctly if they try to set the domain with HTTPS:
```
add_action( 'template_redirect', 'wpse_241934_redirect_https', 1, 1 );
function redirect_https() {
# If 'https://' is in the website's site URL and SSL is not being used, force HTTPS
if ( preg_match( '/https:\/\//', site_url() ) && ! is_ssl() ) {
wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit;
}
}
```
For me, this function wouldn't be necessary since my plugin makes all URLs protocol-relative. This could still be helpful for anyone else who wants to execute a function if a website is running SSL only. |
241,942 | <p>I've been trying to figure this out for about a week and I've got a few different methods that 'work' but I don't feel like are the best/right solutions for the project.</p>
<p>I'm trying to do the following:
I've got grid items that are populated via the WP Posts loop.
The grid items themselves are then wrapped in an tag wherein the post ID is grabbed as a data attribute like so:</p>
<pre><code> <section class="GRIDSECTION">
<?php
query_posts('post_type=CUSTOMTYPE');
while (have_posts()) : the_post();
$postID = get_the_ID();
?>
<a class="GRIDITEM" href="#" data-post_id='<?php echo $postID; ?>' data-post_type='POST-TYPE'>
<h2><?php the_title(); ?></h2>
<span><?php the_field('CUSTOM-CONTENT');?></span>
</a>
<?php
endwhile;
?>
</section>
</code></pre>
<p>And then my AJAX script based on some of the reading I've done:</p>
<pre><code>console.log('01 - AJAX Loaded');
$(".GRIDITEM").click(function () {
console.log('02 - AJAX Starting');
//var id_post = $(this).attr('post_id');
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {
'post_id': ?????,
'action': 'f711_get_post_content' //this is the name of the AJAX method called in WordPress
}, success: function (result) {
console.log('03a - SUCCESS');
alert(result);
},
error: function () {
alert("error");
console.log('03b - FAILURE');
}
});
});
</code></pre>
<p>I'm not sure how to connect pass the ID into the data type with this method.
I figured once I manage to get the post_id passed in, I can do the same thing for the POST-TYPE. </p>
<p>What I intend to do is pass the Post ID and the Custom Post Type into Ajax to send and receive the Post that the GRIDITEM represents.</p>
<p>And then of course, return back to where I started.</p>
<p>Here's the overall feel I want to achieve.</p>
<p><a href="http://tympanus.net/Development/AnimatedGridLayout/" rel="nofollow">http://tympanus.net/Development/AnimatedGridLayout/</a></p>
<p>But since we use custom post types and custom fields in each post, I'm not sure how to call that in. Plus I've only just started using AJAX.</p>
<p>Thanks!</p>
| [
{
"answer_id": 241940,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>There is no fail proof way to know if the site support https without actually trying to send a request ov... | 2016/10/07 | [
"https://wordpress.stackexchange.com/questions/241942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104477/"
] | I've been trying to figure this out for about a week and I've got a few different methods that 'work' but I don't feel like are the best/right solutions for the project.
I'm trying to do the following:
I've got grid items that are populated via the WP Posts loop.
The grid items themselves are then wrapped in an tag wherein the post ID is grabbed as a data attribute like so:
```
<section class="GRIDSECTION">
<?php
query_posts('post_type=CUSTOMTYPE');
while (have_posts()) : the_post();
$postID = get_the_ID();
?>
<a class="GRIDITEM" href="#" data-post_id='<?php echo $postID; ?>' data-post_type='POST-TYPE'>
<h2><?php the_title(); ?></h2>
<span><?php the_field('CUSTOM-CONTENT');?></span>
</a>
<?php
endwhile;
?>
</section>
```
And then my AJAX script based on some of the reading I've done:
```
console.log('01 - AJAX Loaded');
$(".GRIDITEM").click(function () {
console.log('02 - AJAX Starting');
//var id_post = $(this).attr('post_id');
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {
'post_id': ?????,
'action': 'f711_get_post_content' //this is the name of the AJAX method called in WordPress
}, success: function (result) {
console.log('03a - SUCCESS');
alert(result);
},
error: function () {
alert("error");
console.log('03b - FAILURE');
}
});
});
```
I'm not sure how to connect pass the ID into the data type with this method.
I figured once I manage to get the post\_id passed in, I can do the same thing for the POST-TYPE.
What I intend to do is pass the Post ID and the Custom Post Type into Ajax to send and receive the Post that the GRIDITEM represents.
And then of course, return back to where I started.
Here's the overall feel I want to achieve.
<http://tympanus.net/Development/AnimatedGridLayout/>
But since we use custom post types and custom fields in each post, I'm not sure how to call that in. Plus I've only just started using AJAX.
Thanks! | Based on the comments, there is no foolproof way to check if someone's website has SSL set up correctly. Possible options include a setting in the plugin to have the user confirm that they have SSL set up.
However, one automated way is to check if the site URL has `https://` in it. This is assumed that SSL has been set up properly by the user since the website wouldn't load correctly if they try to set the domain with HTTPS:
```
add_action( 'template_redirect', 'wpse_241934_redirect_https', 1, 1 );
function redirect_https() {
# If 'https://' is in the website's site URL and SSL is not being used, force HTTPS
if ( preg_match( '/https:\/\//', site_url() ) && ! is_ssl() ) {
wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit;
}
}
```
For me, this function wouldn't be necessary since my plugin makes all URLs protocol-relative. This could still be helpful for anyone else who wants to execute a function if a website is running SSL only. |
241,961 | <p>With wordpress 4.6.1 is it possible to create a child theme layout of the wp-login page with its own CSS this way original wp-login page and it's defaults are preserved?</p>
<p>How can I hook into the head of this page for custom stylesheets and hook into the body for custom html?</p>
| [
{
"answer_id": 242334,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 3,
"selected": true,
"text": "<p>In <code>functions.php</code> in your child theme, you can do a couple different things on the login sc... | 2016/10/08 | [
"https://wordpress.stackexchange.com/questions/241961",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
] | With wordpress 4.6.1 is it possible to create a child theme layout of the wp-login page with its own CSS this way original wp-login page and it's defaults are preserved?
How can I hook into the head of this page for custom stylesheets and hook into the body for custom html? | In `functions.php` in your child theme, you can do a couple different things on the login screen. First, you'll want to add a custom stylesheet by hooking into `login_enqueue_scripts`.
```
add_action( 'login_enqueue_scripts', 'wpse_login_styles' );
function wpse_login_styles() {
wp_enqueue_style( 'wpse-custom-login', get_stylesheet_directory_uri() . '/style-login.css' );
}
```
Then you can create a `styles-login.css` file in the root of your child theme directory (or adjust the path in `wp_enqueue_script` based on your needs).
Once you've made it that far, you can customize the login page however you'd like using CSS in that file. For example, change the login logo with these instructions ripped from [the Codex](https://codex.wordpress.org/Customizing_the_Login_Form#Change_the_Login_Logo):
```
#login h1 a, .login h1 a {
background-image: url(path/to/login/logo.png);
padding-bottom: 30px;
}
```
Beyond CSS, you can also change the URL and site title on this page using the `login_headerurl` and `login_headertitle` hooks, also described in the above Codex link.
If you want to go further like adding elements to the page, or even creating a custom login page, that's all described [here](https://codex.wordpress.org/Customizing_the_Login_Form#Login_Hooks) and [here](https://codex.wordpress.org/Customizing_the_Login_Form#Make_a_Custom_Login_Page). |
241,996 | <p>I am using ajax in wordpress , i have done every thing right please update me why i ajax returning zero even if code is correct is there something else in the page which is forcing ajax to return 0. her eis my code for js</p>
<pre><code> jQuery('#seller-shop').on('focusout', function() {
var self = jQuery(this);
jQuery.ajax({
type: 'POST',
url: script.axurl,
data: {"action": "wk_check_myshop","shop_slug":self.val(),"nonce":script.nonce},
success: function(resp)
{
console.log(resp);
if ( response == 0){
console.log(response);
}
}
});
});
</code></pre>
<p>code for php is </p>
<pre><code>add_action( 'wp_ajax_nopriv_wk_check_myshop',array($mp_obj,'wk_check_myshop_value') );
add_action( 'wp_ajax_wk_check_myshop',array($mp_obj,'wk_check_myshop_value'));
</code></pre>
<p>Thsi code is inside wp enqueue script hook</p>
<pre><code>wp_localize_script( 'marketplace', 'script', array( 'axurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('ajaxnonce'), 'seller_page' => $page_name , 'site_url' =>site_url() ));
</code></pre>
| [
{
"answer_id": 242001,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": -1,
"selected": true,
"text": "<p>Your Ajax hooked function is:</p>\n\n<pre><code>function wk_check_myshop_value() { echo \"asdasd\... | 2016/10/08 | [
"https://wordpress.stackexchange.com/questions/241996",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103243/"
] | I am using ajax in wordpress , i have done every thing right please update me why i ajax returning zero even if code is correct is there something else in the page which is forcing ajax to return 0. her eis my code for js
```
jQuery('#seller-shop').on('focusout', function() {
var self = jQuery(this);
jQuery.ajax({
type: 'POST',
url: script.axurl,
data: {"action": "wk_check_myshop","shop_slug":self.val(),"nonce":script.nonce},
success: function(resp)
{
console.log(resp);
if ( response == 0){
console.log(response);
}
}
});
});
```
code for php is
```
add_action( 'wp_ajax_nopriv_wk_check_myshop',array($mp_obj,'wk_check_myshop_value') );
add_action( 'wp_ajax_wk_check_myshop',array($mp_obj,'wk_check_myshop_value'));
```
Thsi code is inside wp enqueue script hook
```
wp_localize_script( 'marketplace', 'script', array( 'axurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('ajaxnonce'), 'seller_page' => $page_name , 'site_url' =>site_url() ));
``` | Your Ajax hooked function is:
```
function wk_check_myshop_value() { echo "asdasd"; die;}
```
Try changing `die;` to `die();` |
242,023 | <p>I know how to use <a href="https://codex.wordpress.org/Customizing_the_Read_More" rel="nofollow">read more technique</a> to only view an excerpt of the topic on the homepage and click on the read more icon to open the post and view the full content.</p>
<p>Can we do it on the post itself? When the visitor open the post page itself (not the homepage), only an excerpt is available and they should click on "<em>read more</em>" to view the full content.</p>
| [
{
"answer_id": 242041,
"author": "Dmitry Gamolin",
"author_id": 86509,
"author_profile": "https://wordpress.stackexchange.com/users/86509",
"pm_score": 2,
"selected": false,
"text": "<p>The solution might depend on why exactly you want it to work that way on the post page. But probably t... | 2016/10/08 | [
"https://wordpress.stackexchange.com/questions/242023",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104522/"
] | I know how to use [read more technique](https://codex.wordpress.org/Customizing_the_Read_More) to only view an excerpt of the topic on the homepage and click on the read more icon to open the post and view the full content.
Can we do it on the post itself? When the visitor open the post page itself (not the homepage), only an excerpt is available and they should click on "*read more*" to view the full content. | The solution might depend on why exactly you want it to work that way on the post page. But probably the best way would be to do this on the client side.
**Method with maximum height**
Let's say your post template has its content like this:
```
<div id="content"><?php the_content(); ?></div>
```
You need to add a button after this div, so it would become:
```
<div id="content"><?php the_content(); ?></div>
<button class="show-more">Show more</button>
```
Then you add CSS to only show the content up to specific height, in your style.css add:
```
#content { max-height: 100px; overflow: hidden; }
.show-more { margin-top: 15px; }
```
Finally, add a script that would show the full height of content and remove "show-more" button after it's clicked:
```
jQuery(document).ready(function($) {
$('.show-more').click(function() {
$('#content').css('max-height', 'none');
$(this).remove();
});
});
```
It's just a basic setup, so feel free to adjust the styles and the script as you'd like.
Here's a link to the fiddle where you can try it out: <https://jsfiddle.net/psxtur2L/>
**Method with replacing the content**
If you want to specifically show the excerpt as a short version, you can do it this way.
In your template, you add both the excerpt and the content, and a button, like this:
```
<div id="excerpt"><?php the_excerpt(); ?></div>
<div id="content"><?php the_content(); ?></div>
<button class="show-more">Show more</button>
```
In CSS you just hide the content by default:
```
#content { display: none; }
.show-more { margin-top: 15px; }
```
And then you hide the excerpt and show the content when the user clicks on the button:
```
jQuery(document).ready(function($) {
$('.show-more').click(function() {
$('#excerpt').hide();
$('#content').show();
$(this).remove();
});
});
```
Here's a fiddle for that: <https://jsfiddle.net/o7z2Lsks/>
Note that the user can access full content without clicking the button if he's using browser's debugger tool, but I assume that it is not important. If you would need to make checks whether the user is logged in and so on, you should rather use AJAX, so it would require more additions to the code. |
242,033 | <p>Defining Open Graph meta tags like this for images.</p>
<pre><code>global $post;
$postImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 1200, 9999 ), false );
<meta property="og:image" content="<?php echo $postImg[0]; ?>"/>
<meta property="og:image:width" content="<?php echo $postImg[1]; ?>"/>
<meta property="og:image:height" content="<?php echo $postImg[2]; ?>"/>
</code></pre>
<p>I get this in my website source:</p>
<pre><code><meta property="og:image" content="http://elpace.co/event-image.jpg"/>
<meta property="og:image:width" content="2953"/>
<meta property="og:image:height" content="4134"/>
</code></pre>
<p>But this in facebook's Open Graph debugger
(what scrapper sees).</p>
<pre><code><meta property="og:image" content="">
<meta property="og:image:width" content="">
<meta property="og:image:height" content="">
</code></pre>
<p>Thank You</p>
| [
{
"answer_id": 242041,
"author": "Dmitry Gamolin",
"author_id": 86509,
"author_profile": "https://wordpress.stackexchange.com/users/86509",
"pm_score": 2,
"selected": false,
"text": "<p>The solution might depend on why exactly you want it to work that way on the post page. But probably t... | 2016/10/08 | [
"https://wordpress.stackexchange.com/questions/242033",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101510/"
] | Defining Open Graph meta tags like this for images.
```
global $post;
$postImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 1200, 9999 ), false );
<meta property="og:image" content="<?php echo $postImg[0]; ?>"/>
<meta property="og:image:width" content="<?php echo $postImg[1]; ?>"/>
<meta property="og:image:height" content="<?php echo $postImg[2]; ?>"/>
```
I get this in my website source:
```
<meta property="og:image" content="http://elpace.co/event-image.jpg"/>
<meta property="og:image:width" content="2953"/>
<meta property="og:image:height" content="4134"/>
```
But this in facebook's Open Graph debugger
(what scrapper sees).
```
<meta property="og:image" content="">
<meta property="og:image:width" content="">
<meta property="og:image:height" content="">
```
Thank You | The solution might depend on why exactly you want it to work that way on the post page. But probably the best way would be to do this on the client side.
**Method with maximum height**
Let's say your post template has its content like this:
```
<div id="content"><?php the_content(); ?></div>
```
You need to add a button after this div, so it would become:
```
<div id="content"><?php the_content(); ?></div>
<button class="show-more">Show more</button>
```
Then you add CSS to only show the content up to specific height, in your style.css add:
```
#content { max-height: 100px; overflow: hidden; }
.show-more { margin-top: 15px; }
```
Finally, add a script that would show the full height of content and remove "show-more" button after it's clicked:
```
jQuery(document).ready(function($) {
$('.show-more').click(function() {
$('#content').css('max-height', 'none');
$(this).remove();
});
});
```
It's just a basic setup, so feel free to adjust the styles and the script as you'd like.
Here's a link to the fiddle where you can try it out: <https://jsfiddle.net/psxtur2L/>
**Method with replacing the content**
If you want to specifically show the excerpt as a short version, you can do it this way.
In your template, you add both the excerpt and the content, and a button, like this:
```
<div id="excerpt"><?php the_excerpt(); ?></div>
<div id="content"><?php the_content(); ?></div>
<button class="show-more">Show more</button>
```
In CSS you just hide the content by default:
```
#content { display: none; }
.show-more { margin-top: 15px; }
```
And then you hide the excerpt and show the content when the user clicks on the button:
```
jQuery(document).ready(function($) {
$('.show-more').click(function() {
$('#excerpt').hide();
$('#content').show();
$(this).remove();
});
});
```
Here's a fiddle for that: <https://jsfiddle.net/o7z2Lsks/>
Note that the user can access full content without clicking the button if he's using browser's debugger tool, but I assume that it is not important. If you would need to make checks whether the user is logged in and so on, you should rather use AJAX, so it would require more additions to the code. |
242,068 | <p>Is it possible to limit maximum menu depth in admin panel <code>/nav-menus.php</code>?</p>
<p>I need this because my theme won't support more than two levels of menu, so there is no point in allowing a user to make deeper menus.</p>
| [
{
"answer_id": 242078,
"author": "jmarceli",
"author_id": 81890,
"author_profile": "https://wordpress.stackexchange.com/users/81890",
"pm_score": 4,
"selected": false,
"text": "<p>The solution that I came up with:</p>\n\n<pre><code>/**\n * Limit max menu depth in admin panel to 2\n */\nf... | 2016/10/09 | [
"https://wordpress.stackexchange.com/questions/242068",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81890/"
] | Is it possible to limit maximum menu depth in admin panel `/nav-menus.php`?
I need this because my theme won't support more than two levels of menu, so there is no point in allowing a user to make deeper menus. | Follow up on @jmarceli's and @squarecandy's great answers. Here is a solution that allows for:
* Easier scaling (set an object in the php action)
* Updates to the correct menu depth when the location checkboxes are changed
```
/**
* Limit max menu depth in admin panel
*/
function limit_admin_menu_depth($hook)
{
if ($hook != 'nav-menus.php') return;
wp_register_script('limit-admin-menu-depth', get_stylesheet_directory_uri() . '/js/admin/limit-menu-depth.js', array(), '1.0.0', true);
wp_localize_script(
'limit-admin-menu-depth',
'myMenuDepths',
array(
'primary' => 1, // <-- Set your menu location and max depth here
'footer' => 0 // <-- Add as many as you like
)
);
wp_enqueue_script('limit-admin-menu-depth');
}
add_action( 'admin_enqueue_scripts', 'limit_admin_menu_depth' );
```
js
```
/**
* Limit max menu depth in admin panel
* Expects wp_localize_script to have set an object of menu locations
* in the shape of { location: maxDepth, location2: maxDepth2 }
* e.g var menu-depths = {"primary":"1","footer":"0"};
*/
(function ($) {
// Get initial maximum menu depth, so that we may restore to it later.
var initialMaxDepth = wpNavMenu.options.globalMaxDepth;
function setMaxDepth() {
// Loop through each of the menu locations
$.each(myMenuDepths, function (location, maxDepth) {
if (
$('#locations-' + location).prop('checked') &&
maxDepth < wpNavMenu.options.globalMaxDepth
) {
// If this menu location is checked
// and if the max depth for this location is less than the current globalMaxDepth
// Then set globalMaxDepth to the max depth for this location
wpNavMenu.options.globalMaxDepth = maxDepth;
}
});
}
// Run the function once on document ready
setMaxDepth();
// Re-run the function if the menu location checkboxes are changed
$('.menu-theme-locations input').on('change', function () {
wpNavMenu.options.globalMaxDepth = initialMaxDepth;
setMaxDepth();
});
})(jQuery);
``` |
242,141 | <p>I used these code in my theme's <code>functions.php</code> to logout a particular user with user <strong><em>id 233</em></strong> from everywhere in WordPress and it worked. But I want to logout all the users on my site from everywhere.</p>
<pre><code>// worked for user with user id 233
$sessions = WP_Session_Tokens::get_instance($user_id=233);
$sessions->destroy_all();
</code></pre>
<p>I used this for all the users but did not work</p>
<pre><code>// The code below did not work for all users
$sessions= WP_Session_Tokens::get_instance($user_id=users - get_current_user_id());
$sessions->destroy_all();
</code></pre>
| [
{
"answer_id": 242142,
"author": "Dmitry Gamolin",
"author_id": 86509,
"author_profile": "https://wordpress.stackexchange.com/users/86509",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>$sessions = WP_Session_Tokens::get_instance( get_current_user_id() );\n$se... | 2016/10/10 | [
"https://wordpress.stackexchange.com/questions/242141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104549/"
] | I used these code in my theme's `functions.php` to logout a particular user with user ***id 233*** from everywhere in WordPress and it worked. But I want to logout all the users on my site from everywhere.
```
// worked for user with user id 233
$sessions = WP_Session_Tokens::get_instance($user_id=233);
$sessions->destroy_all();
```
I used this for all the users but did not work
```
// The code below did not work for all users
$sessions= WP_Session_Tokens::get_instance($user_id=users - get_current_user_id());
$sessions->destroy_all();
``` | Firstly if you'd just like everyone to have to log in again you can void all of your cookies at once by changing your cookie hashes in your wordpress config file.
The lines that look like this:
```
define('AUTH_KEY', ':u(rb=Ys8*2x^rVisqX(9=10a*.euPdYEBo6p_ZBB2CDG|rv~Ju)sh+6@=L6p_:l');
define('SECURE_AUTH_KEY', '-`<iUz(4olJ`m&}1kA*{v&OX;Kq?W+!7ppF!tWb}cM<R=d<s=(oL]]04%AA@juZB');
define('LOGGED_IN_KEY', '$KA]84n3ZT}v6m7c:r+!6l}R||)<_$3GxJ%F6Y?MopvxydJ@PRcmZ0-Hyq(EuEZt');
define('NONCE_KEY', 'qT=]!^BARWEMUD(G6]#~q$PAv-N[#^uE991w7HJNN<*mXavH)@o0TkFKVFUNIDN#');
define('AUTH_SALT', 'c W#7TWk{L1+n0A+^:|FHYL#-;*#<8U :v%>~S!45$bbYM09Iwe;@=uk^xeJd_D`');
define('SECURE_AUTH_SALT', 'h3&dgYcQE0uTaxd5bX$&1wC]yKP^?W8#q#>IJ*)ggf_Rc+6f+oZa?#JVS[HmO?=O');
define('LOGGED_IN_SALT', '_L:n)>u>-31YK_ftTp_ZV>-y)qG)so|sOoWgYC9Ju!q_!%f.60g?I~]~lNZ6&o!0');
define('NONCE_SALT', '.KI_*}ONxh/uwZv~!qYqOW+OL;?qvgaEqayN8>i+B.WY$e}+M9.Xqxwlf+?v 1k=');
```
[This website](https://api.wordpress.org/secret-key/1.1/salt/) is a good tool for generating new secure keys to put in.
If you want to change the amount of time you can be logged in for you can use the below code in your themes `functions.php`:
```
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for' );
function keep_me_logged_in_for( $expirein ) {
return 86400; // time in seconds
}
``` |
242,170 | <p>I've looked at many WP development forums but I couldn't find any answer, unfortunately. If anybody can help me. Actually, I am not sure if that kind of problem can be solved with WordPress at all. </p>
<p>My problem is the following.</p>
<p>When creating a new user in WordPress admin, the admin is offered a screen like the photo I am attaching here.</p>
<p><a href="https://i.stack.imgur.com/j66uE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j66uE.png" alt="Adding a new user to WordPress Admin"></a></p>
<p>After the user has already been created, the admin is redirected back to the page containing all the users.</p>
<p>My problem is, how can I add some additional tests on the user that is being created. The question is related to development of a WP plugin, php, which action hooks I can use for that purpose. I want to stay on the same page (my_domain/wp-admin/user-new.php) but after I push the 'Add New User' button, I want only the content of that page to change, the rest (I mean the admin menu on the left side to stay there) but only the content (the right area) to change (here I want to make my additional tests on that user), and showing a 'Next' button at bottom.</p>
<p>I've been thinking about adding some parameters in the URL but I do not know how to insert my code so that my problem can be solved.
I may be wrong, that was the only thing that came into my mind.
Is that possible to be implemented in WP at all? I know how to develop the pages, the only thing I cannot do is how to switch the right content but still stay on the same (add-new user-page). All the lectures I've been watching on WP plugin development, theme development, solve some not so complex problems - creating new content types, adding new menu/submenu items, and the pages related to these items, ajax and so on.</p>
<p>Could you please give me some directions(code snippets, hooks I can use), some code examples maybe, I say again, if that problem can be solved in WP at all.</p>
<p>Thank you in advance.
Best regards, George! </p>
| [
{
"answer_id": 242142,
"author": "Dmitry Gamolin",
"author_id": 86509,
"author_profile": "https://wordpress.stackexchange.com/users/86509",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>$sessions = WP_Session_Tokens::get_instance( get_current_user_id() );\n$se... | 2016/10/10 | [
"https://wordpress.stackexchange.com/questions/242170",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104598/"
] | I've looked at many WP development forums but I couldn't find any answer, unfortunately. If anybody can help me. Actually, I am not sure if that kind of problem can be solved with WordPress at all.
My problem is the following.
When creating a new user in WordPress admin, the admin is offered a screen like the photo I am attaching here.
[](https://i.stack.imgur.com/j66uE.png)
After the user has already been created, the admin is redirected back to the page containing all the users.
My problem is, how can I add some additional tests on the user that is being created. The question is related to development of a WP plugin, php, which action hooks I can use for that purpose. I want to stay on the same page (my\_domain/wp-admin/user-new.php) but after I push the 'Add New User' button, I want only the content of that page to change, the rest (I mean the admin menu on the left side to stay there) but only the content (the right area) to change (here I want to make my additional tests on that user), and showing a 'Next' button at bottom.
I've been thinking about adding some parameters in the URL but I do not know how to insert my code so that my problem can be solved.
I may be wrong, that was the only thing that came into my mind.
Is that possible to be implemented in WP at all? I know how to develop the pages, the only thing I cannot do is how to switch the right content but still stay on the same (add-new user-page). All the lectures I've been watching on WP plugin development, theme development, solve some not so complex problems - creating new content types, adding new menu/submenu items, and the pages related to these items, ajax and so on.
Could you please give me some directions(code snippets, hooks I can use), some code examples maybe, I say again, if that problem can be solved in WP at all.
Thank you in advance.
Best regards, George! | Firstly if you'd just like everyone to have to log in again you can void all of your cookies at once by changing your cookie hashes in your wordpress config file.
The lines that look like this:
```
define('AUTH_KEY', ':u(rb=Ys8*2x^rVisqX(9=10a*.euPdYEBo6p_ZBB2CDG|rv~Ju)sh+6@=L6p_:l');
define('SECURE_AUTH_KEY', '-`<iUz(4olJ`m&}1kA*{v&OX;Kq?W+!7ppF!tWb}cM<R=d<s=(oL]]04%AA@juZB');
define('LOGGED_IN_KEY', '$KA]84n3ZT}v6m7c:r+!6l}R||)<_$3GxJ%F6Y?MopvxydJ@PRcmZ0-Hyq(EuEZt');
define('NONCE_KEY', 'qT=]!^BARWEMUD(G6]#~q$PAv-N[#^uE991w7HJNN<*mXavH)@o0TkFKVFUNIDN#');
define('AUTH_SALT', 'c W#7TWk{L1+n0A+^:|FHYL#-;*#<8U :v%>~S!45$bbYM09Iwe;@=uk^xeJd_D`');
define('SECURE_AUTH_SALT', 'h3&dgYcQE0uTaxd5bX$&1wC]yKP^?W8#q#>IJ*)ggf_Rc+6f+oZa?#JVS[HmO?=O');
define('LOGGED_IN_SALT', '_L:n)>u>-31YK_ftTp_ZV>-y)qG)so|sOoWgYC9Ju!q_!%f.60g?I~]~lNZ6&o!0');
define('NONCE_SALT', '.KI_*}ONxh/uwZv~!qYqOW+OL;?qvgaEqayN8>i+B.WY$e}+M9.Xqxwlf+?v 1k=');
```
[This website](https://api.wordpress.org/secret-key/1.1/salt/) is a good tool for generating new secure keys to put in.
If you want to change the amount of time you can be logged in for you can use the below code in your themes `functions.php`:
```
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for' );
function keep_me_logged_in_for( $expirein ) {
return 86400; // time in seconds
}
``` |
242,196 | <p>I am using per_page instead of the filter since it is no more available. but the problem is per_page value can be between 1 and 100. what if I want to pull records and it is more that 100. per_page will not return records if the count is more than 100.
in the below API I want to pull the images which are more than 100 in count.</p>
<p><a href="http://domain_name/wp-json/wp/v2/media/?per_page=100" rel="nofollow">http://domain_name/wp-json/wp/v2/media/?per_page=100</a></p>
<p>Appreciate your help</p>
<p>Srikant</p>
| [
{
"answer_id": 242205,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": -1,
"selected": false,
"text": "<p>Limits are there for a reason, before trying to overcome them you should ask yourself, \"why is there a ... | 2016/10/10 | [
"https://wordpress.stackexchange.com/questions/242196",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104400/"
] | I am using per\_page instead of the filter since it is no more available. but the problem is per\_page value can be between 1 and 100. what if I want to pull records and it is more that 100. per\_page will not return records if the count is more than 100.
in the below API I want to pull the images which are more than 100 in count.
<http://domain_name/wp-json/wp/v2/media/?per_page=100>
Appreciate your help
Srikant | Add a page number query to your request URL, and continue querying next page numbers until you get an empty result:
```
<your_wordpress_install_base_url>/wp-json/wp/v2/media/?per_page=100&page=2
```
Mark's suggestion to consider requesting less than 100 per page may be a good one. So for example you may want to do your query this way:
```
<your_wordpress_install_base_url>/wp-json/wp/v2/media/?per_page=25&page=3
```
Note also that (for me at least) these query URLs work if constructed as just ~/`media?per_page=3` (instead of ~/`media/?per_page=3`). I don't know whether one or the other is preferred.
Thanks, incidentally, for the `/media/?per_page=100` part of your example. I'd been stumped about getting empty results when querying just `/media` :) |
242,197 | <p>I've noticed that WordPress seems a little loosey goosey when it comes to quoting styles in the HTML it generates. Sometimes WordPress uses single quotes, other times it uses double quotes</p>
<pre><code><link rel='next' title='An Example' href='http://example.com/foo/' />
<link rel="canonical" href="http://example.com/foo/" />
</code></pre>
<p>I know that single quote are, as of HTML5, technically "OK", but I'm weird and particular about how my HTML looks. Is there a way to tell WordPress to always use double quotes? If not, is there a plugin that might do this for me, or can someone point me to the appropriate do_action/apply_filter points so I can investigate this one my own?</p>
| [
{
"answer_id": 242200,
"author": "db306",
"author_id": 90056,
"author_profile": "https://wordpress.stackexchange.com/users/90056",
"pm_score": 3,
"selected": true,
"text": "<p>First of all, either quotes are as good as each other. See <a href=\"https://stackoverflow.com/questions/2373074... | 2016/10/10 | [
"https://wordpress.stackexchange.com/questions/242197",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33566/"
] | I've noticed that WordPress seems a little loosey goosey when it comes to quoting styles in the HTML it generates. Sometimes WordPress uses single quotes, other times it uses double quotes
```
<link rel='next' title='An Example' href='http://example.com/foo/' />
<link rel="canonical" href="http://example.com/foo/" />
```
I know that single quote are, as of HTML5, technically "OK", but I'm weird and particular about how my HTML looks. Is there a way to tell WordPress to always use double quotes? If not, is there a plugin that might do this for me, or can someone point me to the appropriate do\_action/apply\_filter points so I can investigate this one my own? | First of all, either quotes are as good as each other. See [this question](https://stackoverflow.com/questions/2373074/single-vs-double-quotes-vs)
There is no way you can do this with a plugin, action or filter. To achieve this you will have to do this manually by using the "find and replace" option on your IDE. I do not advise you to do this as:
* You may end up breaking your WordPress core
* You will lose all changes next time you will update your WordPress
* You will have to go case by case as situations like these may appear:
`echo <link rel='" . echo $bar . "' href="' . echo $foo . '";`
in which case you will have to invert double quotes for single quotes and vice versa.
This will be very time consuming for what you will get in return.
As a matter of fact WordPress coding standards accept both quotation styles:
See [WordPress HTML Coding Standards on Quotes](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/html/#quotes) |
242,206 | <p>I am trying to show a Formidable Pro Form from a WordPress site to the other.
I followed the developer's API and the REST API, but faced a CORS problem.</p>
<p>Then I found a suggestion on a forum thread suggesting to add this line of code the <code>functions.php</code> of the site where the original form is:</p>
<p><code>header("Access-Control-Allow-Origin: *");</code></p>
<p>I tried this code and it worked perfectly fine.</p>
<p>My question is: does this code opens security risks or other vulnerabilities?</p>
<p>The solution seems too simple for a problem that faces many people.</p>
<p>Your input is highly appreciated.</p>
| [
{
"answer_id": 242321,
"author": "Jesús Franco",
"author_id": 16301,
"author_profile": "https://wordpress.stackexchange.com/users/16301",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, you open your site to being requested via AJAX to any other script in the whole web.</p>\n\n<p>It wo... | 2016/10/10 | [
"https://wordpress.stackexchange.com/questions/242206",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91570/"
] | I am trying to show a Formidable Pro Form from a WordPress site to the other.
I followed the developer's API and the REST API, but faced a CORS problem.
Then I found a suggestion on a forum thread suggesting to add this line of code the `functions.php` of the site where the original form is:
`header("Access-Control-Allow-Origin: *");`
I tried this code and it worked perfectly fine.
My question is: does this code opens security risks or other vulnerabilities?
The solution seems too simple for a problem that faces many people.
Your input is highly appreciated. | Yes, you open your site to being requested via AJAX to any other script in the whole web.
It would be better if you limit the origin to **one** specific remote domain from which you are consuming the API, like [this example](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin):
```
header("Access-Control-Allow-Origin: http://mozilla.com");
```
However as the mozilla documentation states, a client can fork the origin, nevertheless limiting the sites a casual user can connect is a deterrent for some attacks.
Even better, you can limit your request to [only the methods you really need to allow](https://es.stackoverflow.com/a/20431/2162), the gist is this snippet, and it works for several domains, **if you have the `$_SERVER['HTTP_ORIGIN']` variable populated**:
```
add_action('rest_api_init', function() {
/* unhook default function */
remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
/* then add your own filter */
add_filter('rest_pre_serve_request', function( $value ) {
$origin = get_http_origin();
$my_sites = array( 'http://site1.org/', 'http://site2.net', );
if ( in_array( $origin, $my_sites ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
} else {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ) );
}
header( 'Access-Control-Allow-Methods: GET' );
return $value;
});
}, 15);
```
As you can see, this snippet uses the function [get\_http\_origin](https://developer.wordpress.org/reference/functions/get_http_origin/) provided by WordPress, but it will return null or empty, if the key `HTTP_ORIGIN` is not populated in the `$_SERVER` array, therefore it's not available to the PHP script, maybe because it is blocked by the cloudflare proxy you are using. I'd check quickly, with a script with the `<?php phpinfo(); ?>`, if you have this variable populated.
Maybe the origin site it's populated in another header by cloudflare, and you could use it in a function hooked to the `http_origin` filter. If you are lost to this point, edit your original question posting the contents of the \_SERVER variable, except your filesystem paths or passwords.
I'd be glad to help. |
242,256 | <p>I am attempting to create customizable theme for my clients. The goal is to enable them to modify certain styles inside the theme customizer.</p>
<p>I didn't want to insert customizer's variables inside html code, but instead created a <code>css-php</code> file. Everything works well except that live preview of the changes doesn't reflect them in real time. Instead I have to refresh the page each time after single change. It doesn't bother me personally but it annoys my clients.</p>
<p>What are your thoughts on this?</p>
<p>Thats what I have in my <code>functions.php</code>:</p>
<pre><code>function im_customize_register( $wp_customize ) {
$colors = array();
$colors[] = array(
'slug'=>'im_header_bcolor',
'default' => '#556d80',
'label' => __('Header Background Color', 'impressive')
);
$colors[] = array(
'slug'=>'im_nav_bar_bcolor',
'default' => '#434044',
'label' => __('Navigation Bar Background Color', 'impressive')
);
foreach( $colors as $color ) {
// SETTINGS
$wp_customize->add_setting(
$color['slug'], array(
'default' => $color['default'],
'type' => 'theme_mod',
'capability' =>
'edit_theme_options'
)
);
// CONTROLS
$wp_customize->add_control(
new WP_Customize_Color_Control(
$wp_customize,
$color['slug'],
array('label' => $color['label'],
'section' => 'colors',
'settings' => $color['slug'])
)
);
}
}
add_action( 'customize_register', 'im_customize_register' );
function im_theme_styles() {
wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'im_theme_styles' );
$custom_css= '
.im_header { background-color: ' . get_theme_mod('im_header_bcolor') . '; }
.im_nav_bar { background-color: ' . get_theme_mod('im_nav_bar_bcolor') . '; }
';
wp_add_inline_style ('main-style', $custom_css);
</code></pre>
<p>And my <code>css.php</code>:</p>
<pre><code><?php header("Content-type: text/css; charset: UTF-8"); ?>
<?php
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$im_header_bcolor = get_theme_mod('im_header_bcolor');
$im_nav_bar_bcolor = get_theme_mod('im_nav_bar_bcolor');
?>
.im_header { background-color: <?php echo $im_header_bcolor; ?>; }
.im_nav_bar { background-color: <?php echo $im_nav_bar_bcolor; ?>; }
</code></pre>
| [
{
"answer_id": 242326,
"author": "Miles Elliott",
"author_id": 104700,
"author_profile": "https://wordpress.stackexchange.com/users/104700",
"pm_score": 1,
"selected": false,
"text": "<p>You will want to put the code in the child theme, otherwise an update to the parent theme will erase ... | 2016/10/11 | [
"https://wordpress.stackexchange.com/questions/242256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103317/"
] | I am attempting to create customizable theme for my clients. The goal is to enable them to modify certain styles inside the theme customizer.
I didn't want to insert customizer's variables inside html code, but instead created a `css-php` file. Everything works well except that live preview of the changes doesn't reflect them in real time. Instead I have to refresh the page each time after single change. It doesn't bother me personally but it annoys my clients.
What are your thoughts on this?
Thats what I have in my `functions.php`:
```
function im_customize_register( $wp_customize ) {
$colors = array();
$colors[] = array(
'slug'=>'im_header_bcolor',
'default' => '#556d80',
'label' => __('Header Background Color', 'impressive')
);
$colors[] = array(
'slug'=>'im_nav_bar_bcolor',
'default' => '#434044',
'label' => __('Navigation Bar Background Color', 'impressive')
);
foreach( $colors as $color ) {
// SETTINGS
$wp_customize->add_setting(
$color['slug'], array(
'default' => $color['default'],
'type' => 'theme_mod',
'capability' =>
'edit_theme_options'
)
);
// CONTROLS
$wp_customize->add_control(
new WP_Customize_Color_Control(
$wp_customize,
$color['slug'],
array('label' => $color['label'],
'section' => 'colors',
'settings' => $color['slug'])
)
);
}
}
add_action( 'customize_register', 'im_customize_register' );
function im_theme_styles() {
wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'im_theme_styles' );
$custom_css= '
.im_header { background-color: ' . get_theme_mod('im_header_bcolor') . '; }
.im_nav_bar { background-color: ' . get_theme_mod('im_nav_bar_bcolor') . '; }
';
wp_add_inline_style ('main-style', $custom_css);
```
And my `css.php`:
```
<?php header("Content-type: text/css; charset: UTF-8"); ?>
<?php
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$im_header_bcolor = get_theme_mod('im_header_bcolor');
$im_nav_bar_bcolor = get_theme_mod('im_nav_bar_bcolor');
?>
.im_header { background-color: <?php echo $im_header_bcolor; ?>; }
.im_nav_bar { background-color: <?php echo $im_nav_bar_bcolor; ?>; }
``` | You will want to put the code in the child theme, otherwise an update to the parent theme will erase it.
You want the loader to be a part of the page as the document is first loaded by the browser, then use javascript to detect when the images are finished loading and remove the loader.
Check out these resources that have more information specifically on the structure of the HTML and javascript
<https://css-tricks.com/snippets/jquery/display-loading-graphic-until-page-fully-loaded/>
<https://stackoverflow.com/questions/11072759/display-a-loading-bar-before-the-entire-page-is-loaded>
<http://smallenvelop.com/display-loading-icon-page-loads-completely/> |
242,278 | <p>I have a desktop app and I use <strong>$.getJSON</strong> to get data from my wordpress site using the plugin the <strong>WP REST API</strong>. This works fine and so I assume I can also make an Ajax call to a function in the functions.php? How do I do this? None of the examples I have seen supply the ajaxURL. How do I find out what this is?</p>
<p>I have the following code:</p>
<p><strong>Functions.php (in wordpress site on server)</strong></p>
<pre><code>//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {
$folderPath = $_POST['path'] ;
$files = array_diff(scandir($path), array('.', '..'));
print_r($files);
return $files;
die();
}
add_action('wp_ajax_my_action', 'folder_contents');
</code></pre>
<p><strong>app.js (run using node webkit locally from machine)</strong></p>
<pre><code>//ajax call
var data = {
action: 'path',
path: datafolder;
};
var ajaxurl = baseurl + ''; //WHAT IS THIS?!?!
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
console.log(response);
});
</code></pre>
<p><strong>-------------------EDIT----------------------</strong></p>
<p>After the answer below I have tried the below code based on the advice but I get </p>
<blockquote>
<p>"index.html:324 Uncaught ReferenceError: ajax_params is not defined"</p>
</blockquote>
<p><strong>Functions.php</strong> </p>
<pre><code>//add code to use ajax
function add_ajax_script() {
wp_localize_script( 'ajax-js', 'ajax_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {
$folderPath = $_POST['path'] ;
$files = array_diff(scandir($path), array('.', '..'));
wp_send_json($files);
die();
}
add_action('wp_ajax_folder_contents', 'folder_contents');
add_action('wp_ajax_nopriv_folder_contents', 'folder_contents');
add_action( 'wp_enqueue_scripts', 'add_ajax_script' );
</code></pre>
<p><strong>App.js</strong></p>
<pre><code>//ajax call
var data = {action: 'powerpoint_folder_contents',path: datafolder};
var ajaxurl = ajax_params.ajax_url;
console.log(ajaxurl);
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
console.log(response);
});
</code></pre>
<p>If I remove the <strong>add_ajax_script()</strong> function and simply use the below it returns 0.</p>
<blockquote>
<p>var ajaxurl = baseurl + 'wp-admin/admin-ajax.php';</p>
</blockquote>
<p>Please help...</p>
| [
{
"answer_id": 242279,
"author": "Tex0gen",
"author_id": 97070,
"author_profile": "https://wordpress.stackexchange.com/users/97070",
"pm_score": 4,
"selected": true,
"text": "<pre><code>//ajax call \nvar data = {\n action: 'folder_contents',\n path: datafolder\n};\nvar ajaxurl = ba... | 2016/10/11 | [
"https://wordpress.stackexchange.com/questions/242278",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70019/"
] | I have a desktop app and I use **$.getJSON** to get data from my wordpress site using the plugin the **WP REST API**. This works fine and so I assume I can also make an Ajax call to a function in the functions.php? How do I do this? None of the examples I have seen supply the ajaxURL. How do I find out what this is?
I have the following code:
**Functions.php (in wordpress site on server)**
```
//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {
$folderPath = $_POST['path'] ;
$files = array_diff(scandir($path), array('.', '..'));
print_r($files);
return $files;
die();
}
add_action('wp_ajax_my_action', 'folder_contents');
```
**app.js (run using node webkit locally from machine)**
```
//ajax call
var data = {
action: 'path',
path: datafolder;
};
var ajaxurl = baseurl + ''; //WHAT IS THIS?!?!
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
console.log(response);
});
```
**-------------------EDIT----------------------**
After the answer below I have tried the below code based on the advice but I get
>
> "index.html:324 Uncaught ReferenceError: ajax\_params is not defined"
>
>
>
**Functions.php**
```
//add code to use ajax
function add_ajax_script() {
wp_localize_script( 'ajax-js', 'ajax_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {
$folderPath = $_POST['path'] ;
$files = array_diff(scandir($path), array('.', '..'));
wp_send_json($files);
die();
}
add_action('wp_ajax_folder_contents', 'folder_contents');
add_action('wp_ajax_nopriv_folder_contents', 'folder_contents');
add_action( 'wp_enqueue_scripts', 'add_ajax_script' );
```
**App.js**
```
//ajax call
var data = {action: 'powerpoint_folder_contents',path: datafolder};
var ajaxurl = ajax_params.ajax_url;
console.log(ajaxurl);
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
console.log(response);
});
```
If I remove the **add\_ajax\_script()** function and simply use the below it returns 0.
>
> var ajaxurl = baseurl + 'wp-admin/admin-ajax.php';
>
>
>
Please help... | ```
//ajax call
var data = {
action: 'folder_contents',
path: datafolder
};
var ajaxurl = baseurl + ''; //WHAT IS THIS?!?!
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
console.log(response);
});
```
And your PHP in functions.php
```
//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally
function folder_contents() {
$folderPath = $_POST['path'] ;
$files = array_diff(scandir($path), array('.', '..'));
print_r($files);
return $files;
die();
}
add_action('wp_ajax_folder_contents', 'folder_contents');
add_action('wp_ajax_nopriv_folder_contents', 'folder_contents');
```
The above add your function as an ajax action. You then call the function name in your AJAX.
See <https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)> |