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 configuration files. In the case of Apache, rewrites are most often implemented using the <a href=\"http://httpd.apache.org/docs/current/mod/mod_rewrite.html\" rel=\"nofollow\"><code>mod_rewrite</code></a> module's directives in the WordPress installation's directory-level <code>.htaccess</code> configuration file - however, a faulty rewrite rule could also be present in higher-level configuration files (directory, vhost, primary configuration, etc.).</p>\n\n<p>By default, WordPress routes every request for anything except existing files and directories to <code>index.php</code> using a configuration similar to the following:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n\n<p>There are two modifications that will cause these directives to drop the querystring in the process of rewriting the request:</p>\n\n<ul>\n<li><p>The <a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsd\" rel=\"nofollow\">discard querystring flag</a>. This is added to the square brackets at the end of a <code>RewriteRule</code> directive as either <code>QSD</code> or <code>qsdiscard</code>. If this flag is present for <em>either</em> of the <code>RewriteRule</code> directives in the configuration above, the querystring will be discarded for virtually every request handled by WordPress. For example:</p>\n\n<pre><code>RewriteRule ^index\\.php$ - [L,QSD]\n</code></pre></li>\n<li><p>Any use of a <code>?</code> in a <code>RewriteRule</code> directive's substitution string (without the <a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa\" rel=\"nofollow\">append querystring flag</a>). Specifying <em>any</em> querystring (even a single <code>?</code> without any subsequent key/value pairs) in the substitution will result in the rewrite completely replacing the original querystring. For example:</p>\n\n<pre><code>RewriteRule . /index.php? [L]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>RewriteRule . /index.php?foo=bar [L]\n</code></pre>\n\n<p>If it is desireable to append a custom GET variable to every rewrite, the append querystring flag can be specified in the brackets as <code>QSA</code> or <code>qsappend</code> in order to merge the querystring in the substitution with the original querystring instead of completely overwriting it:</p>\n\n<pre><code>RewriteRule . /index.php?foo=bar [L,QSA]\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 408603,
"author": "Wilhelm",
"author_id": 223979,
"author_profile": "https://wordpress.stackexchange.com/users/223979",
"pm_score": -1,
"selected": false,
"text": "<p>An easy way to get the query string is to do the following:</p>\n<pre><code>$query_string = $_SERVER['QUERY_STRING'];\n</code></pre>\n"
}
] |
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 configuration files. In the case of Apache, rewrites are most often implemented using the <a href=\"http://httpd.apache.org/docs/current/mod/mod_rewrite.html\" rel=\"nofollow\"><code>mod_rewrite</code></a> module's directives in the WordPress installation's directory-level <code>.htaccess</code> configuration file - however, a faulty rewrite rule could also be present in higher-level configuration files (directory, vhost, primary configuration, etc.).</p>\n\n<p>By default, WordPress routes every request for anything except existing files and directories to <code>index.php</code> using a configuration similar to the following:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n\n<p>There are two modifications that will cause these directives to drop the querystring in the process of rewriting the request:</p>\n\n<ul>\n<li><p>The <a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsd\" rel=\"nofollow\">discard querystring flag</a>. This is added to the square brackets at the end of a <code>RewriteRule</code> directive as either <code>QSD</code> or <code>qsdiscard</code>. If this flag is present for <em>either</em> of the <code>RewriteRule</code> directives in the configuration above, the querystring will be discarded for virtually every request handled by WordPress. For example:</p>\n\n<pre><code>RewriteRule ^index\\.php$ - [L,QSD]\n</code></pre></li>\n<li><p>Any use of a <code>?</code> in a <code>RewriteRule</code> directive's substitution string (without the <a href=\"http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa\" rel=\"nofollow\">append querystring flag</a>). Specifying <em>any</em> querystring (even a single <code>?</code> without any subsequent key/value pairs) in the substitution will result in the rewrite completely replacing the original querystring. For example:</p>\n\n<pre><code>RewriteRule . /index.php? [L]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>RewriteRule . /index.php?foo=bar [L]\n</code></pre>\n\n<p>If it is desireable to append a custom GET variable to every rewrite, the append querystring flag can be specified in the brackets as <code>QSA</code> or <code>qsappend</code> in order to merge the querystring in the substitution with the original querystring instead of completely overwriting it:</p>\n\n<pre><code>RewriteRule . /index.php?foo=bar [L,QSA]\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 408603,
"author": "Wilhelm",
"author_id": 223979,
"author_profile": "https://wordpress.stackexchange.com/users/223979",
"pm_score": -1,
"selected": false,
"text": "<p>An easy way to get the query string is to do the following:</p>\n<pre><code>$query_string = $_SERVER['QUERY_STRING'];\n</code></pre>\n"
}
] |
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.org/The_Loop\" rel=\"nofollow\">wordpress loop</a>, therefore, they will not work.</p>\n\n<p>I suggest you try something like :</p>\n\n<pre><code>$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);\n$query = new WP_Query($args);\nwhile($query->have_posts()){\n $query->the_post();\n // the_excerpt() will now work as expected\n}\n</code></pre>\n"
},
{
"answer_id": 240723,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 0,
"selected": false,
"text": "<p>Your <code>get_posts()</code> function may be causing the error that you interpret now.</p>\n\n<p>You can follow up the standard loop structure so that it will be very easy for you to print the <code>title()</code>, content and the excerpt conditions.</p>\n\n<pre><code><?php\n$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);\n $random_posts = new WP_Query($args);\n if($random_posts->have_posts()) : \n while($random_posts->have_posts()) : \n $random_posts->the_post();\n?>\n <h1><?php the_title() ?></h1>\n <div class='post-content'><?php the_content() ?></div>\n <div class='excerpt'><?php the_excerpt(); ?></div> \n<?php\n endwhile;\n else: \n?>\n Oops, there are no posts.\n<?php\n endif;\n?>\n</code></pre>\n"
}
] |
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.org/The_Loop\" rel=\"nofollow\">wordpress loop</a>, therefore, they will not work.</p>\n\n<p>I suggest you try something like :</p>\n\n<pre><code>$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);\n$query = new WP_Query($args);\nwhile($query->have_posts()){\n $query->the_post();\n // the_excerpt() will now work as expected\n}\n</code></pre>\n"
},
{
"answer_id": 240723,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 0,
"selected": false,
"text": "<p>Your <code>get_posts()</code> function may be causing the error that you interpret now.</p>\n\n<p>You can follow up the standard loop structure so that it will be very easy for you to print the <code>title()</code>, content and the excerpt conditions.</p>\n\n<pre><code><?php\n$args = array( 'posts_per_page' => 12, 'orderby' => 'rand', 'post_status' => 'publish', 'offset' => 1);\n $random_posts = new WP_Query($args);\n if($random_posts->have_posts()) : \n while($random_posts->have_posts()) : \n $random_posts->the_post();\n?>\n <h1><?php the_title() ?></h1>\n <div class='post-content'><?php the_content() ?></div>\n <div class='excerpt'><?php the_excerpt(); ?></div> \n<?php\n endwhile;\n else: \n?>\n Oops, there are no posts.\n<?php\n endif;\n?>\n</code></pre>\n"
}
] |
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>. WordPress sites already have the <code>htaccess</code> in the main directory.</p>\n\n<p>Add an <code>.htpasswd</code> file at the same level as your root HTML folder. Example:</p>\n\n<pre><code>. \n├── public_html\n| └── wordpress\n| └── .htaccess\n└── .htpasswd\n</code></pre>\n\n<p>Use a tool like <a href=\"http://www.htaccesstools.com/htpasswd-generator/\" rel=\"nofollow noreferrer\">htpasswd generator</a> to generate a username/password pair. Then add this to your <code>.htpasswd</code> file.</p>\n\n<p>Find the path <code>$_SERVER[\"DOCUMENT_ROOT\"]</code> may provide some insight for you.</p>\n\n<p>Edit WP's <code>.htaccess</code>. After the <code>#END WORDPRESS#</code> add </p>\n\n<pre><code>AuthType Basic\nAuthName \"Restricted Area\"\nAuthUserFile /var/www/mysite/.htpasswd\nrequire valid-user\n</code></pre>\n\n<p>If you need more detailed instructions see <a href=\"https://www.zigpress.com/2014/09/22/password-protecting-an-entire-wordpress-site/\" rel=\"nofollow noreferrer\">this post</a>.</p>\n\n<p>However, this does not address your request about IP Validation. <a href=\"https://stackoverflow.com/questions/10419592/htaccess-htpasswd-bypass-if-at-a-certain-ip-address\">This question</a> on StackOverflow may address it. </p>\n\n<p>You would update the <code>.htaccess</code> file to read</p>\n\n<pre><code>AuthUserFile /var/www/mysite/.htpasswd\nAuthName \"Please Log In\"\nAuthType Basic\nrequire valid-user\nOrder allow,deny\nAllow from xxx.xxx.xxx.xxx\nsatisfy any\n</code></pre>\n"
},
{
"answer_id": 240820,
"author": "Muhammad Riyaz",
"author_id": 63027,
"author_profile": "https://wordpress.stackexchange.com/users/63027",
"pm_score": 0,
"selected": false,
"text": "<p>You can make <code>page-whitelist_content_page_slug.php</code> on your <em>theme</em> folder and add required rules.</p>\n\n<p><strong>OR</strong></p>\n\n<p>In <code>page.php</code> try this condition:</p>\n\n<pre><code><?php if (is_page(page_ID) ){ ?>\n //content for whitelist page \n<?php } \nelse if(is_user_logged_in()){ ?>\n //Content for all pages\n<?php } ?>\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<p>These plugins May help you:</p>\n\n<p>1) <strong><a href=\"https://wordpress.org/plugins/wp-private-content-plus/\" rel=\"nofollow\">WP Private Content Plus</a></strong></p>\n\n<p>Main features:</p>\n\n<ul>\n<li>Restrict entire posts/pages/custom post types</li>\n<li>Restrict content by User Groups</li>\n<li>Restrict content by User roles</li>\n<li>Restrict content for Guests or Members</li>\n<li>Restrict content by User role Levels</li>\n<li>Restrict content by WordPress capabilities</li>\n<li>Private Page for user profiles</li>\n<li>Restrict menu for members, guests, user roles, user groups</li>\n<li>Restrict widgets for members, guests, user roles</li>\n<li>Restrict post attachments and downloads to for members, guests</li>\n<li>Restrict content by multiple user meta keys</li>\n<li>Restrict content by multiple user meta values</li>\n<li>Restrict search content by user types</li>\n<li>Integration with User Profiles Made Easy</li>\n<li>Global Site Protection with Single Password</li>\n</ul>\n\n<p>2) <strong><a href=\"https://wordpress.org/plugins/redirect-to-login-if-not-logged-in/\" rel=\"nofollow\">Redirect to login if not logged in</a></strong></p>\n\n<p>Redirect user to login page if not logged in</p>\n\n<p>NB: <em>Both plugins are free</em></p>\n"
}
] |
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 <code>$wp_query</code>. Here is how.</p>\n\n<p>In your theme's <code>functions.php</code> you can add these functions to show 7 posts on first page, and 9 posts on any other page.</p>\n\n<p>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 <code>the_posts_pagination()</code> function it'll work as you expect.</p>\n\n<p><strong>The trick is to change the <code>max_num_pages</code> inside $wp_query global variable to our custom value and ignore WP calculation during the pagination links display only for first page.</strong></p>\n\n<pre><code>global $wp_query;\n\n// Needed for first page only\nif ( ! $wp_query->is_paged ) {\n $all_posts_except_fp = ( $wp_query->found_posts - 7 ); // Get us the found posts except those on first page\n $wp_query->max_num_pages = ceil( $all_posts_except_fp / 9 ) + 1; // + 1 the first page we have containing 7 posts\n}\n</code></pre>\n\n<p>And this is the code to put in functions.php to filter the query.</p>\n\n<pre><code>add_action('pre_get_posts', 'myprefix_query_offset', 1 );\nfunction myprefix_query_offset(&$query) {\n\n if ( ! $query->is_home() ) {\n return;\n }\n\n $fp = 7;\n $ppp = 9;\n\n if ( $query->is_paged ) {\n $offset = $fp + ( ($query->query_vars['paged'] - 2) * $ppp );\n $query->set('offset', $offset );\n $query->set('posts_per_page', $ppp );\n\n } else {\n $query->set('posts_per_page', $fp );\n }\n\n}\n\nadd_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );\nfunction myprefix_adjust_offset_pagination($found_posts, $query) {\n\n $fp = 7;\n $ppp = 9;\n\n if ( $query->is_home() ) {\n if ( $query->is_paged ) {\n return ( $found_posts + ( $ppp - $fp ) );\n }\n }\n return $found_posts;\n}\n</code></pre>\n"
},
{
"answer_id": 277940,
"author": "KJQLjeRJltuEEDGxxXlbteVyyIFEDM",
"author_id": 126491,
"author_profile": "https://wordpress.stackexchange.com/users/126491",
"pm_score": 0,
"selected": false,
"text": "<p>function pagination($query_string){\nglobal $posts_per_page, $paged;\n$my_query = new WP_Query($query_string .\"&posts_per_page=-1\");\n$total_posts = $my_query->post_count;\nif(empty($paged))$paged = 1;\n$prev = $paged - 1;\n$next = $paged + 1;\n$range = 5;\n$showitems = ($range * 2)+1;\n$pages = ceil($total_posts/$posts_per_page);\nif(1 != $pages){\necho '';\necho ($paged > 1 && $showitems < $pages)? '«</li>':\"\";\nfor ($i=1; $i <= $pages; $i++){\nif (1 != $pages &&( !($i >= $paged+$range-0 || $i <= $paged-$range-1) || $pages <= $showitems )){\necho ($paged == $i)? ''.$i.'</li>':''.$i.'</li>';}}\necho ($paged < $pages && $showitems < $pages) ? '»</li>' :\"\";echo \"\\n\";}}</p>\n"
}
] |
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 this file <code>WP_DEBUG</code> is true or false. If you don't want to see warnings then it must be set to <code>false</code> like this</p>\n\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n\n<p>If your <code>WP_DEBUG</code> is true (<code>define('WP_DEBUG', true);</code>) then simply make it false(<code>define('WP_DEBUG', false);</code>).</p>\n\n<p>However if this don't work for your then try to replace your <code>WP_DEBUG</code>\nChange your following line of code</p>\n\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n\n<p>Into this</p>\n\n<pre><code>ini_set('log_errors','On');\nini_set('display_errors','Off');\nini_set('error_reporting', E_ALL );\ndefine('WP_DEBUG', false);\ndefine('WP_DEBUG_LOG', true);\ndefine('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p><strong>Note:</strong> Before trying any change in this file, first take backup of it Because if you mistakenly did any mistake while changing code then it may cause some unwanted problems. </p>\n"
},
{
"answer_id": 241009,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>i think javascript will help you. Use this code, and see if it helps:</p>\n\n<pre><code>add_action( 'add_meta_boxes', function () { add_meta_box('myhtml_ID_123', 'smth', 'draft_title_remover');} );\nfunction draft_title_remover( $post ) { ?>\n <script>\n nIntervId = setInterval(RemoveMyDiv, 1000);\n function RemoveMyDiv() {\n if(document.getElementById(\"message\")){\n var x = document.getElementById(\"message\");\n if( x.innerHTML.indexOf(\"The backup of this post in your browser\") > -1){\n x.style.display=\"none\";\n }\n }\n }\n </script>\n <?php \n}\n</code></pre>\n"
},
{
"answer_id": 285081,
"author": "jaswrks",
"author_id": 81760,
"author_profile": "https://wordpress.stackexchange.com/users/81760",
"pm_score": 1,
"selected": false,
"text": "<p>The way to avoid this error is to make sure the <code>wp-saving-post</code> cookie is being set to a value of <code>[post id]-saved</code>, as seen <a href=\"https://github.com/WordPress/WordPress/blob/10970701d7fbcaf504dd7d35d0e75c5c2b0c2e52/wp-includes/js/autosave.js#L457\" rel=\"nofollow noreferrer\">here</a>. 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.</p>\n\n<p>Also take a look at <a href=\"https://github.com/WordPress/WordPress/blob/a72be13ec0b57a2831d75540fd1892d1bd121f3b/wp-admin/post.php#L197\" rel=\"nofollow noreferrer\">this line</a> and note that WordPress <a href=\"https://github.com/WordPress/WordPress/blob/a72be13ec0b57a2831d75540fd1892d1bd121f3b/wp-admin/post.php#L197\" rel=\"nofollow noreferrer\">handles this for you</a> already. So the error you're seeing, it likely has to do with some mild cookie corruption in your browser.</p>\n\n<p>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.</p>\n\n<p>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 <a href=\"https://github.com/WordPress/WordPress/blob/a72be13ec0b57a2831d75540fd1892d1bd121f3b/wp-admin/post.php#L197\" rel=\"nofollow noreferrer\">this line</a> from running once your filter is applied. That too, may lead to the problem that you're seeing.</p>\n"
},
{
"answer_id": 387106,
"author": "biziclop",
"author_id": 975,
"author_profile": "https://wordpress.stackexchange.com/users/975",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to forcefully turn off the notification, you can use this snippet:</p>\n<pre><code>add_action('in_admin_footer', function(){\n remove_action('admin_footer', '_local_storage_notice');\n});\n</code></pre>\n<p><code>in_admin_footer</code> is the nearest action before <code>admin_footer</code> in <code>wordpress/wp-admin/admin-footer.php</code>, and it always runs, so it's a nice place to prevent running <code>_local_storage_notice()</code> which emits the dialog's content.</p>\n"
}
] |
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(); // Restore global post data stomped by the_post().\n</code></pre>\n\n<p>add that line below post data reset (or replace post data reset with this)</p>\n\n<p>i don't believe you'll need rewind posts.</p>\n"
},
{
"answer_id": 240770,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<blockquote>\n <p>Note: Once after you finish the Wp_Query at the first time you need to <code>reset</code> the <code>Wp_Query</code> after the execution of the code.</p>\n</blockquote>\n\n<pre><code>wp_reset_query(); // This will reset all the global variables to \"\".\n</code></pre>\n\n<p><code>wp_reset_query()</code> 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.</p>\n\n<p>Not only by this method you can reset the <code>Wp_Query</code> there are other methods that you can follow up for resetting the <code>post data</code> and as well as the <code>$args</code>.</p>\n\n<p>Quick Reference About the Resetting Query options.</p>\n\n<ol>\n<li><code>wp_reset_query()</code>- best used after a query_posts loop to reset a custom query</li>\n<li><code>wp_reset_postdata()</code> - best used after custom or multiple loops created with WP_Query</li>\n<li><code>rewind_posts()</code> - best for re-using the same query on the same page.</li>\n</ol>\n\n<p>I hope this is a useful round-up of when & how to reset/rewind the WordPress loop</p>\n\n<p><strong>wp_reset_postdata()</strong></p>\n\n<pre><code>$random_post = new WP_query(); \n$random_post->query('cat=3&showposts=1&orderby=rand'); \nwhile ($random_post->have_posts()) : $random_post->the_post(); \n<a href=\"<?php the_permalink() ?>\" title=\"<?php the_title(); ?>\">\n <img src=\"<?php echo get_post_meta($random_post->ID, 'featured', true); ?>\">\n</a>\nendwhile;\nwp_reset_postdata();\n</code></pre>\n\n<blockquote>\n <p>When to use: best used after custom or multiple loops created with WP_Query.</p>\n</blockquote>\n\n<p><strong>wp_reset_query()</strong></p>\n\n<pre><code><?php query_posts('posts_per_page=3');\nif (have_posts()) : while (have_posts()) : the_post(); ?>\n\n<h1><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h1>\n\n<?php endwhile; endif; ?>\n<?php wp_reset_query(); ?>\n</code></pre>\n\n<blockquote>\n <p>When to use: best used after a query_posts loop to reset things after a custom query.</p>\n</blockquote>\n\n<p><strong>rewind_posts()</strong></p>\n\n<pre><code>if (have_posts()) : while (have_posts()) : the_post(); ?>\n<h1><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></h1>\n<?php endwhile; endif; ?>\n\n<?php rewind_posts(); ?>\n\n<?php while (have_posts()) : the_post(); ?>\n<?php the_content(); ?>\n<?php endwhile; ?>\n</code></pre>\n\n<p>So, while <code>wp_reset_query</code> and <code>wp_reset_postdata</code> reset the entire query object, rewind_posts simply resets the post count, as seen for the function in the <code>wp-includes/query.php</code> file:</p>\n\n<pre><code>// rewind the posts and reset post index\nfunction rewind_posts() {\n $this->current_post = -1;\n if ( $this->post_count > 0 ) {\n $this->post = $this->posts[0];\n }\n}\n</code></pre>\n\n<blockquote>\n <p>When to use: best for re-using the same query on the same page.</p>\n</blockquote>\n"
},
{
"answer_id": 240775,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 0,
"selected": false,
"text": "<p>@Michael Already mention it on his comment that did you read about using <a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow noreferrer\">rewind_posts()</a> with a custom query?? If you don't please read by your self and try to figure out.</p>\n\n<p>Anyway you did wrong on <code>rewind_posts()</code>, Because you used custom query. So use like this.</p>\n\n<pre><code><?php\n// rewind_posts(); \n\n// /* Start the Loop */\n// $args = array( 'post_type' => 'kollektion' );\n// $loop = new WP_Query( $args );\n\n$loop->rewind_posts();\n\nif( $loop ->have_posts() ) :\n while( $loop->have_posts() ) :\n $loop->the_post();\n get_template_part( 'template-parts/content-kollektion-modal', get_post_format() );\n endwhile;\nendif;\n?>\n</code></pre>\n\n<p>But that's not the only one way to querying CPT multiplying one same page.\nFirst see here <a href=\"https://wordpress.stackexchange.com/a/144344/64458\">wp_reset_postdata() or wp_reset_query() after a custom loop?</a> </p>\n\n<p>You just have to restore the global $post variable of the main query loop after a secondary query loop using new WP_Query by using <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\">wp_reset_postdata()</a> .</p>\n\n<pre><code>/* Start the Loop */\n$args = array( 'post_type' => 'kollektion' );\n$loop = new WP_Query( $args );\n\nif( $loop ->have_posts() ) :\n while( $loop->have_posts() ) : $loop->the_post();\n get_template_part( 'template-parts/content-kollektion', get_post_format() );\n endwhile;\n wp_reset_postdata(); \nendif;\n</code></pre>\n\n<p>Replace this loop of your both loop and it will done the trick.</p>\n\n<blockquote>\n <p>Turn ON <code>WP_DEBUG</code> to your WordPress site, before you do something. it\n will help you all the way</p>\n</blockquote>\n"
}
] |
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 try one of these commands. Using sudo would try and run the command as an administrator, so you would need a password: </p>\n\n<pre><code>unlink /path/to/symlink\n\nsudo unlink /path/to/symlink\n\nrm /path/to/symlink\n\nsudo rm /path/to/symlink\n</code></pre>\n"
},
{
"answer_id": 240827,
"author": "Carlos ABS",
"author_id": 103173,
"author_profile": "https://wordpress.stackexchange.com/users/103173",
"pm_score": 0,
"selected": false,
"text": "<p>I made it, inserted this code in the functions.php file and it worked:</p>\n\n<pre><code>function remove_symlink() {\n $linkfile = 'www'; //symlink to delete\n $old = getcwd(); // Save the current directory\n chdir($_SERVER['DOCUMENT_ROOT']); //Location of the file to be deleted\n\n if(file_exists($linkfile)) {\n if(is_link($linkfile)) {\n unlink($linkfile);\n } else {\n exit(\"File exists but not symbolic link\\n\");\n }\n }\n chdir($old); // Restore the old working directory ;\n}\n\nremove_symlink();\n</code></pre>\n\n<p>Note that you need to change the current working directory (chdir) to the symlink directory you want to delete.</p>\n\n<p>Thanks for the insights!</p>\n"
}
] |
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\" content=\"%2$s\" class=\"entry-date published updated\" datetime=\"%1$s\">%2$s</time>';\nif ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {\n $time_string = '<time itemprop=\"datePublished\" content=\"%2$s\" class=\"entry-date published\" datetime=\"%1$s\">%2$s</time><time itemprop=\"dateModified\" content=\"%4$s\" class=\"updated\" datetime=\"%3$s\">%4$s</time>';\n}\n\n$time_string = sprintf( $time_string,\n esc_attr( get_the_date( 'c' ) ),\n esc_html( get_the_date() ),\n esc_attr( get_the_modified_date( 'c' ) ),\n esc_html( get_the_modified_date() )\n);\n\n$time_posted = esc_html( get_the_time() );\n$u_time = get_the_time('U'); \n$u_modified_time = get_the_modified_time('U');\n\n$posted_on = sprintf(\n _x( '%s', 'post date', 'ci' ),\n '' . $time_string . ''\n);\n\nif ($u_modified_time >= $u_time + 86400) :\n the_modified_time('g:i a'); \nelse :\n echo ' . $posted_on . ' at ' . $time_posted . ';\n</code></pre>\n\n<p>This is working but using modified date, i want if published date is less than 24 hours show time and after 24 hours show date and time</p>\n"
},
{
"answer_id": 240776,
"author": "cowgill",
"author_id": 5549,
"author_profile": "https://wordpress.stackexchange.com/users/5549",
"pm_score": 1,
"selected": false,
"text": "<p>This should do it.</p>\n\n<pre><code>// See if the post is older than 24 hours.\nif ( get_post_time() <= strtotime( '-1 day' ) ) {\n echo 'Published more than 24 hours ago.';\n} else {\n echo 'Published within the last 24 hours.';\n}\n</code></pre>\n"
}
] |
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 category_post_count( $atts ) {\n\n $atts = shortcode_atts( array(\n 'category' => null\n ), $atts );\n\n // get the category by slug.\n $term = get_term_by( 'slug', $atts['category'], 'category');\n\n return ( isset( $term->count ) ) ? $term->count : 0;\n}\nadd_shortcode( 'category_post_count', 'category_post_count' );\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code>[category_post_count category=\"category_slug_or_name\"]\n</code></pre>\n\n<h3>If you want to get the count by name, not slug change this</h3>\n\n<pre><code>$term = get_term_by( 'slug', $atts['category'], 'category');\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>$term = get_term_by( 'name', $atts['category'], 'category');\n</code></pre>\n"
},
{
"answer_id": 295822,
"author": "Joe",
"author_id": 86358,
"author_profile": "https://wordpress.stackexchange.com/users/86358",
"pm_score": 1,
"selected": false,
"text": "<p>To count posts in subcategories in addition to specified category, one possibility is to query posts using a <code>cat</code> option and count the results. <code>cat</code> option queries posts in child categories by default.</p>\n\n<pre><code>add_shortcode('category_post_count', function ($atts, $content) {\n $atts = shortcode_atts([\n 'category' => 0\n ], $atts);\n $cat_id = is_numeric($atts['category']) ?\n intval($atts['category']) :\n get_category_by_slug($atts['category'])->term_id;\n return count(get_posts([\n 'nopaging' => true,\n 'fields' => 'ids',\n 'cat' => $cat_id\n ]));\n});\n</code></pre>\n\n<p>There are examples of querying the child categories and summing up the <code>count</code> fields, but this may yield invalid results if a post belongs to more than one of the matched categories.</p>\n"
}
] |
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 to upload.</p>\n\n<p><strong>If you like to write codes:</strong>\nPlace this code snippet in your theme's <code>functions.php</code> file-</p>\n\n<pre><code>add_filter( 'intermediate_image_sizes_advanced', 'wpse_240765_image_sizes' );\n\nfunction wpse_240765_image_sizes( $sizes ){\n $sizes = array();\n return $sizes;\n}\n</code></pre>\n\n<p><strong>Or with a plugin:</strong> Use this plugin- <a href=\"https://wordpress.org/plugins/image-sizes/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/image-sizes/</a></p>\n\n<p>It'll give you the same output. You can even choose which of the image sizes you want to be prevented from creating.\n<a href=\"https://i.stack.imgur.com/KNPPy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KNPPy.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 240845,
"author": "italiansoda",
"author_id": 71608,
"author_profile": "https://wordpress.stackexchange.com/users/71608",
"pm_score": 0,
"selected": false,
"text": "<p>1)\nTo stop WordPress from creating multiple image sizes upon uploading of an image, you can accomplish this without using a plugin. </p>\n\n<p>Navigate to <strong>Settings</strong> > <strong>Media</strong> in the admin section. </p>\n\n<p>By setting the sizes to <strong>0</strong> you will disable WordPress from creating default image sizes and only the original image will be stored. </p>\n\n<p><a href=\"https://i.stack.imgur.com/7VTBX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7VTBX.png\" alt=\"enter image description here\"></a></p>\n\n<p>2) To reduce the 20GBs of images you have on your site, I would simply SFTP into your server and manually delete the different sized images. From the root directory of a WordPress install, navigate to <code>wp-content/uploads/<yyyy>/<mm>/</code> and you will find all of your images and media uploads. You want to be sure to leave the original image, or else you are simply deleting the entire image. Any image file name with an extra <code>- ###x###.jpg</code> is an auto generated image. The original image would not have this in the file name. </p>\n\n<p>As an aside - to help you with your images I would check out WPMU DEV's WP-Smush plugin.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-smushit/\" rel=\"nofollow noreferrer\">WP-Smush - Image Optimization</a></p>\n\n<p>It's really great and when you upload images it automatically uses their servers to crunch and compress images before storing. It also can size down large resolution images to a reasonable maximum size. You really shouldn't have to display an image that is bigger than 2048x2048. </p>\n"
},
{
"answer_id": 240907,
"author": "marikamitsos",
"author_id": 17797,
"author_profile": "https://wordpress.stackexchange.com/users/17797",
"pm_score": 2,
"selected": false,
"text": "<p><strong>If coding is not your strongest point</strong> you may want to look at a plugin solution.</p>\n<p>What I have in mind is a suggestion of a couple free plugins residing in the WordPress repository:</p>\n<ul>\n<li><a href=\"https://wordpress.org/plugins/media-cleaner/\" rel=\"nofollow noreferrer\">Media Cleaner</a> by <a href=\"https://profiles.wordpress.org/tigroumeow/\" rel=\"nofollow noreferrer\">Jordy Meow</a></li>\n<li><a href=\"https://wordpress.org/plugins/optimize-images-resizing/\" rel=\"nofollow noreferrer\">Optimize Images Resizing</a> by <a href=\"https://profiles.wordpress.org/originalexe/\" rel=\"nofollow noreferrer\">OriginalEXE</a></li>\n<li><a href=\"https://wordpress.org/plugins/thumbnail-cleaner/\" rel=\"nofollow noreferrer\">Thumbnail Cleaner</a></li>\n</ul>\n<p>I must admit that I have not yet used the first one - <a href=\"https://wordpress.org/plugins/media-cleaner/\" rel=\"nofollow noreferrer\">Media Cleaner</a> - so I cannot provide you with a solid opinion.</p>\n<p>I have used though the second one - <a href=\"https://wordpress.org/plugins/optimize-images-resizing/\" rel=\"nofollow noreferrer\">Optimize Images Resizing</a> - and had the expected results.</p>\n<h2>Points to always look for in any case:</h2>\n<p>Before attempting anything,</p>\n<ul>\n<li><p><strong>I cannot stretch enough the importance of creating a full <a href=\"https://codex.wordpress.org/WordPress_Backups\" rel=\"nofollow noreferrer\">backup of your WordPress installation</a> (both your uploads folder and your dB)</strong>.<br />\nI do understand that we are talking about 20GB but a backup is essential, especially in this unique situation.</p>\n</li>\n<li><p>This procedure is time consuming as well as heavy on the server.<br />\nIt is wise to put your site in the maintenance mode.</p>\n</li>\n<li><p>Delete orphan attachments</p>\n</li>\n</ul>\n<p><strong>After all is done</strong> use your favorite <a href=\"https://wordpress.org/plugins/search.php?q=Regenerate+Thumbnails\" rel=\"nofollow noreferrer\">Regenerate Thumbnails</a> plugins to get your WordPress/themes image sizes back as well as install <a href=\"https://wordpress.org/plugins/ewww-image-optimizer/\" rel=\"nofollow noreferrer\">EWWW Image Optimizer</a> and <a href=\"https://wordpress.org/plugins/imsanity/\" rel=\"nofollow noreferrer\">Imsanity</a>. This combination will guarantee optimized, resized, only necessary images.</p>\n<hr />\n<h3>Plugin specific points.</h3>\n<p><a href=\"https://wordpress.org/plugins/media-cleaner/\" rel=\"nofollow noreferrer\">Media Cleaner</a></p>\n<ul>\n<li>"<em>Files detected as un-used are added to a specific dashboard where you can choose to trash them. They will be then moved to a trash internal to the plugin. After more testing, you can trash them definitely</em>".</li>\n<li>Some plugins may clash with it. If that happens and assuming you are on maintenance mode, deactivate all and do your cleaning.</li>\n</ul>\n<p><a href=\"https://wordpress.org/plugins/optimize-images-resizing/\" rel=\"nofollow noreferrer\">Optimize Images Resizing</a></p>\n<ul>\n<li>"<em>TO REMOVE image sizes generated prior to activating the plugin, visit the Settings -> Media and use the button under "Remove image sizes" to perform the cleanup</em>".</li>\n<li>Read this support thread: <a href=\"https://wordpress.org/support/topic/urgent-questions-on-processing-existing-images/?replies=11#post-7660645\" rel=\"nofollow noreferrer\">Urgent questions on processing existing images</a></li>\n</ul>\n<p><a href=\"https://wordpress.org/plugins/thumbnail-cleaner/\" rel=\"nofollow noreferrer\">Thumbnail Cleaner</a></p>\n<ul>\n<li>Includes functions like: Creating backups of your uploads, analyzes your uploads directory, giving you an overview how many original files and thumbnails there are, restores backups in case you have lost a file that was not supposed to be deleted.</li>\n<li>Read this support thread: <a href=\"https://wordpress.org/support/topic/backup-only-orginal-image/\" rel=\"nofollow noreferrer\">Backup only original image</a></li>\n</ul>\n<hr />\n<p>Please let us know how you achieved the best results.</p>\n"
},
{
"answer_id": 241237,
"author": "Phill Healey",
"author_id": 55152,
"author_profile": "https://wordpress.stackexchange.com/users/55152",
"pm_score": 0,
"selected": false,
"text": "<p>The flowing steps should do it:</p>\n\n<p>1)You should start by removing any unneeded image sizes from your relevant files e.g. functions. PHP in your theme and any plugins if the exist (e.g. rudderless). </p>\n\n<p>2)Next you can delete all required image sizes via ftp. </p>\n\n<p>3)Then you need to regenerate the thumbnails (e.g. all the image sizes that Wordpress is being told to create.) You can use any 'Regenerate thumbnails' plugin from the WP repo.</p>\n\n<p>Alternatively try this:\n1) Same as step 1 above</p>\n\n<p>2) There are a couple of plugins in the plugin directory(repo) which will delete all WP thumbs and then only generate the thumbs when they are called for the first time on any given page on your website. On subsequent request for the image, the image will already exist and be served as normal. The benefit of this is that thumbs are only created for images/sizes that are actually required by your site. However, images called in non-standard ways may not get generated.</p>\n\n<p>If you want to reduce additional overhead from excessively large original images you can use 'imsanity' plugin to reduce the physical file size of these originals down to a size of your choice. It's a great tool for sites with user submitted images.</p>\n"
},
{
"answer_id": 241243,
"author": "user9447",
"author_id": 25271,
"author_profile": "https://wordpress.stackexchange.com/users/25271",
"pm_score": 3,
"selected": false,
"text": "<p>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 <code>functions.php</code>:</p>\n\n<pre><code>function wpse_240765_unset_images( $sizes ){\n unset( $sizes[ 'thumbnail' ]);\n unset( $sizes[ 'medium' ]);\n unset( $sizes[ 'medium_large' ] );\n unset( $sizes[ 'large' ]);\n unset( $sizes[ 'full' ] );\n return $sizes;\n}\nadd_filter( 'intermediate_image_sizes_advanced', 'wpse_240765_unset_images' );\n</code></pre>\n\n<p>and you can also turn off future default image generation by setting the images to zero:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7VTBX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7VTBX.png\" alt=\"enter image description here\"></a></p>\n\n<p>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:</p>\n\n<ul>\n<li><p>Download all the photos locally using an SFTP service, I love <a href=\"https://panic.com/transmit/\" rel=\"noreferrer\">Transmit</a> (paid) but you can use something like <a href=\"https://filezilla-project.org/\" rel=\"noreferrer\">Filezilla</a> (free) .</p></li>\n<li><p>Download all the files to a directory. </p></li>\n</ul>\n\n<p>I'm on a Mac but any terminal that allows bash will work. I coded a simple bash script:</p>\n\n<pre><code># !/bin/bash\n\nUSERNAME=vader\nDIRECTORY=\"/Users/$USERNAME/desktop/question240765\"\nfor imageWithSize in $(find \"$DIRECTORY\" -type f -regex '.*/[a-z-]*-[0-9].*.txt$'); do\n cd $DIRECTORY\n echo rm $imageWithSize\ndone\n</code></pre>\n\n<p>The folder is located on my desktop, and for the question I named it <code>question240765</code>. I used <code>.txt</code> files to test this but you can change it to <code>.jpg</code>. I saved it as a bash file <code>image_dust.sh</code> so that it will allow me to modify or enhance later down the road. Run the script first with the <code>echo</code> and you could even dump it to a file with changing the line:</p>\n\n<pre><code>echo rm $imageWithSize \n</code></pre>\n\n<p>to:</p>\n\n<pre><code>echo rm $imageWithSize >> result.txt\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>rm $imageWithSize\n</code></pre>\n\n<p>If you're curious here is what the regex does:</p>\n\n<ul>\n<li><code>[a-z-]*</code> looks for filenames like <code>foo-bar</code> or <code>fo-fo-bar</code>. if you have uppercase letters in your name use <code>[A-Za-z-]*</code></li>\n<li><code>-[0-9]</code> after the filename it looks for the remaining <code>-</code> (dash) with a number <code>[0-9]</code></li>\n<li><code>.*.txt</code> looks for anything after the first digit to the end of the name with the extension.</li>\n</ul>\n\n<p>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 <code>imagemagick</code> but I prefer <code>sips</code> to reduce the compression size of the images.</p>\n"
},
{
"answer_id": 241274,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>To remove all superfluous image files, we'll have to loop through all posts, find the attachments to those posts, establish which attached image sizes are no longer needed and remove those files. Here we go.</p>\n\n<p>First, <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow\">get all (custom) posts and pages</a> and loop through them:</p>\n\n<pre><code>$the_query = new WP_Query (array ('posts_per_page' => -1, 'post_type' => 'any'));\nforeach ($all_posts as $post) { ... }\n</code></pre>\n\n<p>Next for <code>$post</code> <a href=\"https://codex.wordpress.org/Function_Reference/get_attached_media\" rel=\"nofollow\">get all the attached images</a> and <a href=\"https://codex.wordpress.org/Function_Reference/get_intermediate_image_sizes\" rel=\"nofollow\">get a list of all media sizes</a>. Then loop through them:</p>\n\n<pre><code>$images = get_attached_media ('image',$post); // returns array of post objects\n$sizes = get_intermediate_image_sizes(); // returns array of identifying strings\nforeach ($images as $image) {\n foreach ($sizes as $size) {\n ...\n }\n }\n</code></pre>\n\n<p>Now for this image and size, <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow\">find the url</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_delete_file/\" rel=\"nofollow\">delete the file</a></p>\n\n<pre><code>$att = wp_get_attachment_image_src ($image->ID,$size); returns array of file properties\nwp_delete_file ($att['url']);\n</code></pre>\n\n<p>I'd give this code a thorough test before applying it... With 20GB in images it could also take a while to execute.</p>\n"
},
{
"answer_id": 242074,
"author": "Ahmad Awais",
"author_id": 43555,
"author_profile": "https://wordpress.stackexchange.com/users/43555",
"pm_score": 1,
"selected": false,
"text": "<p>If you have SSH access then you can run the following commands to list and remove the resized images. Later you can rebuild them.</p>\n\n<p>List all resized images.</p>\n\n<pre><code># List all resized images.\n# Usage: lrimg site.ext\nfunction lrimg() {\n clear\n THE_PWD=$PWD\n cd ~\n cd /var/www/\"$1\"/htdocs/wp-content/uploads/\n find . -regextype posix-extended -regex \".*-[[:digit:]]{1,9}x[[:digit:]]{1,9}(@2x)?.(jpg|jpeg|png|eps|gif)\" -type f\n cd $THE_PWD\n}\n</code></pre>\n\n<p>Remove all resized images.</p>\n\n<pre><code># Remove all resized images.\n# Usage: lrimgrm site.ext\nfunction lrimgrm() {\n clear\n THE_PWD=$PWD\n cd ~\n cd /var/www/\"$1\"/htdocs/wp-content/uploads/\n find . -regextype posix-extended -regex \".*-[[:digit:]]{1,9}x[[:digit:]]{1,9}(@2x)?.(jpg|jpeg|png|eps|gif)\" -type f -exec rm {} \\;\n cd $THE_PWD\n}\n</code></pre>\n\n<p>Be careful here. Keep your backups ready.</p>\n\n<p>P.S. My server has an NGINX setup which is why the site paths are <code>/var/www/\"$1\"/htdocs/</code> $1 being the parameter which is the site name. You can modify it to match your path.</p>\n"
},
{
"answer_id": 351348,
"author": "mwdev",
"author_id": 177454,
"author_profile": "https://wordpress.stackexchange.com/users/177454",
"pm_score": 3,
"selected": false,
"text": "<p>You can easily delete files using \"find\" command on linux, just needed to do the same thing. You can run the following in bash console:</p>\n\n<pre><code>cd /var/www/wordpress/wp-content/uploads\nfind -type f -regex '.*[0-9]+x[0-9]+.\\(jpg\\|png\\|jpeg\\)$' -delete\n</code></pre>\n"
},
{
"answer_id": 357854,
"author": "bristweb",
"author_id": 182084,
"author_profile": "https://wordpress.stackexchange.com/users/182084",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a way you can do this programmatically (for the most part). </p>\n\n<p>1: Set your media sizes (ex: thumbnail 300x300 and the rest 0x0 to keep WP from generating anything other than thumbnail.)</p>\n\n<p>2: Generate the new images with <a href=\"https://developer.wordpress.org/cli/commands/media/regenerate/\" rel=\"nofollow noreferrer\">WP CLI</a>, but do not delete any of the old sizes until it's ready. Or if you really are not keeping any resized images, skip this.</p>\n\n<pre><code>$ wp media regenerate --skip-delete\n</code></pre>\n\n<p>3: Search replace image paths with <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">WP CLI</a>. This updates posts and pages content so you don't have broken images on your site.</p>\n\n<p>Your regular expression will need to be something like the following. </p>\n\n<pre><code>(\\/wp-content\\/uploads\\/)([0-9]{4}\\/[0-9]{2}\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/7xo9Ypi1ESh57l6P.png\" alt=\"Regular expression visualization\"></p>\n\n<p><a href=\"https://www.debuggex.com/r/7xo9Ypi1ESh57l6P\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p>And would have the following wp search-replace:</p>\n\n<pre><code>$ wp search-replace '(\\/wp-content\\/uploads\\/)([0-9]{4}\\/[0-9]{2}\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})' '$1$2$3$5' --regex\n</code></pre>\n\n<p>Or you might have a different upload folder or don't have the year/month folders included. In that case you'd have slightly different regex</p>\n\n<pre><code>(\\/app\\/uploads\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/aHBmaFpz_z1UiT2W.png\" alt=\"Regular expression visualization\"></p>\n\n<p><a href=\"https://www.debuggex.com/r/aHBmaFpz_z1UiT2W\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p>and you'd run</p>\n\n<pre><code>$ wp search-replace '(\\/app\\/uploads\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})' '$1$2$4' --regex\n</code></pre>\n\n<p><strong>Just to be clear: this would make your load times horrible - all images would serve from their full-size file and not the smaller image.</strong>\nIt would be a good idea perhaps to swap your image server with an image processing API / CDN so these problems go away :)</p>\n\n<p>If you are at least keeping one thumbnail, like the 300x300 example I gave, you'd need to run a little different regex:</p>\n\n<pre><code>(\\/wp-content\\/uploads\\/)(.*)(-(?!(?:72))[0-9]{1,5}x(?!(?:72))[0-9]{1,5})(\\..{2,4})\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/scJ10BzDNlGzVdk_.png\" alt=\"Regular expression visualization\"></p>\n\n<p><a href=\"https://www.debuggex.com/r/scJ10BzDNlGzVdk_\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p>Then you run WP CLI twice. The first swaps all the images that aren't the 72x72 thumbnail. The latter changes all the 72x72 thumbnails to the new 300x300 thumbnail</p>\n\n<pre><code>$ wp search-replace '(\\/wp-content\\/uploads\\/)(.*)(-(?!(?:72))[0-9]{1,5}x(?!(?:72))[0-9]{1,5})(\\..{2,4})' '$1$2$4' --regex\n\n$ wp search-replace '(\\/wp-content\\/uploads\\/)(.*)(-72x72)(\\..{2,4})' '$1$2-300x300$4' --regex\n</code></pre>\n\n<p>4: now delete all unused images:</p>\n\n<pre><code>$ wp media regenerate\n</code></pre>\n"
},
{
"answer_id": 375646,
"author": "Brent Pickrel",
"author_id": 195387,
"author_profile": "https://wordpress.stackexchange.com/users/195387",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up using filezilla to connect via ftp. I then searched the uploads folder using the remote file search feature within Filezilla. I used regex in combinations to select all and delete. i.e. \\d\\d\\dx\\d\\d\\d.jpg or \\d\\dx\\d\\d.png or \\d\\d\\dx\\d\\d\\d\\d.gif. I kept using different combinations of the "\\d" to find either a 3 digit by 4 digit size of image or a 2 digit by 2 digit size of image.</p>\n"
},
{
"answer_id": 385093,
"author": "Fred",
"author_id": 203376,
"author_profile": "https://wordpress.stackexchange.com/users/203376",
"pm_score": 0,
"selected": false,
"text": "<p>I am no coder but this works - found it at this url\n<a href=\"https://crunchify.com/wordpress-tips-how-to-remove-redundant-image-sizes-and-files/\" rel=\"nofollow noreferrer\">https://crunchify.com/wordpress-tips-how-to-remove-redundant-image-sizes-and-files/</a></p>\n<p>ssh into your public_html</p>\n<p>Use the following (without the quotes) to find all the images of that nominated size\n"find . -name <em>-72x72.</em>"</p>\n<p>This line removes images of the nominated size\n"find . -name <em>-72x72.</em> | xargs rm -f"</p>\n<p>then just change the 72x72 to the next image size</p>\n<p>Removes a thousand images in one second - you will think it didn't work until you check your uploads and see they are gone.</p>\n"
},
{
"answer_id": 396943,
"author": "Vignesh PV",
"author_id": 152215,
"author_profile": "https://wordpress.stackexchange.com/users/152215",
"pm_score": 0,
"selected": false,
"text": "<p>I too faced the same problem and finally found the solution. It worked 100% for me. I have cleared nearly 10GB of files.</p>\n<p>The command lines below will remove currently resized images, including Retina versions so that we can correctly resize WordPress images per the new theme dimensions. And yes, we're using the command line, because I (Michael) am old school.</p>\n<pre><code>cd /home/example/public_html/wp-content/uploads\n\nfind . -regextype posix-extended -regex ".*-[[:digit:]]{2,4}x[[:digit:]]{2,4}(@2x)?.(jpg|jpeg|png|eps|gif)" -type f -exec rm {} \\;\n</code></pre>\n<p>Reference - <a href=\"https://www.axelerant.com/blog/remove-resize-wordpress-images\" rel=\"nofollow noreferrer\">https://www.axelerant.com/blog/remove-resize-wordpress-images</a></p>\n"
}
] |
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 to upload.</p>\n\n<p><strong>If you like to write codes:</strong>\nPlace this code snippet in your theme's <code>functions.php</code> file-</p>\n\n<pre><code>add_filter( 'intermediate_image_sizes_advanced', 'wpse_240765_image_sizes' );\n\nfunction wpse_240765_image_sizes( $sizes ){\n $sizes = array();\n return $sizes;\n}\n</code></pre>\n\n<p><strong>Or with a plugin:</strong> Use this plugin- <a href=\"https://wordpress.org/plugins/image-sizes/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/image-sizes/</a></p>\n\n<p>It'll give you the same output. You can even choose which of the image sizes you want to be prevented from creating.\n<a href=\"https://i.stack.imgur.com/KNPPy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KNPPy.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 240845,
"author": "italiansoda",
"author_id": 71608,
"author_profile": "https://wordpress.stackexchange.com/users/71608",
"pm_score": 0,
"selected": false,
"text": "<p>1)\nTo stop WordPress from creating multiple image sizes upon uploading of an image, you can accomplish this without using a plugin. </p>\n\n<p>Navigate to <strong>Settings</strong> > <strong>Media</strong> in the admin section. </p>\n\n<p>By setting the sizes to <strong>0</strong> you will disable WordPress from creating default image sizes and only the original image will be stored. </p>\n\n<p><a href=\"https://i.stack.imgur.com/7VTBX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7VTBX.png\" alt=\"enter image description here\"></a></p>\n\n<p>2) To reduce the 20GBs of images you have on your site, I would simply SFTP into your server and manually delete the different sized images. From the root directory of a WordPress install, navigate to <code>wp-content/uploads/<yyyy>/<mm>/</code> and you will find all of your images and media uploads. You want to be sure to leave the original image, or else you are simply deleting the entire image. Any image file name with an extra <code>- ###x###.jpg</code> is an auto generated image. The original image would not have this in the file name. </p>\n\n<p>As an aside - to help you with your images I would check out WPMU DEV's WP-Smush plugin.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-smushit/\" rel=\"nofollow noreferrer\">WP-Smush - Image Optimization</a></p>\n\n<p>It's really great and when you upload images it automatically uses their servers to crunch and compress images before storing. It also can size down large resolution images to a reasonable maximum size. You really shouldn't have to display an image that is bigger than 2048x2048. </p>\n"
},
{
"answer_id": 240907,
"author": "marikamitsos",
"author_id": 17797,
"author_profile": "https://wordpress.stackexchange.com/users/17797",
"pm_score": 2,
"selected": false,
"text": "<p><strong>If coding is not your strongest point</strong> you may want to look at a plugin solution.</p>\n<p>What I have in mind is a suggestion of a couple free plugins residing in the WordPress repository:</p>\n<ul>\n<li><a href=\"https://wordpress.org/plugins/media-cleaner/\" rel=\"nofollow noreferrer\">Media Cleaner</a> by <a href=\"https://profiles.wordpress.org/tigroumeow/\" rel=\"nofollow noreferrer\">Jordy Meow</a></li>\n<li><a href=\"https://wordpress.org/plugins/optimize-images-resizing/\" rel=\"nofollow noreferrer\">Optimize Images Resizing</a> by <a href=\"https://profiles.wordpress.org/originalexe/\" rel=\"nofollow noreferrer\">OriginalEXE</a></li>\n<li><a href=\"https://wordpress.org/plugins/thumbnail-cleaner/\" rel=\"nofollow noreferrer\">Thumbnail Cleaner</a></li>\n</ul>\n<p>I must admit that I have not yet used the first one - <a href=\"https://wordpress.org/plugins/media-cleaner/\" rel=\"nofollow noreferrer\">Media Cleaner</a> - so I cannot provide you with a solid opinion.</p>\n<p>I have used though the second one - <a href=\"https://wordpress.org/plugins/optimize-images-resizing/\" rel=\"nofollow noreferrer\">Optimize Images Resizing</a> - and had the expected results.</p>\n<h2>Points to always look for in any case:</h2>\n<p>Before attempting anything,</p>\n<ul>\n<li><p><strong>I cannot stretch enough the importance of creating a full <a href=\"https://codex.wordpress.org/WordPress_Backups\" rel=\"nofollow noreferrer\">backup of your WordPress installation</a> (both your uploads folder and your dB)</strong>.<br />\nI do understand that we are talking about 20GB but a backup is essential, especially in this unique situation.</p>\n</li>\n<li><p>This procedure is time consuming as well as heavy on the server.<br />\nIt is wise to put your site in the maintenance mode.</p>\n</li>\n<li><p>Delete orphan attachments</p>\n</li>\n</ul>\n<p><strong>After all is done</strong> use your favorite <a href=\"https://wordpress.org/plugins/search.php?q=Regenerate+Thumbnails\" rel=\"nofollow noreferrer\">Regenerate Thumbnails</a> plugins to get your WordPress/themes image sizes back as well as install <a href=\"https://wordpress.org/plugins/ewww-image-optimizer/\" rel=\"nofollow noreferrer\">EWWW Image Optimizer</a> and <a href=\"https://wordpress.org/plugins/imsanity/\" rel=\"nofollow noreferrer\">Imsanity</a>. This combination will guarantee optimized, resized, only necessary images.</p>\n<hr />\n<h3>Plugin specific points.</h3>\n<p><a href=\"https://wordpress.org/plugins/media-cleaner/\" rel=\"nofollow noreferrer\">Media Cleaner</a></p>\n<ul>\n<li>"<em>Files detected as un-used are added to a specific dashboard where you can choose to trash them. They will be then moved to a trash internal to the plugin. After more testing, you can trash them definitely</em>".</li>\n<li>Some plugins may clash with it. If that happens and assuming you are on maintenance mode, deactivate all and do your cleaning.</li>\n</ul>\n<p><a href=\"https://wordpress.org/plugins/optimize-images-resizing/\" rel=\"nofollow noreferrer\">Optimize Images Resizing</a></p>\n<ul>\n<li>"<em>TO REMOVE image sizes generated prior to activating the plugin, visit the Settings -> Media and use the button under "Remove image sizes" to perform the cleanup</em>".</li>\n<li>Read this support thread: <a href=\"https://wordpress.org/support/topic/urgent-questions-on-processing-existing-images/?replies=11#post-7660645\" rel=\"nofollow noreferrer\">Urgent questions on processing existing images</a></li>\n</ul>\n<p><a href=\"https://wordpress.org/plugins/thumbnail-cleaner/\" rel=\"nofollow noreferrer\">Thumbnail Cleaner</a></p>\n<ul>\n<li>Includes functions like: Creating backups of your uploads, analyzes your uploads directory, giving you an overview how many original files and thumbnails there are, restores backups in case you have lost a file that was not supposed to be deleted.</li>\n<li>Read this support thread: <a href=\"https://wordpress.org/support/topic/backup-only-orginal-image/\" rel=\"nofollow noreferrer\">Backup only original image</a></li>\n</ul>\n<hr />\n<p>Please let us know how you achieved the best results.</p>\n"
},
{
"answer_id": 241237,
"author": "Phill Healey",
"author_id": 55152,
"author_profile": "https://wordpress.stackexchange.com/users/55152",
"pm_score": 0,
"selected": false,
"text": "<p>The flowing steps should do it:</p>\n\n<p>1)You should start by removing any unneeded image sizes from your relevant files e.g. functions. PHP in your theme and any plugins if the exist (e.g. rudderless). </p>\n\n<p>2)Next you can delete all required image sizes via ftp. </p>\n\n<p>3)Then you need to regenerate the thumbnails (e.g. all the image sizes that Wordpress is being told to create.) You can use any 'Regenerate thumbnails' plugin from the WP repo.</p>\n\n<p>Alternatively try this:\n1) Same as step 1 above</p>\n\n<p>2) There are a couple of plugins in the plugin directory(repo) which will delete all WP thumbs and then only generate the thumbs when they are called for the first time on any given page on your website. On subsequent request for the image, the image will already exist and be served as normal. The benefit of this is that thumbs are only created for images/sizes that are actually required by your site. However, images called in non-standard ways may not get generated.</p>\n\n<p>If you want to reduce additional overhead from excessively large original images you can use 'imsanity' plugin to reduce the physical file size of these originals down to a size of your choice. It's a great tool for sites with user submitted images.</p>\n"
},
{
"answer_id": 241243,
"author": "user9447",
"author_id": 25271,
"author_profile": "https://wordpress.stackexchange.com/users/25271",
"pm_score": 3,
"selected": false,
"text": "<p>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 <code>functions.php</code>:</p>\n\n<pre><code>function wpse_240765_unset_images( $sizes ){\n unset( $sizes[ 'thumbnail' ]);\n unset( $sizes[ 'medium' ]);\n unset( $sizes[ 'medium_large' ] );\n unset( $sizes[ 'large' ]);\n unset( $sizes[ 'full' ] );\n return $sizes;\n}\nadd_filter( 'intermediate_image_sizes_advanced', 'wpse_240765_unset_images' );\n</code></pre>\n\n<p>and you can also turn off future default image generation by setting the images to zero:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7VTBX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7VTBX.png\" alt=\"enter image description here\"></a></p>\n\n<p>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:</p>\n\n<ul>\n<li><p>Download all the photos locally using an SFTP service, I love <a href=\"https://panic.com/transmit/\" rel=\"noreferrer\">Transmit</a> (paid) but you can use something like <a href=\"https://filezilla-project.org/\" rel=\"noreferrer\">Filezilla</a> (free) .</p></li>\n<li><p>Download all the files to a directory. </p></li>\n</ul>\n\n<p>I'm on a Mac but any terminal that allows bash will work. I coded a simple bash script:</p>\n\n<pre><code># !/bin/bash\n\nUSERNAME=vader\nDIRECTORY=\"/Users/$USERNAME/desktop/question240765\"\nfor imageWithSize in $(find \"$DIRECTORY\" -type f -regex '.*/[a-z-]*-[0-9].*.txt$'); do\n cd $DIRECTORY\n echo rm $imageWithSize\ndone\n</code></pre>\n\n<p>The folder is located on my desktop, and for the question I named it <code>question240765</code>. I used <code>.txt</code> files to test this but you can change it to <code>.jpg</code>. I saved it as a bash file <code>image_dust.sh</code> so that it will allow me to modify or enhance later down the road. Run the script first with the <code>echo</code> and you could even dump it to a file with changing the line:</p>\n\n<pre><code>echo rm $imageWithSize \n</code></pre>\n\n<p>to:</p>\n\n<pre><code>echo rm $imageWithSize >> result.txt\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>rm $imageWithSize\n</code></pre>\n\n<p>If you're curious here is what the regex does:</p>\n\n<ul>\n<li><code>[a-z-]*</code> looks for filenames like <code>foo-bar</code> or <code>fo-fo-bar</code>. if you have uppercase letters in your name use <code>[A-Za-z-]*</code></li>\n<li><code>-[0-9]</code> after the filename it looks for the remaining <code>-</code> (dash) with a number <code>[0-9]</code></li>\n<li><code>.*.txt</code> looks for anything after the first digit to the end of the name with the extension.</li>\n</ul>\n\n<p>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 <code>imagemagick</code> but I prefer <code>sips</code> to reduce the compression size of the images.</p>\n"
},
{
"answer_id": 241274,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>To remove all superfluous image files, we'll have to loop through all posts, find the attachments to those posts, establish which attached image sizes are no longer needed and remove those files. Here we go.</p>\n\n<p>First, <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow\">get all (custom) posts and pages</a> and loop through them:</p>\n\n<pre><code>$the_query = new WP_Query (array ('posts_per_page' => -1, 'post_type' => 'any'));\nforeach ($all_posts as $post) { ... }\n</code></pre>\n\n<p>Next for <code>$post</code> <a href=\"https://codex.wordpress.org/Function_Reference/get_attached_media\" rel=\"nofollow\">get all the attached images</a> and <a href=\"https://codex.wordpress.org/Function_Reference/get_intermediate_image_sizes\" rel=\"nofollow\">get a list of all media sizes</a>. Then loop through them:</p>\n\n<pre><code>$images = get_attached_media ('image',$post); // returns array of post objects\n$sizes = get_intermediate_image_sizes(); // returns array of identifying strings\nforeach ($images as $image) {\n foreach ($sizes as $size) {\n ...\n }\n }\n</code></pre>\n\n<p>Now for this image and size, <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow\">find the url</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_delete_file/\" rel=\"nofollow\">delete the file</a></p>\n\n<pre><code>$att = wp_get_attachment_image_src ($image->ID,$size); returns array of file properties\nwp_delete_file ($att['url']);\n</code></pre>\n\n<p>I'd give this code a thorough test before applying it... With 20GB in images it could also take a while to execute.</p>\n"
},
{
"answer_id": 242074,
"author": "Ahmad Awais",
"author_id": 43555,
"author_profile": "https://wordpress.stackexchange.com/users/43555",
"pm_score": 1,
"selected": false,
"text": "<p>If you have SSH access then you can run the following commands to list and remove the resized images. Later you can rebuild them.</p>\n\n<p>List all resized images.</p>\n\n<pre><code># List all resized images.\n# Usage: lrimg site.ext\nfunction lrimg() {\n clear\n THE_PWD=$PWD\n cd ~\n cd /var/www/\"$1\"/htdocs/wp-content/uploads/\n find . -regextype posix-extended -regex \".*-[[:digit:]]{1,9}x[[:digit:]]{1,9}(@2x)?.(jpg|jpeg|png|eps|gif)\" -type f\n cd $THE_PWD\n}\n</code></pre>\n\n<p>Remove all resized images.</p>\n\n<pre><code># Remove all resized images.\n# Usage: lrimgrm site.ext\nfunction lrimgrm() {\n clear\n THE_PWD=$PWD\n cd ~\n cd /var/www/\"$1\"/htdocs/wp-content/uploads/\n find . -regextype posix-extended -regex \".*-[[:digit:]]{1,9}x[[:digit:]]{1,9}(@2x)?.(jpg|jpeg|png|eps|gif)\" -type f -exec rm {} \\;\n cd $THE_PWD\n}\n</code></pre>\n\n<p>Be careful here. Keep your backups ready.</p>\n\n<p>P.S. My server has an NGINX setup which is why the site paths are <code>/var/www/\"$1\"/htdocs/</code> $1 being the parameter which is the site name. You can modify it to match your path.</p>\n"
},
{
"answer_id": 351348,
"author": "mwdev",
"author_id": 177454,
"author_profile": "https://wordpress.stackexchange.com/users/177454",
"pm_score": 3,
"selected": false,
"text": "<p>You can easily delete files using \"find\" command on linux, just needed to do the same thing. You can run the following in bash console:</p>\n\n<pre><code>cd /var/www/wordpress/wp-content/uploads\nfind -type f -regex '.*[0-9]+x[0-9]+.\\(jpg\\|png\\|jpeg\\)$' -delete\n</code></pre>\n"
},
{
"answer_id": 357854,
"author": "bristweb",
"author_id": 182084,
"author_profile": "https://wordpress.stackexchange.com/users/182084",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a way you can do this programmatically (for the most part). </p>\n\n<p>1: Set your media sizes (ex: thumbnail 300x300 and the rest 0x0 to keep WP from generating anything other than thumbnail.)</p>\n\n<p>2: Generate the new images with <a href=\"https://developer.wordpress.org/cli/commands/media/regenerate/\" rel=\"nofollow noreferrer\">WP CLI</a>, but do not delete any of the old sizes until it's ready. Or if you really are not keeping any resized images, skip this.</p>\n\n<pre><code>$ wp media regenerate --skip-delete\n</code></pre>\n\n<p>3: Search replace image paths with <a href=\"https://developer.wordpress.org/cli/commands/search-replace/\" rel=\"nofollow noreferrer\">WP CLI</a>. This updates posts and pages content so you don't have broken images on your site.</p>\n\n<p>Your regular expression will need to be something like the following. </p>\n\n<pre><code>(\\/wp-content\\/uploads\\/)([0-9]{4}\\/[0-9]{2}\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/7xo9Ypi1ESh57l6P.png\" alt=\"Regular expression visualization\"></p>\n\n<p><a href=\"https://www.debuggex.com/r/7xo9Ypi1ESh57l6P\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p>And would have the following wp search-replace:</p>\n\n<pre><code>$ wp search-replace '(\\/wp-content\\/uploads\\/)([0-9]{4}\\/[0-9]{2}\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})' '$1$2$3$5' --regex\n</code></pre>\n\n<p>Or you might have a different upload folder or don't have the year/month folders included. In that case you'd have slightly different regex</p>\n\n<pre><code>(\\/app\\/uploads\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/aHBmaFpz_z1UiT2W.png\" alt=\"Regular expression visualization\"></p>\n\n<p><a href=\"https://www.debuggex.com/r/aHBmaFpz_z1UiT2W\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p>and you'd run</p>\n\n<pre><code>$ wp search-replace '(\\/app\\/uploads\\/)(.*)(-[0-9]{1,5}x[0-9]{1,5})(\\..{2,4})' '$1$2$4' --regex\n</code></pre>\n\n<p><strong>Just to be clear: this would make your load times horrible - all images would serve from their full-size file and not the smaller image.</strong>\nIt would be a good idea perhaps to swap your image server with an image processing API / CDN so these problems go away :)</p>\n\n<p>If you are at least keeping one thumbnail, like the 300x300 example I gave, you'd need to run a little different regex:</p>\n\n<pre><code>(\\/wp-content\\/uploads\\/)(.*)(-(?!(?:72))[0-9]{1,5}x(?!(?:72))[0-9]{1,5})(\\..{2,4})\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/scJ10BzDNlGzVdk_.png\" alt=\"Regular expression visualization\"></p>\n\n<p><a href=\"https://www.debuggex.com/r/scJ10BzDNlGzVdk_\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p>Then you run WP CLI twice. The first swaps all the images that aren't the 72x72 thumbnail. The latter changes all the 72x72 thumbnails to the new 300x300 thumbnail</p>\n\n<pre><code>$ wp search-replace '(\\/wp-content\\/uploads\\/)(.*)(-(?!(?:72))[0-9]{1,5}x(?!(?:72))[0-9]{1,5})(\\..{2,4})' '$1$2$4' --regex\n\n$ wp search-replace '(\\/wp-content\\/uploads\\/)(.*)(-72x72)(\\..{2,4})' '$1$2-300x300$4' --regex\n</code></pre>\n\n<p>4: now delete all unused images:</p>\n\n<pre><code>$ wp media regenerate\n</code></pre>\n"
},
{
"answer_id": 375646,
"author": "Brent Pickrel",
"author_id": 195387,
"author_profile": "https://wordpress.stackexchange.com/users/195387",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up using filezilla to connect via ftp. I then searched the uploads folder using the remote file search feature within Filezilla. I used regex in combinations to select all and delete. i.e. \\d\\d\\dx\\d\\d\\d.jpg or \\d\\dx\\d\\d.png or \\d\\d\\dx\\d\\d\\d\\d.gif. I kept using different combinations of the "\\d" to find either a 3 digit by 4 digit size of image or a 2 digit by 2 digit size of image.</p>\n"
},
{
"answer_id": 385093,
"author": "Fred",
"author_id": 203376,
"author_profile": "https://wordpress.stackexchange.com/users/203376",
"pm_score": 0,
"selected": false,
"text": "<p>I am no coder but this works - found it at this url\n<a href=\"https://crunchify.com/wordpress-tips-how-to-remove-redundant-image-sizes-and-files/\" rel=\"nofollow noreferrer\">https://crunchify.com/wordpress-tips-how-to-remove-redundant-image-sizes-and-files/</a></p>\n<p>ssh into your public_html</p>\n<p>Use the following (without the quotes) to find all the images of that nominated size\n"find . -name <em>-72x72.</em>"</p>\n<p>This line removes images of the nominated size\n"find . -name <em>-72x72.</em> | xargs rm -f"</p>\n<p>then just change the 72x72 to the next image size</p>\n<p>Removes a thousand images in one second - you will think it didn't work until you check your uploads and see they are gone.</p>\n"
},
{
"answer_id": 396943,
"author": "Vignesh PV",
"author_id": 152215,
"author_profile": "https://wordpress.stackexchange.com/users/152215",
"pm_score": 0,
"selected": false,
"text": "<p>I too faced the same problem and finally found the solution. It worked 100% for me. I have cleared nearly 10GB of files.</p>\n<p>The command lines below will remove currently resized images, including Retina versions so that we can correctly resize WordPress images per the new theme dimensions. And yes, we're using the command line, because I (Michael) am old school.</p>\n<pre><code>cd /home/example/public_html/wp-content/uploads\n\nfind . -regextype posix-extended -regex ".*-[[:digit:]]{2,4}x[[:digit:]]{2,4}(@2x)?.(jpg|jpeg|png|eps|gif)" -type f -exec rm {} \\;\n</code></pre>\n<p>Reference - <a href=\"https://www.axelerant.com/blog/remove-resize-wordpress-images\" rel=\"nofollow noreferrer\">https://www.axelerant.com/blog/remove-resize-wordpress-images</a></p>\n"
}
] |
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 = date('H:i');\n\n$args = array (\n 'post_type' => array( 'voucher' ),\n 'meta_query' => array(\n 'relation' => 'AND',\n array(\n 'key' => '_voucher_days_available',\n 'value' => $today,\n 'compare' => 'LIKE',\n 'type' => 'CHAR',\n ),\n array(\n 'key' => '_voucher_start_time',\n 'value' => $time_now,\n 'compare' => '>=',\n 'type' => 'date'\n ),\n array(\n 'key' => '_voucher_end_time',\n 'value' => $time_now,\n 'compare' => '<=',\n 'type' => 'date'\n ),\n ),\n);\n</code></pre>\n"
},
{
"answer_id": 240826,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>In addition to the suggestion by @AhmedMahdi to solve your problem, here's the narrower answer to your question: Nope, <code>key</code> cannot be an array. As you can see in the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow\">specs of WP_Meta_Query</a> <code>key</code> must be a string.</p>\n"
}
] |
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 beginning of your code:</p>\n\n<pre><code><?php\n/**\n* Plugin Name: My Plugin Name\n* Plugin URI: http://mypluginuri.com/\n* Description: A brief description about your plugin.\n* Version: 1.0 or whatever version of the plugin (pretty self explanatory)\n* Author: Plugin Author's Name\n* Author URI: Author's website\n* License: A \"Slug\" license name e.g. GPL12\n*/\n</code></pre>\n\n<p>Now you should name this file and your folder with the same name like:</p>\n\n<p><code>…/plugins/haroon-register-testimonial/haroon-register-testimonial.php</code></p>\n\n<p>Notice that I added \"haroon-\" prefix at the beginning of the folder and filename in order to make it's name unique, this is needed to work properly with other plugins by avoiding repeated names.</p>\n\n<p>Now you should add a readme.txt to inform users about any updates and the usage of your plugin. Is not needed but recommended.</p>\n\n<p>That's it! now you have a plugin!</p>\n\n<p>Read more on the <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow\">Codex</a> and <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-a-wordpress-plugin\" rel=\"nofollow\">Here</a></p>\n\n<p>I think the 2nd create a custom post type as well.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 240847,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 0,
"selected": false,
"text": "<p>You can create a custom post type plugin of your choice and you have to follow the steps in order to create the successful plugin of your choice.</p>\n\n<p><strong>1. Step One:</strong></p>\n\n<p>You have to create a folder under the <code>wp-content->plugins->YOUR PLUGIN FOLDER</code>.</p>\n\n<p>(E.g) - In Our Exapmple we are going to create the plugin called <code>Destination_Category</code></p>\n\n<p>Folder Structure: <code>wp-content->plugins->Destination_Category</code>.</p>\n\n<p><strong>2. Step Two:</strong></p>\n\n<p>Inside that folder you have to create the file structure as follows.</p>\n\n<ol>\n<li>css(folder)</li>\n<li>images(folder)</li>\n<li>index.php</li>\n</ol>\n\n<p><strong>3. Step Three:</strong></p>\n\n<p>Open up the index.php and you have to add the copyrights and descriptions for the plugin.</p>\n\n<p>In our example we are going to create as Destination Category.</p>\n\n<pre><code><?php\n/*\nPlugin Name: Destination Category\nDescription: This plugin is used for the creation of the Custom Category for the Wordpress Destination Post type and it allows you to link the Category and the Sub Category using this plugin.\nVersion: 1.0\nAuthor: Naresh Kumar.P\nEmail: [email protected]\nLicense: NKPDC007\n*/\n?>\n</code></pre>\n\n<p>After creating this Structure you can see the plugin in the <code>Plugins</code> Menu at the WordPress Dashboard. You can see the Plugin Name, Description, Email and all the other details that you have provided.</p>\n\n<p><strong>4. Step Four:</strong></p>\n\n<p>In addition to the Step Three you have to <code>register the custom post type</code> with the code available for it and you are created with the plugin that you need.</p>\n\n<pre><code>//Creation of custom post type(Start)\nadd_action( 'init', 'create_destination_category' );\nfunction create_destination_category() \n{\n $args = array(\n 'labels' => array(\n 'name' => 'Destination Categories',\n 'singular_name' => 'Destination Category',\n 'add_new' => 'Add New',\n 'add_new_item' => 'Add New Destination Category',\n 'edit' => 'Edit',\n 'edit_item' => 'Edit Destination Category',\n 'new_item' => 'New Destination Category',\n 'view' => 'View',\n 'view_item' => 'View Destination Category',\n 'search_items' => 'Search Destination Category',\n 'not_found' => 'No Destination Categories found',\n 'not_found_in_trash' => 'No Destination Category found in Trash', \n ), \n 'menu_position' => 15,\n 'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ), \n 'menu_icon' => plugins_url( 'images/logo.png', __FILE__ ),\n 'public' => true \n );\n register_post_type( 'destination_category',$args); \n }//Creation of custom post type(End) \n</code></pre>\n\n<p>And one more step to go and that is you are now to activate the plugin that you have created and you will be getting the message as <code>Your plugin is successfully activated</code> and thus your plugin is successfully created.</p>\n\n<p>And onto the whole the entire index.php will look like the below code.</p>\n\n<p><strong>index.php</strong></p>\n\n<pre><code><?php\n/*\nPlugin Name: Destination Category\nDescription: This plugin is used for the creation of the Custom Category for the Wordpress Destination Post type and it allows you to link the Category and the Sub Category using this plugin.\nVersion: 1.0\nAuthor: Naresh Kumar.P\nEmail: [email protected]\nLicense: NKPDC007\n*/\n\n//Creation of custom post type(Start)\nadd_action( 'init', 'create_destination_category' );\nfunction create_destination_category() \n{\n $args = array(\n 'labels' => array(\n 'name' => 'Destination Categories',\n 'singular_name' => 'Destination Category',\n 'add_new' => 'Add New',\n 'add_new_item' => 'Add New Destination Category',\n 'edit' => 'Edit',\n 'edit_item' => 'Edit Destination Category',\n 'new_item' => 'New Destination Category',\n 'view' => 'View',\n 'view_item' => 'View Destination Category',\n 'search_items' => 'Search Destination Category',\n 'not_found' => 'No Destination Categories found',\n 'not_found_in_trash' => 'No Destination Category found in Trash', \n ), \n 'menu_position' => 15,\n 'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ), \n 'menu_icon' => plugins_url( 'images/logo.png', __FILE__ ),\n 'public' => true \n );\n register_post_type( 'destination_category',$args); \n }//Creation of custom post type(End) \n?>\n</code></pre>\n"
},
{
"answer_id": 240879,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>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.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n\n<p>Then to address post links on the front (so they see www.example.com/testimoinals/1 instead of www.example.com/haroon-testimonials/1\nyou'll need to use a re-write back to testimonials:</p>\n\n<pre><code> 'rewrite' => array('slug' => 'locations'),\n</code></pre>\n\n<p>Here is a sample code i use:</p>\n\n<pre><code><?php\n/**\n * @package rt_create_cpt\n * @version 1.0\n */\n/*\nPlugin Name: Custom Post Creation by RT\nDescription: A Plugin to create CPT \nAuthor: RT, Inc\nVersion: 3.4\nAuthor URI: http://\n*/\n\nadd_action( 'init', 'rt_custom_post' );\nfunction rt_custom_post() {\n register_post_type( 'rt_locations',\n array(\n 'labels' => array(\n 'name' => __( 'Locations' ),\n 'singular_name' => __( 'Location' ),\n 'add_new' => _x('Add New Location', 'Location'),\n 'add_new_item' => __(\"Add New Location\"),\n 'edit_item' => __(\"Edit This Location\"),\n 'new_item' => __(\"New Location\"),\n 'view_item' => __(\"View Location\"),\n 'search_items' => __(\"Search in Locations\"),\n 'uploaded_to_this_item' => __(\"Used for image for this Location\"),\n 'featured_image' => __(\"Location Image\"),\n 'set_featured_image' => __(\"Set Location Image\"),\n 'remove_featured_image' => __(\"Remove Location Image\"),\n 'use_featured_image' => __(\"Use Location Image\"),\n 'not_found' => __('No Locations'),\n 'not_found_in_trash' => __('No Locations found in Trash')\n\n ),\n 'public' => true,\n 'has_archive' => true,\n 'menu_icon' => 'dashicons-store',\n 'supports' => array('title','author','thumbnail','editor'),\n 'rewrite' => array('slug' => 'locations'),\n )\n );\n}\n\n\nfunction rt_rewrite_flush() {\n // First, we \"add\" the custom post type via the above written function.\n // Note: \"add\" is written with quotes, as CPTs don't get added to the DB,\n // They are only referenced in the post_type column with a post entry, \n // when you add a post of this CPT.\n rt_custom_post();\n\n // ATTENTION: This is *only* done during plugin activation hook in this example!\n // You should *NEVER EVER* do this on every page load!!\n flush_rewrite_rules();\n}\nregister_activation_hook( __FILE__, 'rt_rewrite_flush' );\n\n?>\n</code></pre>\n\n<p>you'll just want to put your code function in and then change the rewrite rule to match your code!</p>\n"
}
] |
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_excerpt_field');\n\nfunction remove_page_excerpt_field(){\n remove_meta_box( 'pexeto-meta-page-boxes' , 'page' , 'normal' ); \n}\n</code></pre>\n\n<p>or just <code>remove_action('the_function_used_by_the_theme_to_add_metabox', 10, 1);</code> use the same priority and args number of the add_action.</p>\n"
},
{
"answer_id": 240848,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Remove WordPress Meta Boxes</strong></p>\n\n<p>You have to make use of the function called <code>remove meta box</code>.</p>\n\n<p><strong>Description:</strong>\nRemoves 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. </p>\n\n<blockquote>\n <p>Steps to remove the meta box from WordPress Dashboard:</p>\n</blockquote>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>Anyway, the two ways I’ve often seen it done is when:</p>\n\n<p>Developers look for the check boxes under the Screen Options and then trigger the click event.</p>\n\n<p>Developers sniff out the meta boxes ID and then use <code>jQuery’s hide()</code> method to hide the meta boxes from the page.</p>\n\n<p>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.</p>\n\n<p>Unless a hook exists.</p>\n\n<p>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.</p>\n\n<p>Specifically, we need to ask ourselves:</p>\n\n<p>Given what I need to do, is there a hook that makes this available?</p>\n\n<p>And this is this case (and many, many cases), there is. We can take advantage of the <code>default_hidden_meta_boxes</code> hook. </p>\n\n<p><strong>Using The Hook</strong></p>\n\n<p>The function accepts two arguments:</p>\n\n<ol>\n<li>An array of meta boxes that should be hidden</li>\n<li>The current screen being displayed</li>\n</ol>\n\n<p>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.</p>\n\n<p>So let’s say that we have a custom post type called <code>acme_post_type</code> and we want to hide the Categories, Author, Post Excerpt, and Slug meta box.</p>\n\n<pre><code><?php\nadd_action( 'default_hidden_meta_boxes', 'acme_remove_meta_boxes', 10, 2 );\n/**\n * Removes the category, author, post excerpt, and slug meta boxes.\n *\n * @since 1.0.0\n *\n * @param array $hidden The array of meta boxes that should be hidden for Acme Post Types\n * @param object $screen The current screen object that's being displayed on the screen\n * @return array $hidden The updated array that removes other meta boxes\n */\nfunction acme_remove_meta_boxes( $hidden, $screen ) {\n if ( 'acme_post_type' == $screen->id ) {\n $hidden = array(\n 'acme_post_type_categorydiv',\n 'authordiv',\n 'postexcerpt',\n 'slugdiv'\n );\n\n }\n return $hidden; \n}\n</code></pre>\n\n<p>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.</p>\n\n<p>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. </p>\n\n<blockquote>\n <p>Another Example of how to remove the meta box in WordPress.</p>\n</blockquote>\n\n<pre><code>// REMOVE POST META BOXES\nfunction remove_my_post_metaboxes() {\nremove_meta_box( 'authordiv','post','normal' ); // Author Metabox\nremove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Status Metabox\nremove_meta_box( 'commentsdiv','post','normal' ); // Comments Metabox\nremove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox\nremove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox\nremove_meta_box( 'revisionsdiv','post','normal' ); // Revisions Metabox\nremove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox\nremove_meta_box( 'trackbacksdiv','post','normal' ); // Trackback Metabox\n}\nadd_action('admin_menu','remove_my_post_metaboxes');\n</code></pre>\n\n<p>Place the following code in your functions file <code>(Appearance > Editor > Theme Functions – functions.php)</code>.</p>\n\n<p>Placing that code should remove all the meta boxes below the post editor and give you a nice, clean look.</p>\n"
}
] |
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=\"nofollow\">query for your posts which have a the associated custom taxonomy term(s)</a>, </p>\n\n<pre><code>$args = array(\n 'post_type' => 'football_fixture',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'competition',\n 'field' => 'term_id',\n 'terms' => array($term_id), //put more term ids if required\n ),\n ),\n );\n$query = new WP_Query( $args );\nif($query->have_posts()){\n while($query->have_posts()){\n $query->the_post();\n echo '<li>' . get_the_title( $query->post->ID ) . '</li>';\n }\n\n // Restore original Post Data once finished, IMPORTANT\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>now, you need to get the <code>$term_id</code> of your term to make sure the above query works, in your example you have the following line at the top,</p>\n\n<pre><code>$term_id = get_queried_object()->term_id;\n</code></pre>\n\n<p>however, <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow\">the function <code>get_queried_object</code></a> will only return the the term_id for a taxonomy template, what you are trying to do is display this in a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/#file-organization-of-page-templates\" rel=\"nofollow\">page template</a>, as your page header starts with,</p>\n\n<pre><code> <?php\n /**\n * Template Name: Fixture -- this indicates that you are building a page template\n</code></pre>\n\n<p>so you will not have access to any term id. You have 2 options to get the results you are looking for, </p>\n\n<ul>\n<li>hard code the term ID in your page template, or pass it as an argument in the URL attribute</li>\n<li>create a <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#custom-taxonomies\" rel=\"nofollow\">taxonomy archive template</a>, so you can use your custom taxonomy terms directly into your menu, users will click the term link and WordPress will parse the term id to your page.</li>\n</ul>\n\n<h2>Putting it all together,</h2>\n\n<p>I would recommend the second option. Create a new file called <code>taxonomy-competition.php</code> and save it in your root theme or child theme folder with the following content,</p>\n\n<pre><code><?php\n/**\n * Taxonomy 'competition' archive template\n */\nget_header();\n\n$term_id = get_queried_object()->term_id;\n$args = array(\n 'post_type' => 'football_fixture',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'competition',\n 'field' => 'term_id',\n 'terms' => array($term_id), //put more term ids if required\n ),\n ),\n );\n$query = new WP_Query( $args );\n\necho '<ul>';\nif($query->have_posts()){\n while($query->have_posts()){\n $query->the_post();\n echo '<li>' . get_the_title( $query->post->ID ) . '</li>';\n }\n\n // Restore original Post Data once finished, IMPORTANT\n wp_reset_postdata();\n}\necho '</ul>';\n\nget_footer();\n</code></pre>\n\n<p>This will display the list post titles which are organised under the given term.</p>\n\n<p>To use this on the front end, add the custom taxonomy <code>competition</code> terms you want to display your <a href=\"http://www.wpbeginner.com/beginners-guide/how-to-add-navigation-menu-in-wordpress-beginners-guide/\" rel=\"nofollow\">navigational menu in the dashboard</a>. If you are unable to see your taxonomy menu option, make sure it is selected in the 'Screen Options' tab at the top of the dashboard page.</p>\n"
},
{
"answer_id": 240864,
"author": "C Sabhar",
"author_id": 103830,
"author_profile": "https://wordpress.stackexchange.com/users/103830",
"pm_score": 1,
"selected": true,
"text": "<p>In your custom templates, First you have to fetch all terms for your custom post type.</p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\">get_terms</a> to retrive terms in taxonomy</p>\n\n<p>If you are using wordpress prior to 4.5</p>\n\n<pre><code>$terms = get_terms( 'competition' , array(\n 'hide_empty' => false\n) );\n</code></pre>\n\n<p>OR if you are using wordpress prior to 4.5.0 or later</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'competition',\n 'hide_empty' => false,\n) ); \n</code></pre>\n\n<p>Next Build Term name lists:</p>\n\n<pre><code>$termNames = array();\n$count = count( $terms );\nif ( $count > 0 ) {\n foreach ( $terms as $term ) {\n $termNames[] = $term->name;\n }\n}\n</code></pre>\n\n<p>Next loop trough each terms and query posts for the current terms & then run the loop:</p>\n\n<pre><code>foreach($termNames as $termName) :\n\n$args = array(\n 'post_type' => 'football_fixture',\n 'competition' => $termName,\n 'order' => 'ASC',\n);\nquery_posts( $args );\nif(have_posts()): ?>\n <div class=\"<?php echo $col; ?>\">\n <h2><?php echo $termName; ?></h2>\n <?php while(have_posts()): the_post(); ?>\n <div id=\"post-<?php the_ID(); ?>\" <?php post_class(); ?>>\n <?php\n $id = get_the_ID();\n $date = rwmb_meta( 'pb_match_date','', $post->ID);\n $time = rwmb_meta( 'pb_match_time','', $post->ID );\n $competition = rwmb_meta( 'pb_match_competition_cats','', $post->ID );\n $team_a = get_post_meta( $post->ID, 'match_details_home_team', true );\n $team_b = get_post_meta( $post->ID, 'match_details_away_team', true );\n\n ?>\n <div class=\"fixture-item\">\n <div class=\"row\">\n <div class=\"col-xs-4\">\n <div class=\"media\">\n <div class=\"media-body\">\n <h4><?php echo $team_a; ?></h4>\n </div>\n </div>\n </div>\n\n <div class=\"col-xs-4 match-time\">\n <i class=\"fa fa-clock-o\"></i> <?php echo $time; ?>\n </div>\n\n <div class=\"col-xs-4\">\n <div class=\"media\">\n <div class=\"media-body\">\n <h4 class=\"pull-right\"><?php echo $team_b; ?></h4>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div><!--/#post-->\n <?php endwhile; ?>\n\n <?php \n wp_reset_query();\n ?>\n</code></pre>\n\n<p>\n </p>\n\n\n"
}
] |
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 permalinks. If you have recently changed the structure of your URLs, simply by going to <strong>Settings</strong> > <strong>Permalinks</strong> and click <strong>Save Changes</strong> might resolve this issue.</p>\n"
},
{
"answer_id": 240931,
"author": "Arcath",
"author_id": 85357,
"author_profile": "https://wordpress.stackexchange.com/users/85357",
"pm_score": 1,
"selected": true,
"text": "<p>I found the answer.</p>\n\n<p>It was only for post-formats on pages. The issue was that I needed to also register the taxonomy <code>post_format</code> on pages as well in the init action.</p>\n\n<p>I have updated the wiki page to reflect this.\n<a href=\"https://codex.wordpress.org/Post_Formats#Adding_Post_Type_Support\" rel=\"nofollow\">https://codex.wordpress.org/Post_Formats#Adding_Post_Type_Support</a></p>\n\n<pre><code>// add post-formats to post_type 'page'\nadd_action('init', 'my_theme_slug_add_post_formats_to_page', 11);\n\nfunction my_theme_slug_add_post_formats_to_page(){\n add_post_type_support( 'page', 'post-formats' );\n register_taxonomy_for_object_type( 'post_format', 'page' );\n}\n</code></pre>\n"
}
] |
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 = array(\n'post_type' => 'loan-offers',\n'meta_query' => array(\n relation' => 'OR',\n array(\n 'key' => 'amount',\n 'value' => $amount,\n 'compare' => '>='\n ),\n\n array(\n 'key' => 'time',\n 'value' => $months,\n 'compare' => '>='\n )\n));\n</code></pre>\n"
},
{
"answer_id": 240860,
"author": "Naresh Kumar P",
"author_id": 101025,
"author_profile": "https://wordpress.stackexchange.com/users/101025",
"pm_score": 2,
"selected": true,
"text": "<p>In order to deliver the amount variable to be less than 25000 you need to check the query with the operator called <code><=</code> but you have tested it with <code>>=</code> in your query.</p>\n<p><strong>Note:</strong> There are several comparison operators available</p>\n<pre><code>= equals\n!= does not equal\n> greater than\n>= greater than or equal to\n< less than\n<= less than or equal to\n</code></pre>\n<blockquote>\n<p>But in your query you have misjudged the query and used. You have to use <code><=</code> rather you have used <code>>=</code></p>\n</blockquote>\n<ol>\n<li><code><=</code> - Less than or Equal to</li>\n<li><code>>=</code> - Greater than or Equal to</li>\n</ol>\n<blockquote>\n<p>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</p>\n</blockquote>\n<pre><code>$args = array(\n'post_type' => 'loan-offers',\n'meta_query' => array(\n relation => 'AND', // This can be AND / OR depending on your choice\n array(\n 'key' => 'amount',\n 'value' => $amount,\n 'compare' => '<='\n ),\n\n array(\n 'key' => 'time',\n 'value' => $months,\n 'compare' => '>='\n )\n));\n</code></pre>\n<p><code>LIKE</code> and <code>NOT LIKE</code> are <code>SQL operators</code> that let you add in wild-card symbols, so you could have a meta query that looks like this:</p>\n<pre><code>array( \n 'key' => 'name', \n 'value' => 'Pat', \n 'compare' => 'LIKE'\n)\n</code></pre>\n<blockquote>\n<p>Get Posts Within a Given Range of Numeric Meta Values</p>\n</blockquote>\n<pre><code>// the loan-offers is more than 10000 and less than 25000\n$rd_args = array(\n 'post_type' => 'loan-offers',\n 'meta_query' => array(\n array(\n 'key' => 'amount',\n 'value' => array( 10000, 25000 ),\n 'type' => 'numeric',\n 'compare' => 'BETWEEN'\n )\n )\n);\n$rd_query = new WP_Query( $rd_args );\n</code></pre>\n<p>You can use BETWEEN operator for getting the output as required by you.</p>\n"
},
{
"answer_id": 240863,
"author": "AppleTattooGuy",
"author_id": 102637,
"author_profile": "https://wordpress.stackexchange.com/users/102637",
"pm_score": 0,
"selected": false,
"text": "<p>Found the issue, was missing the 'type' => 'NUMERIC' as follows:</p>\n\n<pre><code>$args = array(\n'post_type' => 'loan-offers',\n'meta_query' => array(\n 'relation' => 'AND',\n array(\n 'key' => 'amount',\n 'value' => $amount,\n 'compare' => '>=',\n 'type' => 'NUMERIC'\n ),\n\n array(\n 'key' => 'time',\n 'value' => $months,\n 'compare' => '>=',\n 'type' => 'NUMERIC'\n )\n));\n</code></pre>\n"
}
] |
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></p>\n\n<ol>\n<li><code><?php global $post; ?></code> - Initialization at the start of the loop</li>\n</ol>\n\n<blockquote>\n <p>After setting up the post data your query becomes like normal <code>Wp_Query</code> so that you can get the <code>permalink()</code> in normal method itself using <code>the_permalink()</code> instead of <code>get_permalink($post->id)</code>.</p>\n</blockquote>\n\n<p>Since your posts is behaving in the normal method you need to make the following changes.</p>\n\n<ol>\n<li>Remove the <code>get_permalink()</code> from the code</li>\n<li>Remove the echo tag in roder to display the permalink</li>\n</ol>\n\n<p>Replace your code with the current one.</p>\n\n<p><strong>Wherever you have used</strong> </p>\n\n<pre><code><?php echo get_permalink($post->ID); ?>\n</code></pre>\n\n<p><strong>Replace it with</strong></p>\n\n<pre><code><?php the_permalink(); ?>\n</code></pre>\n\n<p>And your final code will look like as follows.</p>\n\n<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\" ); ?>\n<?php if( $posts ) : ?>\n<?php global $post; ?>\n<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>\n<div class=\"post homepage\">\n <a href=\"<?php the_permalink(); ?>\"><img src=\"<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo $feat_image;?>\" /></a>\n <h3 class=\"homepage-post-title\"><a href=\"<?php the_permalink(); ?>\"><?php echo $post->post_title; ?></a></h3>\n <a class=\"read-more-link\" href=\"<?php the_permalink(); ?>\">Read More</a>\n</div>\n<?php endforeach; ?>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 240870,
"author": "Web Guy Mofassel",
"author_id": 103832,
"author_profile": "https://wordpress.stackexchange.com/users/103832",
"pm_score": -1,
"selected": false,
"text": "<p>Using <code><?php global $post; ?></code> on top of your query should do the magic.</p>\n\n<p>Even you can use \n <code><?php echo get_permalink(get_the_ID()); ?></code> \ninstead of using\n <code><?php echo get_permalink($post->ID); ?></code></p>\n\n<p>Better and easy option is to use <code><?php the_permalink(); ?></code></p>\n"
},
{
"answer_id": 313650,
"author": "Go Mo",
"author_id": 150222,
"author_profile": "https://wordpress.stackexchange.com/users/150222",
"pm_score": 0,
"selected": false,
"text": "<p>Had the similar issue, after creating category.php. My the_permalink() was not working, and it was returning just the same category instead going to the single post. It turned out, I had things modified in the permalinks menu of the admin panel. I had chosen \"custom structure\" and had /%groups% added, which rang me a bell that I might need to add /%postname% to it and it worked as /%groups%/%postname%.\nIn your specific case scenario, you should use the /%post_id% at the end of that custom structure option. </p>\n"
}
] |
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></p>\n\n<ol>\n<li><code><?php global $post; ?></code> - Initialization at the start of the loop</li>\n</ol>\n\n<blockquote>\n <p>After setting up the post data your query becomes like normal <code>Wp_Query</code> so that you can get the <code>permalink()</code> in normal method itself using <code>the_permalink()</code> instead of <code>get_permalink($post->id)</code>.</p>\n</blockquote>\n\n<p>Since your posts is behaving in the normal method you need to make the following changes.</p>\n\n<ol>\n<li>Remove the <code>get_permalink()</code> from the code</li>\n<li>Remove the echo tag in roder to display the permalink</li>\n</ol>\n\n<p>Replace your code with the current one.</p>\n\n<p><strong>Wherever you have used</strong> </p>\n\n<pre><code><?php echo get_permalink($post->ID); ?>\n</code></pre>\n\n<p><strong>Replace it with</strong></p>\n\n<pre><code><?php the_permalink(); ?>\n</code></pre>\n\n<p>And your final code will look like as follows.</p>\n\n<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\" ); ?>\n<?php if( $posts ) : ?>\n<?php global $post; ?>\n<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>\n<div class=\"post homepage\">\n <a href=\"<?php the_permalink(); ?>\"><img src=\"<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo $feat_image;?>\" /></a>\n <h3 class=\"homepage-post-title\"><a href=\"<?php the_permalink(); ?>\"><?php echo $post->post_title; ?></a></h3>\n <a class=\"read-more-link\" href=\"<?php the_permalink(); ?>\">Read More</a>\n</div>\n<?php endforeach; ?>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 240870,
"author": "Web Guy Mofassel",
"author_id": 103832,
"author_profile": "https://wordpress.stackexchange.com/users/103832",
"pm_score": -1,
"selected": false,
"text": "<p>Using <code><?php global $post; ?></code> on top of your query should do the magic.</p>\n\n<p>Even you can use \n <code><?php echo get_permalink(get_the_ID()); ?></code> \ninstead of using\n <code><?php echo get_permalink($post->ID); ?></code></p>\n\n<p>Better and easy option is to use <code><?php the_permalink(); ?></code></p>\n"
},
{
"answer_id": 313650,
"author": "Go Mo",
"author_id": 150222,
"author_profile": "https://wordpress.stackexchange.com/users/150222",
"pm_score": 0,
"selected": false,
"text": "<p>Had the similar issue, after creating category.php. My the_permalink() was not working, and it was returning just the same category instead going to the single post. It turned out, I had things modified in the permalinks menu of the admin panel. I had chosen \"custom structure\" and had /%groups% added, which rang me a bell that I might need to add /%postname% to it and it worked as /%groups%/%postname%.\nIn your specific case scenario, you should use the /%post_id% at the end of that custom structure option. </p>\n"
}
] |
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 this:</p>\n\n<p><code><a href=\"#\" name=\"metakey\" id=\"metakey\">Sony Lite</a></code></p>\n\n<p>I would add <code>onclick='getPostMeta()'</code> or similar. You may have to pass some data so the function knows which data to look up.</p>\n\n<p>Inside the new function, put the jQuery.ajax function. That should get you started on getting data into the metakey part of your page. </p>\n"
},
{
"answer_id": 240873,
"author": "mlimon",
"author_id": 64458,
"author_profile": "https://wordpress.stackexchange.com/users/64458",
"pm_score": 2,
"selected": true,
"text": "<p>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. </p>\n\n<p><strong><em>Q</em></strong>. <em>Why you used inline script ? On my opinion you should used external script file to do this.</em></p>\n\n<p>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.</p>\n\n<p>Here is an example, but I'm useing external js file for this and so you just have to register.</p>\n\n<pre><code>/**\n * Add js file with Enqueues scripts.\n */\nfunction wpse_scripts() {\n\n wp_enqueue_script( 'wpse-ajax-init', get_stylesheet_directory_uri() . '/js/wpse-ajax-init.js', array( 'jquery' ), '1.0', true );\n wp_localize_script( 'wpse-ajax-init', 'ajaxwpse', array(\n 'ajaxurl' => admin_url( 'admin-ajax.php' )\n ));\n\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_scripts' );\n</code></pre>\n\n<p>And now change you title markup that you fetch post title. </p>\n\n<pre><code>// the ajax function\nadd_action('wp_ajax_data_fetch' , 'data_fetch');\nadd_action('wp_ajax_nopriv_data_fetch','data_fetch');\nfunction data_fetch(){\nif ( esc_attr( $_POST['keyword'] ) == null ) { die(); }\n$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );\nif( $the_query->have_posts() ) :\nwhile( $the_query->have_posts() ): $the_query->the_post(); ?>\n\n <h2><a href=\"#\" name=\"metakey\" id=\"<?php the_ID(); ?>\"><?php the_title();?></a> </h2>\n\n<?php endwhile;\nwp_reset_postdata(); \nendif;\ndie();\n}\n</code></pre>\n\n<p>I'm here just changed <code><h2><a href=\"#\" name=\"metakey\" id=\"metakey\"><?php the_title();?></a> </h2></code> to <code><h2><a href=\"#\" name=\"metakey\" id=\"<?php the_ID(); ?>\"><?php the_title();?></a> </h2></code> because you need to grab the ID of the title dynamically.</p>\n\n<p>After doing that add below code on your <code>wpse-ajax-init.js</code> that you just register and hook with <code>admin-ajax.php</code>.</p>\n\n<pre><code>(function ($) {\n $(\"#datafetch\").on('click', 'a', function(e) {\n e.preventDefault();\n\n $('#keyword').delay(100).attr('value', '');\n $(this).delay(100).hide();\n\n $.ajax({\n url: ajaxwpse.ajaxurl,\n type: 'post',\n data: { \n action: 'data_fetchmeta', \n ID: $(this).attr('id')\n },\n success: function(data) {\n $('#viewspec').html( data );\n }\n });\n });\n})(jQuery);\n</code></pre>\n\n<p>And finally changed your <code>data_fetchmeta()</code> function query like this</p>\n\n<pre><code>add_action('wp_ajax_data_fetchmeta' , 'data_fetchmeta');\nadd_action('wp_ajax_nopriv_data_fetchmeta','data_fetchmeta');\nfunction data_fetchmeta(){\n $ID = esc_attr( $_POST['ID'] ); ?> \n <p>\n <?php echo get_post_meta( $ID, 'brand', true );?>\n <?php echo get_post_meta( $ID, 'price', true );?>\n <?php echo get_post_meta( $ID, 'cpu', true );?>\n <?php echo get_post_meta( $ID, 'ram', true );?>\n </p>\n <?php die();\n}\n</code></pre>\n\n<p>You can see, I just grab the dynamic id and used to display post meta.</p>\n\n<p>Hope it make sense to you.</p>\n"
},
{
"answer_id": 240880,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>If you use a event handler when user click on your link, you can remove the onClick event.</p>\n\n<p>the a tag must look like this to make it work with this method (assuming your loop has $post).</p>\n\n<p><code><a href=\"#\" data-id=\"<?php echo $post->ID;?>\" name=\"metakey\" id=\"metakey\"><?php echo $post->post_title;?></a></code></p>\n\n<p>the js :</p>\n\n<pre><code>$('a #metakey').on('click',function(e){\n e.preventDefault();\n var post_id = e.target.dataset.id\n data = {\n action: 'data_fetchmeta', \n sel_action: 'show_metafield',\n post_id: post_id,\n }\n $.post(ajaxurl, data, function(response) {\n var json = $.parseJSON(response);\n $('#viewspec').html(json.metakey);\n });\n\n});\n</code></pre>\n\n<p>the callback function</p>\n\n<pre><code>function data_fetchmeta(){\n if(isset($_POST['list_action'])){\n $action = $_POST['list_action'];\n }\n $action_params = array();\n parse_str($_POST['data'], $action_params);\n\n switch ($action){\n\n case 'show_metafield':\n ob_start(); // not necessary if you make a single string for $ result\n\n echo get_post_meta( $_POST['id'], 'brand', true );\n echo '<br/>;\n echo get_post_meta( $_POST['id'], 'price', true );\n echo '<br/>;\n echo get_post_meta( $_POST['id'], 'cpu', true );\n echo '<br/>;\n echo get_post_meta( $_POST['id'], 'ram', true );\n\n $result = ob_get_clean();\n echo json_encode(array(\n 'metakey' =>$result\n )\n );\n\n\n exit();\n break;\n default:\n break;\n\n}\n</code></pre>\n\n<p>There is many ways to do it, I hope this one helps you.</p>\n"
}
] |
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><code>add_action(\"login_form_lostpassword\", function () {\n\n echo \"on the lostpassword page\";\n exit();\n\n});\n</code></pre>\n\n<p>instead of the <code>echo</code>, redirect to your instructions page</p>\n"
},
{
"answer_id": 240886,
"author": "Ahmed Fouad",
"author_id": 102371,
"author_profile": "https://wordpress.stackexchange.com/users/102371",
"pm_score": 2,
"selected": true,
"text": "<p>This is straightforward.</p>\n\n<ol>\n<li><p>Hook on init to detect the lostpassword page</p></li>\n<li><p>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</p></li>\n<li><p>In your custom page add the link to lost password page including the extra parameter we set to skip the redirection.</p>\n\n<pre><code>add_action( 'init', 'lostpassword_instructions' );\n\nfunction lostpassword_instructions() {\n\n\n global $pagenow;\n\n if ( $pagenow == 'wp-login.php' && \n isset( $_REQUEST[ 'action' ] ) && \n $_REQUEST[ 'action' ] == 'lostpassword' && \n ! isset( $_REQUEST[ 'skip' ] )\n ) {\n\n exit( wp_redirect( 'http://domain.com/lost-password-instructions' ) );\n\n }\n\n}\n</code></pre></li>\n</ol>\n\n<p>Now on your custom page, something like that should work:</p>\n\n<pre><code>$url = 'http://domain.com/wp-login.php?action=lostpassword&skip=true';\n</code></pre>\n"
}
] |
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 correct locale and that \"decline months names: on or off\" is translated as \"on\" in your locale), you can <em>\"force\"</em> genitive case, by making a generic wrap function based on the <code>wp_maybe_decline_date()</code>. </p>\n\n<p>I have tested and used this, in order to overcome the <code>wp_maybe_decline_date()</code> regex that ,matches formats like <code>'j F Y'</code> or <code>'j. F'</code>, while I wanted to use <code>'l j F Y'</code></p>\n\n<p>Example use case:</p>\n\n<p>In our theme <code>functions.php</code> we define the wrapper function like:</p>\n\n<pre><code>/**\n * [multi_force_use_genitive_month_date]\n * Call this to force genitive use case for months in date translation\n * @param string $date Formatted date string.\n * @return string The date, declined if locale specifies it.\n */\nfunction multi_force_use_genitive_month_date( $date ) {\n global $wp_locale;\n\n // i18n functions are not available in SHORTINIT mode\n if ( ! function_exists( '_x' ) ) {\n return $date;\n }\n\n /* translators: If months in your language require a genitive case,\n * translate this to 'on'. Do not translate into your own language.\n */\n if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {\n // Match a format like 'j F Y' or 'j. F'\n $months = $wp_locale->month;\n $months_genitive = $wp_locale->month_genitive;\n\n foreach ( $months as $key => $month ) {\n $months[ $key ] = '# ' . $month . '( |$)#u';\n }\n\n foreach ( $months_genitive as $key => $month ) {\n $months_genitive[ $key ] = ' ' . $month . '$1';\n }\n\n $date = preg_replace( $months, $months_genitive, $date );\n }\n\n // Used for locale-specific rules\n $locale = get_locale();\n\n return $date;\n}\n</code></pre>\n\n<p>Then, in our template file where we want the genitive case to appear, we wrap the <code>date_i18n()</code>, like:</p>\n\n<pre><code><?php echo multi_force_use_genitive_month_date( date_i18n( 'l j F Y' ) ); ?>\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 377404,
"author": "skwrn",
"author_id": 196422,
"author_profile": "https://wordpress.stackexchange.com/users/196422",
"pm_score": 0,
"selected": false,
"text": "<p>Updated, working version based on the code from @Cubakos:</p>\n<pre><code>function multi_force_use_genitive_month_date( $date ) {\n global $wp_locale;\n\n $months = $wp_locale->month;\n $months_genitive = $wp_locale->month_genitive;\n\n $date = str_replace( $months, $months_genitive, $date );\n\n return $date;\n}\n</code></pre>\n<p>Usage in posts loop</p>\n<pre><code><?= multi_force_use_genitive_month_date(get_the_date()); ?>\n</code></pre>\n"
}
] |
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 correct locale and that \"decline months names: on or off\" is translated as \"on\" in your locale), you can <em>\"force\"</em> genitive case, by making a generic wrap function based on the <code>wp_maybe_decline_date()</code>. </p>\n\n<p>I have tested and used this, in order to overcome the <code>wp_maybe_decline_date()</code> regex that ,matches formats like <code>'j F Y'</code> or <code>'j. F'</code>, while I wanted to use <code>'l j F Y'</code></p>\n\n<p>Example use case:</p>\n\n<p>In our theme <code>functions.php</code> we define the wrapper function like:</p>\n\n<pre><code>/**\n * [multi_force_use_genitive_month_date]\n * Call this to force genitive use case for months in date translation\n * @param string $date Formatted date string.\n * @return string The date, declined if locale specifies it.\n */\nfunction multi_force_use_genitive_month_date( $date ) {\n global $wp_locale;\n\n // i18n functions are not available in SHORTINIT mode\n if ( ! function_exists( '_x' ) ) {\n return $date;\n }\n\n /* translators: If months in your language require a genitive case,\n * translate this to 'on'. Do not translate into your own language.\n */\n if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {\n // Match a format like 'j F Y' or 'j. F'\n $months = $wp_locale->month;\n $months_genitive = $wp_locale->month_genitive;\n\n foreach ( $months as $key => $month ) {\n $months[ $key ] = '# ' . $month . '( |$)#u';\n }\n\n foreach ( $months_genitive as $key => $month ) {\n $months_genitive[ $key ] = ' ' . $month . '$1';\n }\n\n $date = preg_replace( $months, $months_genitive, $date );\n }\n\n // Used for locale-specific rules\n $locale = get_locale();\n\n return $date;\n}\n</code></pre>\n\n<p>Then, in our template file where we want the genitive case to appear, we wrap the <code>date_i18n()</code>, like:</p>\n\n<pre><code><?php echo multi_force_use_genitive_month_date( date_i18n( 'l j F Y' ) ); ?>\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 377404,
"author": "skwrn",
"author_id": 196422,
"author_profile": "https://wordpress.stackexchange.com/users/196422",
"pm_score": 0,
"selected": false,
"text": "<p>Updated, working version based on the code from @Cubakos:</p>\n<pre><code>function multi_force_use_genitive_month_date( $date ) {\n global $wp_locale;\n\n $months = $wp_locale->month;\n $months_genitive = $wp_locale->month_genitive;\n\n $date = str_replace( $months, $months_genitive, $date );\n\n return $date;\n}\n</code></pre>\n<p>Usage in posts loop</p>\n<pre><code><?= multi_force_use_genitive_month_date(get_the_date()); ?>\n</code></pre>\n"
}
] |
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_registration_approved_hook', 10, 2);\n</code></pre>\n\n<p>... to run after the original <code>add_action</code>, but before the action triggers the function <code>um_post_registration_approved_hook</code></p>\n\n<p>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:</p>\n\n<pre><code>add_action( 'um_post_registration_approved_hook', 'remove_my_action', 9 );\nfunction remove_my_action(){\n remove_action('um_post_registration_approved_hook', 'um_post_registration_approved_hook', 10, 2);\n}\n</code></pre>\n\n<p>This is what you were trying, but the priority was the wrong way around. <code>11</code> runs after <code>10</code>.</p>\n"
},
{
"answer_id": 354921,
"author": "Zahid Ali Keerio",
"author_id": 179982,
"author_profile": "https://wordpress.stackexchange.com/users/179982",
"pm_score": 2,
"selected": false,
"text": "<pre><code>if(!function_exists('remove_my_action')){\n function remove_my_action(){\n remove_action( 'storefront_header', 'storefront_secondary_navigation', 30 );\n remove_action( 'storefront_header', 'storefront_header_container_close', 41 );\n remove_action( 'storefront_header', 'storefront_primary_navigation_wrapper', 42 );\n remove_action( 'storefront_header', 'storefront_primary_navigation', 50 );\n remove_action( 'storefront_header', 'storefront_primary_navigation_wrapper_close', 68 );\n }\n}\nadd_action( 'init', 'remove_my_action', 99);\n</code></pre>\n\n<p>Its Working fine I've tested by using this snippet.</p>\n\n<p>Note: In Remove Action the Priority of the action should be same as it is used inthe adding an action.</p>\n"
}
] |
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 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).</p>\n\n<p>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)</p>\n"
},
{
"answer_id": 241497,
"author": "Revious",
"author_id": 64590,
"author_profile": "https://wordpress.stackexchange.com/users/64590",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, having it installed as a PHP extension is needed to have it working with memcached, for example. It makes life really really easier.</p>\n"
}
] |
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>$args = array(\n'post_type'=>'post',\n'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => array( 'transportation' ),\n ),\n array(\n 'taxonomy' => 'tag',\n 'field' => 'slug',\n 'terms' => array( 'car' ),\n 'operator' => 'IN',\n ),\n);\n$posts = get_posts($args);\n</code></pre>\n\n<p><strong>EDIT :</strong> for a simple tax_query</p>\n\n<pre><code>'tax_query' => array(\n array(\n 'taxonomy' => 'tag',\n 'field' => 'slug',\n 'terms' => 'car'\n )\n)\n</code></pre>\n\n<p>You can grab more details and it for your case here <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters</a></p>\n\n<p>This will not get the posts tag 'car' and add category 'transportation' to them, but you need first to get posts.\nWith this result you can loop through it and use <code>wp_set_object_terms( $object_id, $terms, $taxonomy, $append );</code> in this loop to add your category to the tagged posts.</p>\n\n<pre><code>foreach($posts as $post){\n $append = true; // If true, terms will be appended to the object. If false, terms will replace existing terms\n // make some verif that's better\n wp_set_object_terms($post->ID, 'transportation', 'category', $append);\n}\n</code></pre>\n\n<p>the best it to read <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_set_object_terms</a></p>\n\n<p>I hope you get it ! </p>\n"
},
{
"answer_id": 241173,
"author": "bpy",
"author_id": 18693,
"author_profile": "https://wordpress.stackexchange.com/users/18693",
"pm_score": 0,
"selected": false,
"text": "<p>OK! Thanks to <a href=\"https://wordpress.stackexchange.com/users/58141/benoti\">@Benoti</a> I was able to find a way of doing this. </p>\n\n<p>It's possible that it can be improved but you can always contribute...</p>\n\n<pre><code>$args = array('post_type' => 'post',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'post_tag',\n 'field' => 'slug',\n 'terms' => 'tag_slug_to_find',// <= your cat slug to find\n ),\n ),\n);\n$posts = get_posts( $args );\n foreach ($posts as $post) :\n // let's do some stuff \n $cat_id = 'cat_slug_name'; //Cat slug to append to the object\n // If true, terms will be appended to the object. If false, terms will replace existing terms\n $append = true; \n // make some verif that's better\n $term_taxonomy_ids = wp_set_object_terms($post->ID, $cat_id, 'category', $append);\n // Let's count how many object's where changed \n // (If you know a better way, please let us know. Thanks!)\n $count = count( wp_set_object_terms($post->ID, $cat_id, 'category', $append)); \n\n if ( is_wp_error( $term_taxonomy_ids ) ) {\n echo 'There his an error somewhere and the terms could not be set.';\n} else {\n echo ''. $count . ' posts with tag \"'.$cat_id.'\" where changed.';\n}\n endforeach;\n</code></pre>\n\n<p>Thank you again, <a href=\"https://wordpress.stackexchange.com/users/58141/benoti\">@Benoti</a>! Your answer was very useful!</p>\n"
},
{
"answer_id": 407643,
"author": "gmush",
"author_id": 224049,
"author_profile": "https://wordpress.stackexchange.com/users/224049",
"pm_score": 0,
"selected": false,
"text": "<p>You can simply change tag 'wordpress' to category 'wordpress' by changing the taxonomy column from 'post_tag' to 'category' in table wp_term_taxonomy, you need to know term_id of 'wordpress' tag</p>\n"
}
] |
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 like <code>$my_class = new ngob_sitelist_slug;</code>. Doing it this way would require that your class have a <a href=\"http://php.net/manual/en/language.oop5.decon.php\" rel=\"nofollow\">constructor</a>. if it doesn't, you'll get an error.</p>\n\n<p>You could still call your class methods statically:</p>\n\n<pre><code>$my_thing = ngob_sitelist_slug::my_method();\n</code></pre>\n\n<p>Though technically you should add the <code>static</code> keyword to your methods in this case.</p>\n\n<p>Also I see that in your case you are using $this, so you really need a constructor.</p>\n\n<p>EDIT:\nI now realize you do have a constructor - albeit a deprecated one.</p>\n"
},
{
"answer_id": 240978,
"author": "George Bredberg",
"author_id": 97904,
"author_profile": "https://wordpress.stackexchange.com/users/97904",
"pm_score": 0,
"selected": false,
"text": "<p>I solved the problem by doing this;</p>\n\n<pre><code>class ngob_sitelist_slug {\n function ngob_sitelist_slug( ) {\n // Check if we are on network site\n if( is_main_site( $blog_id ) ) {\n add_filter( 'admin_init' , array( &$this , 'ngob_register_slug' ) );\n }\n }\n</code></pre>\n\n<p>The rest of the code is the same. But I guess there has to be a better aproach? How <em>should</em> you do it?</p>\n"
}
] |
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<p>But with you method, it's easy to adapt:</p>\n\n<p>Instead of <code>include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-config.php' );</code></p>\n\n<p>Add this at the top of processa.php</p>\n\n<pre><code>define('WP_USE_THEMES', false);\nrequire ('../wp-blog-header.php'); // be carrefull to get your right path\n</code></pre>\n\n<p>You file can now use WordPress globals, functions...</p>\n"
},
{
"answer_id": 251930,
"author": "krunal sojitra",
"author_id": 44054,
"author_profile": "https://wordpress.stackexchange.com/users/44054",
"pm_score": 1,
"selected": false,
"text": "<p>Try like this\nMain HTML:</p>\n\n<pre><code><form class=\"home_footer\" method=\"post\" id=\"home_conct_form\" action=\"\">\n <input type=\"text\" name=\"fname\" class=\"txt\" />\n <input type=\"text\" name=\"lname\" class=\"txt\" />\n <input type=\"button\" name=\"home_submit\" id=\"home_submit\" value=\"Get In Touch\"/>\n</form>\n</code></pre>\n\n<p>Add on same page: </p>\n\n<pre><code><script>\n$('#home_submit').click(function(){ \n var formData = $(\"#home_conct_form\").serialize() \n $.ajax({\n type: 'POST',\n url: '<?php echo home_url('/'); ?>wp-admin/admin-ajax.php?action=footerFrm',\n data: formData,\n beforeSend: function(){\n $('.progloader').show();\n $('#home_submit').hide();\n },\n success:function(data) {\n console.log(data);\n }\n }); \n});\n</script>\n</code></pre>\n\n<p>Add blow code in Function.php</p>\n\n<pre><code>add_action('wp_ajax_footerFrm' , 'footerFrm');\nadd_action('wp_ajax_nopriv_footerFrm' , 'footerFrm');\nfunction footerFrm() {\n print_r($_POST);\n die();\n}\n</code></pre>\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;\nwidth: 100%;\n</code></pre>\n\n<p>Makes the bar appear and</p>\n\n<p>I added z-index: 0; to .mdl-layout__header to make the dropdowns appear.</p>\n\n<p>Not the prettiest.</p>\n"
},
{
"answer_id": 241007,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>insert this into your style.css:</p>\n\n<pre><code>body #wpadminbar{z-index:99;}\n</code></pre>\n\n<p>and maybe this solves.</p>\n"
}
] |
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;\nwidth: 100%;\n</code></pre>\n\n<p>Makes the bar appear and</p>\n\n<p>I added z-index: 0; to .mdl-layout__header to make the dropdowns appear.</p>\n\n<p>Not the prettiest.</p>\n"
},
{
"answer_id": 241007,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>insert this into your style.css:</p>\n\n<pre><code>body #wpadminbar{z-index:99;}\n</code></pre>\n\n<p>and maybe this solves.</p>\n"
}
] |
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 ($_terms as $term) :\n $term_slug = $term->slug;\n $_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, ), ), ));\n\n if( $_posts->have_posts() ) :\n $i++;\n\n if ( $i == 1 ) {\n $class = 'is-active';\n } else {\n $class = null;\n }\n\n echo'<li class=\"accordion-item ' . $class . '\" data-accordion-item>';\n echo'<a href=\"#\" class=\"accordion-title\">';\n echo ''. $term->name .'';\n echo'</a>';\n while ( $_posts->have_posts() ) :\n $_posts->the_post();\n ?>\n <div class=\"accordion-content\" data-tab-content>\n <a data-open=\"exampleModal1\">\n <h4><?php the_title(); ?></h4></a>\n </div>\n <div class=\"reveal\" id=\"exampleModal1\" data-reveal>\n <?php the_content(); ?>\n <button class=\"close-button\" data-close aria-label=\"Close modal\" type=\"button\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n <?php\n endwhile;\n echo '</li>';\n endif;\n wp_reset_postdata();\n endforeach;\n ?>\n</ul>\n?>\n</code></pre>\n"
},
{
"answer_id": 241050,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>another way - instead of:</p>\n\n<pre><code>echo'<li class=\"accordion-item \" data-accordion-item>';\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>echo '<li class=\"accordion-item '.(!defined('firstp_created_444') && define('firstp_created_444',true) ? 'is-active' : '') .'\" data-accordion-item>';\n</code></pre>\n"
}
] |
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 protected]";
$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 PHP to display errors</a>. You can turn on DB logging in WordPress by adding this line to the <code>wp-config.php</code> file:</p>\n\n<pre><code>define( 'WP_DEBUG_LOG', true );\n</code></pre>\n\n<p>Starting on line 84, you've got some code that is not being fired via a hook. You should wrap that code in a function and fire it on a hook to ensure that you're controlling the timing of the code being fired. </p>\n\n<p>On line 101 your're doing an include for a PHP file over HTTP, which is usually not a good idea and it won't work on some server configurations anyway depending on <a href=\"http://php.net/manual/en/filesystem.configuration.php\" rel=\"nofollow\">allow_url_include</a> settings:</p>\n\n<pre><code>require('http://solutionsagencia.com.br/comparasaude/wp-load.php');\n\n$status = wp_mail( $para, $assunto, $conteudo );\n</code></pre>\n\n<p>I'm really not sure why you'd be including <code>wp-load.php</code>, AJAX maybe? If so, then check out the Codex article on <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">AJAX in Plugins</a>.</p>\n"
},
{
"answer_id": 241025,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 2,
"selected": false,
"text": "<p>Throws an error for me alright:</p>\n\n<pre><code>Warning: require(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in /var/www/europeanvoice/wp-content/plugins/test.php on line 101\n\nWarning: require(http://solutionsagencia.com.br/comparasaude/wp-load.php): failed to open stream: no suitable wrapper could be found in /var/www/europeanvoice/wp-content/plugins/test.php on line 101\n\nFatal error: require(): Failed opening required 'http://solutionsagencia.com.br/comparasaude/wp-load.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/europeanvoice/wp-content/plugins/test.php on line 101\n</code></pre>\n\n<p>Basically, you can't do this:</p>\n\n<pre><code>require('http://solutionsagencia.com.br/comparasaude/wp-load.php');\n</code></pre>\n"
},
{
"answer_id": 241052,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": true,
"text": "<p>you should remove:</p>\n\n<pre><code>require('http://solutionsagencia.com.br/comparasaude/wp-load.php');\n</code></pre>\n\n<p>and use:</p>\n\n<pre><code>require(ABSPATH.'wp-includes/pluggable.php');\n</code></pre>\n\n<p>p.s. I advice you, these executions should be hooked in 'init', like:</p>\n\n<pre><code>add_action('init', function(){\n\n $para = \"[email protected]\";\n $assunto = \"Assunto\" . $nome;\n $conteudo =\n \"<b>Nome:</b> {$nome}\" .\n \"<b>Email:</b> {$email}\" .\n\n $headers = array(\n 'Reply-To' => $name . '<' . $email . '>',\n );\n\n $status = wp_mail( $para, $assunto, $conteudo );\n\n remove_filter( 'wp_mail_content_type', 'set_html_content_type' );\n\n if ( $status ){\n echo \"sucesso\";\n } else {\n }\n\n});\n</code></pre>\n"
}
] |
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 protected]";
$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 protected]";
$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.wordpress.org/reference/classes/wpdb/query/\" rel=\"nofollow noreferrer\">wpdb::query()</a>, including Data Definition Statements, e.g.</p>\n\n<pre><code>function\ncreate_index ()\n{\n global $wpdb ;\n\n $sql = \"CREATE INDEX my_index ON {$wpdb->prefix}my_table (my_column)\" ;\n\n $wpdb->query ($sql) ;\n\n return ;\n}\n</code></pre>\n\n<p><strong>Note:</strong> Because <code>$wpdb->query()</code> can execute <em>arbitrary</em> SQL, if the statement you pass to it contains <strong>ANY</strong> user input, then you should use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">wpdb::prepare()</a> to protect against SQL Injection attacks.</p>\n\n<p>But this raises the question: how did you create your plugin-specific tables? \"Manually\" or programmatically? If programmatically, did you not use <code>$wpdb->query()</code>? If you did it \"manually\", then you really should create the tables (and their indexes) upon plugin activation.</p>\n\n<p>See the excellent answer to <a href=\"https://wordpress.stackexchange.com/questions/25910/uninstall-activate-deactivate-a-plugin-typical-features-how-to/25979#25979\">this other WPSE question</a> for how to hook into plugin activation (and/or deactivation and uninstall) to do things like create private tables.</p>\n"
},
{
"answer_id": 314047,
"author": "froger.me",
"author_id": 130448,
"author_profile": "https://wordpress.stackexchange.com/users/130448",
"pm_score": 3,
"selected": false,
"text": "<p>Using dbDelta, on top of a PRIMARY KEY, you can include the word KEY to create an index for other columns:</p>\n\n<blockquote>\n <p>You must use the key word KEY rather than its synonym INDEX and you must include at least one KEY.</p>\n</blockquote>\n\n<p>Example from schema.php in core:</p>\n\n<pre><code>CREATE TABLE $wpdb->termmeta (\n meta_id bigint(20) unsigned NOT NULL auto_increment,\n term_id bigint(20) unsigned NOT NULL default '0',\n meta_key varchar(255) default NULL,\n meta_value longtext,\n PRIMARY KEY (meta_id),\n KEY term_id (term_id),\n KEY meta_key (meta_key($max_index_length))\n) $charset_collate;\n</code></pre>\n\n<p>Source: <a href=\"https://codex.wordpress.org/Creating_Tables_with_Plugins\" rel=\"noreferrer\">codex - Creating Tables with Plugins</a></p>\n"
}
] |
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.wordpress.org/reference/classes/wpdb/query/\" rel=\"nofollow noreferrer\">wpdb::query()</a>, including Data Definition Statements, e.g.</p>\n\n<pre><code>function\ncreate_index ()\n{\n global $wpdb ;\n\n $sql = \"CREATE INDEX my_index ON {$wpdb->prefix}my_table (my_column)\" ;\n\n $wpdb->query ($sql) ;\n\n return ;\n}\n</code></pre>\n\n<p><strong>Note:</strong> Because <code>$wpdb->query()</code> can execute <em>arbitrary</em> SQL, if the statement you pass to it contains <strong>ANY</strong> user input, then you should use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">wpdb::prepare()</a> to protect against SQL Injection attacks.</p>\n\n<p>But this raises the question: how did you create your plugin-specific tables? \"Manually\" or programmatically? If programmatically, did you not use <code>$wpdb->query()</code>? If you did it \"manually\", then you really should create the tables (and their indexes) upon plugin activation.</p>\n\n<p>See the excellent answer to <a href=\"https://wordpress.stackexchange.com/questions/25910/uninstall-activate-deactivate-a-plugin-typical-features-how-to/25979#25979\">this other WPSE question</a> for how to hook into plugin activation (and/or deactivation and uninstall) to do things like create private tables.</p>\n"
},
{
"answer_id": 314047,
"author": "froger.me",
"author_id": 130448,
"author_profile": "https://wordpress.stackexchange.com/users/130448",
"pm_score": 3,
"selected": false,
"text": "<p>Using dbDelta, on top of a PRIMARY KEY, you can include the word KEY to create an index for other columns:</p>\n\n<blockquote>\n <p>You must use the key word KEY rather than its synonym INDEX and you must include at least one KEY.</p>\n</blockquote>\n\n<p>Example from schema.php in core:</p>\n\n<pre><code>CREATE TABLE $wpdb->termmeta (\n meta_id bigint(20) unsigned NOT NULL auto_increment,\n term_id bigint(20) unsigned NOT NULL default '0',\n meta_key varchar(255) default NULL,\n meta_value longtext,\n PRIMARY KEY (meta_id),\n KEY term_id (term_id),\n KEY meta_key (meta_key($max_index_length))\n) $charset_collate;\n</code></pre>\n\n<p>Source: <a href=\"https://codex.wordpress.org/Creating_Tables_with_Plugins\" rel=\"noreferrer\">codex - Creating Tables with Plugins</a></p>\n"
}
] |
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/\" rel=\"nofollow\"><code>wp_get_recent_posts()</code></a> 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.</p>\n\n<pre><code>$args = array(\n 'numberposts' => '5',\n 'orderby' => 'post_date',\n 'order' => 'DESC',\n 'post_type' => 'matratze',\n 'post_status' => 'publish'\n);\n$recent_posts = wp_get_recent_posts( $args );\n</code></pre>\n\n<p><strong>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 <a href=\"https://wordpress.org/plugins/posts-in-sidebar/\" rel=\"nofollow\">Posts in Sidebar</a> Plugin.</strong> This plugins i very powerful and provides you many options to show posts based on many criteria including recent posts from custom post types.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Here is code you can use for your specific case:</p>\n\n<p>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. </p>\n\n<pre><code>function filter_recent_get_posts($query) {\n if (isset($_POST['tab']) && ($_POST['tab'] == 'recent')) {\n $query->set('post_type', 'matratze');\n }\n}\nadd_action( 'pre_get_posts', 'filter_recent_get_posts' );\n</code></pre>\n"
},
{
"answer_id": 241228,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 2,
"selected": false,
"text": "<p>To display Custom Post Types in the regular Recent Post widget for sidebar(s),<br /> we use following function which works flawless for us.<br />\n<em>We use our own functions and try to prevent overhead often created by plugins.</em></p>\n\n<blockquote>\n <p>Note: make a backup before adding this function into <code>functions.php</code></p>\n</blockquote>\n\n<pre><code>/**\n * Display CPT on Recent Post widget\n *\n * @version WP 4.6.1\n */\nadd_filter( 'widget_posts_args', 'wpse241060_widget_recent_post_4_cpt' );\nfunction wpse241060_widget_recent_post_4_cpt( $params )\n{\n $params['post_type'] = array( 'post', 'cpt01', 'cpt02');\n return $params;\n}\n</code></pre>\n\n<blockquote>\n <p>Read more in <a href=\"https://developer.wordpress.org/reference/hooks/widget_posts_args/\" rel=\"nofollow\">Codex</a></p>\n</blockquote>\n"
}
] |
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</code>. In fact, you can just get rid of your <code>sort_*</code> arguments as <code>wp_list_pages</code> will output the correct natural order by default.</p>\n"
},
{
"answer_id": 241093,
"author": "Amino",
"author_id": 8124,
"author_profile": "https://wordpress.stackexchange.com/users/8124",
"pm_score": 0,
"selected": false,
"text": "<p>I found this <a href=\"http://wpsmith.net/2011/how-to-get-all-the-children-of-a-specific-nav-menu-item/\" rel=\"nofollow\">http://wpsmith.net/2011/how-to-get-all-the-children-of-a-specific-nav-menu-item/</a></p>\n\n<p>and wrote this code, so it fixed!</p>\n\n<p>function get_nav_menu_item_children( $menu, $depth = true) {</p>\n\n<pre><code> $post_id = $post_id ? : get_the_ID();\n$menu_items = wp_get_nav_menu_items($menu);\n\n$parent_item_id = wp_filter_object_list($menu_items, array('object_id' => $post_id), 'and', 'menu_item_parent');\n\nif (!empty($parent_item_id)) {\n $parent_item_id = array_shift($parent_item_id);\n $parent_post_id = wp_filter_object_list($menu_items, array('ID' => $parent_item_id), 'and', 'object_id');\n\n if (!empty($parent_post_id)) {\n $parent_post_id = array_shift($parent_post_id);\n\n $parent_id= get_post($parent_post_id)->ID;\n }\n}\n\n\n\n\n$nav_menu_item_list = array();\n\nforeach ((array) $menu_items as $nav_menu_item) {\n\n if ($nav_menu_item->post_parent == $parent_id) {\n\n $nav_menu_item_list[] = $nav_menu_item;\n\n }\n}\nreturn $nav_menu_item_list;\n</code></pre>\n\n<p>}</p>\n\n<p><strong>Usage</strong></p>\n\n<pre><code> $menuSide=get_nav_menu_item_children('Main menu');\n\n foreach ($menuSide as $link):\n $active='';\n if(intval($post->ID)===intval($link->object_id)){\n $active=' current_page_item ';\n\n }\n echo ' <li class=\"'.$active.'\"><a href=\"'.$link->url.'\">' . $link->title . '</a></li>';\n endforeach;\n</code></pre>\n"
},
{
"answer_id": 348560,
"author": "mrwpress",
"author_id": 115461,
"author_profile": "https://wordpress.stackexchange.com/users/115461",
"pm_score": 0,
"selected": false,
"text": "<p>You should use the page editor and set the 'order'. Setting the page order is what the problem here is. Once you set the order (lowest to highest) it will display in wp_list_pages in that order and not the default order which is page_title as @TheDeadMedic has stated. By default wp_list_pages lists pages alphabetically by their post_title. So if you want anything different from that, you are going to have to go to your pages in the dashboard one-by-one, and set those orders. After that, you will be all set.</p>\n\n<p>Hope that helps!</p>\n"
}
] |
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\" rel=\"nofollow\">source of <code>load_textdomain</code></a> (in WP 4.6):</p>\n\n<blockquote>\n <p>If the text domain already exists, the translations will be merged. If\n both sets have the same string, the translation from the original\n value will be taken.</p>\n</blockquote>\n\n<p>In other words, in order to make your translation override TwentyFifteen's, you must make sure your mo-files are loaded first, so they will be regarded as 'the original'. To do this, you can use the fact that a child theme's <code>functions.php</code> is loaded before the parent's.</p>\n\n<p>In the parent theme find the function that is loading the textdomain. It probably uses the <code>after_setup_theme</code> hook. Make sure your child theme uses the same textdomain as the parent. Then load your textdomain with <a href=\"https://developer.wordpress.org/reference/functions/load_child_theme_textdomain/\" rel=\"nofollow\"><code>load_child_theme_textdomain</code></a> on the same hook, but with a <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow\">higher priority</a>.</p>\n"
},
{
"answer_id": 249127,
"author": "Henrique Vianna",
"author_id": 68849,
"author_profile": "https://wordpress.stackexchange.com/users/68849",
"pm_score": 2,
"selected": false,
"text": "<p>Since WP 4.6 <code>load_theme_textdomain()</code> (and consequently <code>load_child_theme_textdomain()</code>) will give priority to .mo files downloaded from WP's online translation platform (translate.wordpress.org). Due to some new code (<a href=\"https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/l10n.php#L755\" rel=\"nofollow noreferrer\">here, on line 769</a>) these functions will completely ignore your local .mo files if the textdomain is found in the general <em>languages/</em> directory.</p>\n\n<p>You can, however, use the more basic <code>load_textdomain()</code> function to directly load your .mo file and override strings from the original domain, like this:</p>\n\n<pre><code>$domain = 'textdomain-to-override';\n$path = get_stylesheet_directory() . '/languages/'; // adjust to the location of your .mo file\n\n$locale = apply_filters( 'theme_locale', get_locale(), $domain );\nload_textdomain( $domain, $path . $locale . '.mo' );\n</code></pre>\n"
}
] |
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 how to send a custom message to the client( i.e. browser) if <code>check_ajax_referrer</code> returns <code>false</code>.</p>\n\n<p>Looking at the <a href=\"https://developer.wordpress.org/reference/functions/check_ajax_referer/\" rel=\"nofollow\">code reference</a> you will see the function fires an action called <code>check_ajax_referer</code>, right before it stops code execution, if false. What we will do is use this action to override the outcome of a false nonce result.</p>\n\n<pre><code>function fn_name($action, $result){\n\n // check if $result, passed from core function, is false\n // alternately you can check for action if only needed for a specific ajax request\n // For example: \n // if($action == 'the_action_name' && false === $result)\n\n if ( false === $result ) {\n\n // use built in send function to return json to client,\n // wp_send_json has wp_die() built-in\n\n wp_send_json('This term cannot be deleted');\n }\n\n // return to core function if true\n return $result;\n}\n\nadd_action('check_ajax_referer', 'fn_name', 10, 2);\n</code></pre>\n\n<p>I apologize if this answer is too verbose, I wanted to be as thorough as possible.</p>\n"
},
{
"answer_id": 242427,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>Every AJAX call has similar stucture:</p>\n\n<pre><code>jQuery.post(ajaxurl, { \n action: \"something_namee\", \n parameter1: \"blabla\" ,\n parameter2: \"blabla222\" ,\n ........ \n</code></pre>\n\n<p>in PHP side, you should create an <code>wp_ajax_</code> action, followed exactly <code>something_namee</code>:</p>\n\n<pre><code>add_action('wp_ajax_something_namee','myfunc123',1);\nfunction myfunc123(){\n //var_dump($_POST);\n if(!EMPTY($_POST['parameter1']) && $_POST['parameter1']==53){\n die(\"this term id cant be deleted\");\n }\n}\n</code></pre>\n\n<p>p.s. just change parameter1 and 53 with the real parameters being called (you can find out what parameters are passed from AJAX by uncommenting <code>var_dump</code> above)</p>\n\n<p>p.s.2. However, I suggest not to be dependent on AJAX calls at all!\nBecause many different things can be done for deleting the categories, so the above method wont help. I will post another answer, which is recommended.</p>\n"
},
{
"answer_id": 242431,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": false,
"text": "<p>Another answer is not concerned with AJAX/JAVASCRIPT at all.</p>\n\n<p>Instead, add this code:</p>\n\n<pre><code>add_action( 'pre_delete_term', 'myfunc', 10,2 );\nfunction myfunc($term, $taxonomy){\n //var_dump($term); var_dump($taxonomy);\n if($taxonomy =='category' && $term==745 ){\n die('not allowed');\n }\n}\n</code></pre>\n\n<p>p.s. change 745 to the desired category id.</p>\n"
},
{
"answer_id": 242451,
"author": "darrinb",
"author_id": 6304,
"author_profile": "https://wordpress.stackexchange.com/users/6304",
"pm_score": 0,
"selected": false,
"text": "<p>I have this in one of my plugins:</p>\n\n<pre><code>/**\n * Prevents deletion of term\n *\n * Applies filter \"atf_locks_term_delete_cap\" to allow other plugins to filter the capability.\n *\n * @uses Adv_Term_Fields_Locks::get_prevent_msg()\n *\n * @access public\n *\n * @since 0.1.0\n *\n * @param int $term_id Term ID.\n * @param string $taxonomy Taxonomy Name.\n *\n * @return mixed int $term_id If current user can delete the term or term is not locked.\n * wp_die() On AJAX calls: If current user can't delete term or user is not detected.\n */\npublic function maybe_prevent_term_delete( $term_id, $taxonomy )\n{\n // If no lock, return term ID\n if ( ! $lock = get_term_meta( $term_id, $this->meta_key, true ) ) {\n return $term_id;\n };\n\n $cap = apply_filters( \"atf_locks_term_delete_cap\", \"manage_others_term_locks\" );\n $user_can_delete = $this->_user_can( $cap, $term_id, $taxonomy, $lock );\n\n if ( ! $user_can_delete ) :\n if ( defined('DOING_AJAX') && DOING_AJAX ) {\n wp_die( -1 );\n } else {\n $_msg = $this->get_prevent_msg( $action = 'delete' );\n wp_die( $_msg, 403 );\n };\n endif;\n\n return $term_id;\n}\n</code></pre>\n\n<p>and it's called like so: </p>\n\n<p><code>add_action( 'pre_delete_term', array( $this, 'maybe_prevent_term_delete' ), 99, 2 );</code></p>\n\n<p>The <code>pre_delete_filter</code> is called before any term is deleted. To prevent deletion, you can hook into the action similar to how I've done it in my class method above.</p>\n\n<p>The problem is, WP doesn't allow for a way to customize the response. Since it's an ajax call it's only looking for a '1', a '0', or a '-1'. </p>\n\n<p>Check out <code>wp_ajax_delete_tag()</code> in <code>/wp-admin/includes/ajax-actions.php</code> to see what I'm referring to.</p>\n"
},
{
"answer_id": 242474,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 0,
"selected": false,
"text": "<p>Every AJAX call uses callback functions to process returning data. Just use the <code>.fail</code> callback:</p>\n\n<pre><code>jQuery.post( ajaxurl,\n { //your data here },\n function( content ) {\n var myContent = JSON.parse(content);\n // success! do something with content\n } ).fail( fucntion( msg ) { alert( msg );\n });\n</code></pre>\n\n<p>This is how I would pass the AJAX failure message to the user interface.</p>\n"
},
{
"answer_id": 242537,
"author": "garprogram",
"author_id": 104651,
"author_profile": "https://wordpress.stackexchange.com/users/104651",
"pm_score": -1,
"selected": false,
"text": "<p>To send a response to the web page via ajax.</p>\n\n<pre><code>add_action('wp_ajax_my_action','my_function');\n\nfunction my_function(){\n if( true === $value ){ // make test\n echo 'Is true'; // send string response to web page\n wp_die(); // Finish response\n } else {\n echo 'Is not true'; // send string response to web page\n wp_die(); // Finish response\n }\n}\n</code></pre>\n\n<p>You can also send a json response:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_send_json</a> :Send a JSON response back to an AJAX request, and die(). </p>\n\n<pre><code>function my_function(){\n $response_true = array('response'=> 'Success','reason'=>'is true');\n $response_not_true = array('response'=> 'Error','reason'=>'is not true');\n if( true === $value ){ // make test\n wp_send_json($response_true); // send json response \n // wp_die(); // not necessary\n } else {\n wp_send_json($response_not_true); // send json response \n // wp_die(); // not necessary\n }\n}\n</code></pre>\n"
},
{
"answer_id": 242552,
"author": "LeMike",
"author_id": 42974,
"author_profile": "https://wordpress.stackexchange.com/users/42974",
"pm_score": 3,
"selected": true,
"text": "<p>Wait for WordPress 4.7 on 6th December. It has this almost built-in.</p>\n\n<p>If I got it right, then you'll want to prevent some terms from deletion.\nI already made a snippet for that which works with WP 4.7</p>\n\n<pre><code>add_filter(\n 'user_has_cap',\n function ( $allcaps, $caps, $args ) {\n if ( ! isset( $args[0] ) || 'delete_term' != $args[0] ) {\n // not the deletion process => ignore\n return $allcaps;\n }\n\n $term = get_term( $args[2] );\n\n // HERE YOU'LL LIKE TO PUT YOUR LOGIC INSTEAD OF THIS:\n if ( $term->count <= 0 ) {\n return $allcaps;\n }\n\n // for all other cases => reject deletion\n return [ ];\n },\n 10,\n 3\n);\n</code></pre>\n\n<p>For more details read <a href=\"https://wp-includes.org/536/capabilities-taxonomies-terms/#Preventnon-empty_categories_from_deletion\" rel=\"nofollow\">https://wp-includes.org/536/capabilities-taxonomies-terms/#Preventnon-empty_categories_from_deletion</a></p>\n"
}
] |
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 how to send a custom message to the client( i.e. browser) if <code>check_ajax_referrer</code> returns <code>false</code>.</p>\n\n<p>Looking at the <a href=\"https://developer.wordpress.org/reference/functions/check_ajax_referer/\" rel=\"nofollow\">code reference</a> you will see the function fires an action called <code>check_ajax_referer</code>, right before it stops code execution, if false. What we will do is use this action to override the outcome of a false nonce result.</p>\n\n<pre><code>function fn_name($action, $result){\n\n // check if $result, passed from core function, is false\n // alternately you can check for action if only needed for a specific ajax request\n // For example: \n // if($action == 'the_action_name' && false === $result)\n\n if ( false === $result ) {\n\n // use built in send function to return json to client,\n // wp_send_json has wp_die() built-in\n\n wp_send_json('This term cannot be deleted');\n }\n\n // return to core function if true\n return $result;\n}\n\nadd_action('check_ajax_referer', 'fn_name', 10, 2);\n</code></pre>\n\n<p>I apologize if this answer is too verbose, I wanted to be as thorough as possible.</p>\n"
},
{
"answer_id": 242427,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>Every AJAX call has similar stucture:</p>\n\n<pre><code>jQuery.post(ajaxurl, { \n action: \"something_namee\", \n parameter1: \"blabla\" ,\n parameter2: \"blabla222\" ,\n ........ \n</code></pre>\n\n<p>in PHP side, you should create an <code>wp_ajax_</code> action, followed exactly <code>something_namee</code>:</p>\n\n<pre><code>add_action('wp_ajax_something_namee','myfunc123',1);\nfunction myfunc123(){\n //var_dump($_POST);\n if(!EMPTY($_POST['parameter1']) && $_POST['parameter1']==53){\n die(\"this term id cant be deleted\");\n }\n}\n</code></pre>\n\n<p>p.s. just change parameter1 and 53 with the real parameters being called (you can find out what parameters are passed from AJAX by uncommenting <code>var_dump</code> above)</p>\n\n<p>p.s.2. However, I suggest not to be dependent on AJAX calls at all!\nBecause many different things can be done for deleting the categories, so the above method wont help. I will post another answer, which is recommended.</p>\n"
},
{
"answer_id": 242431,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": false,
"text": "<p>Another answer is not concerned with AJAX/JAVASCRIPT at all.</p>\n\n<p>Instead, add this code:</p>\n\n<pre><code>add_action( 'pre_delete_term', 'myfunc', 10,2 );\nfunction myfunc($term, $taxonomy){\n //var_dump($term); var_dump($taxonomy);\n if($taxonomy =='category' && $term==745 ){\n die('not allowed');\n }\n}\n</code></pre>\n\n<p>p.s. change 745 to the desired category id.</p>\n"
},
{
"answer_id": 242451,
"author": "darrinb",
"author_id": 6304,
"author_profile": "https://wordpress.stackexchange.com/users/6304",
"pm_score": 0,
"selected": false,
"text": "<p>I have this in one of my plugins:</p>\n\n<pre><code>/**\n * Prevents deletion of term\n *\n * Applies filter \"atf_locks_term_delete_cap\" to allow other plugins to filter the capability.\n *\n * @uses Adv_Term_Fields_Locks::get_prevent_msg()\n *\n * @access public\n *\n * @since 0.1.0\n *\n * @param int $term_id Term ID.\n * @param string $taxonomy Taxonomy Name.\n *\n * @return mixed int $term_id If current user can delete the term or term is not locked.\n * wp_die() On AJAX calls: If current user can't delete term or user is not detected.\n */\npublic function maybe_prevent_term_delete( $term_id, $taxonomy )\n{\n // If no lock, return term ID\n if ( ! $lock = get_term_meta( $term_id, $this->meta_key, true ) ) {\n return $term_id;\n };\n\n $cap = apply_filters( \"atf_locks_term_delete_cap\", \"manage_others_term_locks\" );\n $user_can_delete = $this->_user_can( $cap, $term_id, $taxonomy, $lock );\n\n if ( ! $user_can_delete ) :\n if ( defined('DOING_AJAX') && DOING_AJAX ) {\n wp_die( -1 );\n } else {\n $_msg = $this->get_prevent_msg( $action = 'delete' );\n wp_die( $_msg, 403 );\n };\n endif;\n\n return $term_id;\n}\n</code></pre>\n\n<p>and it's called like so: </p>\n\n<p><code>add_action( 'pre_delete_term', array( $this, 'maybe_prevent_term_delete' ), 99, 2 );</code></p>\n\n<p>The <code>pre_delete_filter</code> is called before any term is deleted. To prevent deletion, you can hook into the action similar to how I've done it in my class method above.</p>\n\n<p>The problem is, WP doesn't allow for a way to customize the response. Since it's an ajax call it's only looking for a '1', a '0', or a '-1'. </p>\n\n<p>Check out <code>wp_ajax_delete_tag()</code> in <code>/wp-admin/includes/ajax-actions.php</code> to see what I'm referring to.</p>\n"
},
{
"answer_id": 242474,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 0,
"selected": false,
"text": "<p>Every AJAX call uses callback functions to process returning data. Just use the <code>.fail</code> callback:</p>\n\n<pre><code>jQuery.post( ajaxurl,\n { //your data here },\n function( content ) {\n var myContent = JSON.parse(content);\n // success! do something with content\n } ).fail( fucntion( msg ) { alert( msg );\n });\n</code></pre>\n\n<p>This is how I would pass the AJAX failure message to the user interface.</p>\n"
},
{
"answer_id": 242537,
"author": "garprogram",
"author_id": 104651,
"author_profile": "https://wordpress.stackexchange.com/users/104651",
"pm_score": -1,
"selected": false,
"text": "<p>To send a response to the web page via ajax.</p>\n\n<pre><code>add_action('wp_ajax_my_action','my_function');\n\nfunction my_function(){\n if( true === $value ){ // make test\n echo 'Is true'; // send string response to web page\n wp_die(); // Finish response\n } else {\n echo 'Is not true'; // send string response to web page\n wp_die(); // Finish response\n }\n}\n</code></pre>\n\n<p>You can also send a json response:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_send_json</a> :Send a JSON response back to an AJAX request, and die(). </p>\n\n<pre><code>function my_function(){\n $response_true = array('response'=> 'Success','reason'=>'is true');\n $response_not_true = array('response'=> 'Error','reason'=>'is not true');\n if( true === $value ){ // make test\n wp_send_json($response_true); // send json response \n // wp_die(); // not necessary\n } else {\n wp_send_json($response_not_true); // send json response \n // wp_die(); // not necessary\n }\n}\n</code></pre>\n"
},
{
"answer_id": 242552,
"author": "LeMike",
"author_id": 42974,
"author_profile": "https://wordpress.stackexchange.com/users/42974",
"pm_score": 3,
"selected": true,
"text": "<p>Wait for WordPress 4.7 on 6th December. It has this almost built-in.</p>\n\n<p>If I got it right, then you'll want to prevent some terms from deletion.\nI already made a snippet for that which works with WP 4.7</p>\n\n<pre><code>add_filter(\n 'user_has_cap',\n function ( $allcaps, $caps, $args ) {\n if ( ! isset( $args[0] ) || 'delete_term' != $args[0] ) {\n // not the deletion process => ignore\n return $allcaps;\n }\n\n $term = get_term( $args[2] );\n\n // HERE YOU'LL LIKE TO PUT YOUR LOGIC INSTEAD OF THIS:\n if ( $term->count <= 0 ) {\n return $allcaps;\n }\n\n // for all other cases => reject deletion\n return [ ];\n },\n 10,\n 3\n);\n</code></pre>\n\n<p>For more details read <a href=\"https://wp-includes.org/536/capabilities-taxonomies-terms/#Preventnon-empty_categories_from_deletion\" rel=\"nofollow\">https://wp-includes.org/536/capabilities-taxonomies-terms/#Preventnon-empty_categories_from_deletion</a></p>\n"
}
] |
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 <code>siteurl</code> option that's otherwise stored in the database, but it also means you can reference the URL without doing a query.</p>\n<p>From <a href=\"https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php\" rel=\"nofollow noreferrer\">the Codex</a>:</p>\n<blockquote>\n<p>It is possible to set the site URL manually in the wp-config.php file.</p>\n<p>Add these two lines to your wp-config.php, where "example.com" is the correct location of your site.</p>\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n</blockquote>\n<p>After that, using code in a regular theme that checks the <code>siteurl</code> or <code>home</code> 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 <code>WP_SITEURL</code> directly to build a redirect URL.</p>\n"
},
{
"answer_id": 241141,
"author": "Dhul Wells",
"author_id": 109750,
"author_profile": "https://wordpress.stackexchange.com/users/109750",
"pm_score": 1,
"selected": false,
"text": "<p>Well the DB error has to come from the site requested. So why not just use the Superglobal $_SERVER and get the HTTP host. </p>\n\n<pre><code>header(\"Location: https://\" . $_SERVER['HTTP_HOST'] ); //Redirect to root\n\nexit(); //Exit \n</code></pre>\n"
},
{
"answer_id": 241142,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress relies on configuration to \"tell\" it what's the correct URL is. This might be database option or <code>WP_HOME</code> constant which overrides it. For a custom site it is common practice to set constant in <code>wp-config.php</code> and not bother with DB option altogether.</p>\n\n<p>General case is more complicated since there is no dedicated WP API function (that I can remember) which makes it <em>determine</em> that information without configuration.</p>\n\n<p>The closest routine I can think of in source is when <code>RELOCATE</code> mode is set, which explicitly tells WP that URL configuration is unreliable and should be updated from current state.</p>\n\n<p>The relevant code in <code>wp-login.php</code> does following:</p>\n\n<pre><code>if ( defined( 'RELOCATE' ) && RELOCATE ) { // Move flag is set\n if ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != $_SERVER['PHP_SELF']) )\n $_SERVER['PHP_SELF'] = str_replace( $_SERVER['PATH_INFO'], '', $_SERVER['PHP_SELF'] );\n\n $url = dirname( set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ) );\n if ( $url != get_option( 'siteurl' ) )\n update_option( 'siteurl', $url );\n}\n</code></pre>\n\n<p>So overall without access to configuration your remaining option is going to <code>$_SERVER</code> context, which is not too reliable.</p>\n"
}
] |
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, the page can only retrieve header and footer templates. The mysqli query seems incompatible with WordPress codex. </p>\n"
},
{
"answer_id": 241168,
"author": "adelval",
"author_id": 40965,
"author_profile": "https://wordpress.stackexchange.com/users/40965",
"pm_score": 2,
"selected": true,
"text": "<p>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.</p>\n\n<p>So, first put all data into an array in the standard way:</p>\n\n<pre><code>$query = (\"SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title\");\n$results_array = array();\n$result = $mysqli->query($query);\nwhile ($row = $result->fetch_assoc()) {\n $results_array[] = $row;\n}\n</code></pre>\n\n<p>The first row of this array, i.e. <code>$results_array[0]</code>, for example, will be the array <code>('Title' => 'Title 1','Author' => 'j cool', 'Device1' => 'inputA',...)</code></p>\n\n<p><strong>Edit</strong>: Alternatively, if you insist on using the wpdb class, replace the above code by:</p>\n\n<pre><code>$mydb = new wpdb('user','password','database','server');\n$results_array = $mydb->get_results(\"SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title\",ARRAY_A);\n</code></pre>\n\n<p><code>$results_array</code> has the same content with both approaches. The rest of the code doesn't change.</p>\n\n<p><strong>End edit</strong></p>\n\n<p>You want to obtain from <code>$results_array</code> an associative array that associates to each Author a table mapping input to devices, like this:</p>\n\n<pre><code>array('j cool' => array('inputA' => array('Device1', 'Device2'),\n 'inputB' => array('Device3')),\n 'l maker' => array('inputA' => array('Device1'),\n 'inputB' => array('Device2'),\n 'inputC' => array('Device3')),\n 'm this' => ...)\n</code></pre>\n\n<p>The following code assumes you know all possible values of inputs in advance, and that these do not match exactly authors or titles.</p>\n\n<pre><code> $inputs = array('inputA','inputB','inputC');\n\n $input_table = array();\n\n foreach ($results_array as $row) {\n $row_inputs = array();\n foreach ($inputs as $in) {\n //get all keys (devices) in $row that have input $in as value\n $devices = array_keys($row,$in); \n if (!empty($devices))\n $row_inputs[$in] = $devices;\n }\n $input_table[$row['Author']] = $row_inputs;\n }\n</code></pre>\n\n<p>This generates an array where each row, indexed by the Author, is an array like the example above. Now we add the title:</p>\n\n<pre><code>$final_table = array();\nforeach ($results_array as $row) {\n $final_table[] = array('Title' => $row['Title'],\n 'Author' => $row['Author'],\n 'Inputs' => $input_table[$row['Author']]);\n}\n</code></pre>\n\n<p>Finally, display the resulting array in html:</p>\n\n<pre><code>$html = '';\n//$html .= '<html><body>';\n$html .= \"<table>\"; //add here code for table headers too\n\nforeach ($final_table as $row) {\n //first row for author\n $html .= '<tr><td>'. $row['Title'] . '</td><td>' . $row['Author'] . '</td>';\n foreach (array_keys($row['Inputs']) as $in) {\n //output input names for this author\n $html .= '<td>'.$in.'</td>';\n }\n $html .= '</tr><td></td><td></td>';\n //second row for author, starting in third column\n foreach ($row['Inputs'] as $in => $devices) {\n $html .= '<td>'.implode(\" \",$devices).'</td>';\n }\n $html .= '</tr>';\n}\n\n$html .= '</table>';\n// $html .= </body></html>\necho $html;\n</code></pre>\n\n<p>Fine-tune the presentation at your liking...</p>\n"
}
] |
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, the page can only retrieve header and footer templates. The mysqli query seems incompatible with WordPress codex. </p>\n"
},
{
"answer_id": 241168,
"author": "adelval",
"author_id": 40965,
"author_profile": "https://wordpress.stackexchange.com/users/40965",
"pm_score": 2,
"selected": true,
"text": "<p>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.</p>\n\n<p>So, first put all data into an array in the standard way:</p>\n\n<pre><code>$query = (\"SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title\");\n$results_array = array();\n$result = $mysqli->query($query);\nwhile ($row = $result->fetch_assoc()) {\n $results_array[] = $row;\n}\n</code></pre>\n\n<p>The first row of this array, i.e. <code>$results_array[0]</code>, for example, will be the array <code>('Title' => 'Title 1','Author' => 'j cool', 'Device1' => 'inputA',...)</code></p>\n\n<p><strong>Edit</strong>: Alternatively, if you insist on using the wpdb class, replace the above code by:</p>\n\n<pre><code>$mydb = new wpdb('user','password','database','server');\n$results_array = $mydb->get_results(\"SELECT * FROM titles WHERE `active` = 0 ORDER BY author, title\",ARRAY_A);\n</code></pre>\n\n<p><code>$results_array</code> has the same content with both approaches. The rest of the code doesn't change.</p>\n\n<p><strong>End edit</strong></p>\n\n<p>You want to obtain from <code>$results_array</code> an associative array that associates to each Author a table mapping input to devices, like this:</p>\n\n<pre><code>array('j cool' => array('inputA' => array('Device1', 'Device2'),\n 'inputB' => array('Device3')),\n 'l maker' => array('inputA' => array('Device1'),\n 'inputB' => array('Device2'),\n 'inputC' => array('Device3')),\n 'm this' => ...)\n</code></pre>\n\n<p>The following code assumes you know all possible values of inputs in advance, and that these do not match exactly authors or titles.</p>\n\n<pre><code> $inputs = array('inputA','inputB','inputC');\n\n $input_table = array();\n\n foreach ($results_array as $row) {\n $row_inputs = array();\n foreach ($inputs as $in) {\n //get all keys (devices) in $row that have input $in as value\n $devices = array_keys($row,$in); \n if (!empty($devices))\n $row_inputs[$in] = $devices;\n }\n $input_table[$row['Author']] = $row_inputs;\n }\n</code></pre>\n\n<p>This generates an array where each row, indexed by the Author, is an array like the example above. Now we add the title:</p>\n\n<pre><code>$final_table = array();\nforeach ($results_array as $row) {\n $final_table[] = array('Title' => $row['Title'],\n 'Author' => $row['Author'],\n 'Inputs' => $input_table[$row['Author']]);\n}\n</code></pre>\n\n<p>Finally, display the resulting array in html:</p>\n\n<pre><code>$html = '';\n//$html .= '<html><body>';\n$html .= \"<table>\"; //add here code for table headers too\n\nforeach ($final_table as $row) {\n //first row for author\n $html .= '<tr><td>'. $row['Title'] . '</td><td>' . $row['Author'] . '</td>';\n foreach (array_keys($row['Inputs']) as $in) {\n //output input names for this author\n $html .= '<td>'.$in.'</td>';\n }\n $html .= '</tr><td></td><td></td>';\n //second row for author, starting in third column\n foreach ($row['Inputs'] as $in => $devices) {\n $html .= '<td>'.implode(\" \",$devices).'</td>';\n }\n $html .= '</tr>';\n}\n\n$html .= '</table>';\n// $html .= </body></html>\necho $html;\n</code></pre>\n\n<p>Fine-tune the presentation at your liking...</p>\n"
}
] |
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\">Object Cache API</a> or <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow\">Transients API</a>, whatever fits better your needs.</p>\n\n<p>A very quick example with object cache:</p>\n\n<pre><code>// helper function\nfunction get_my_object() {\n $object = wp_cache_get( 'my_object' );\n if ( false === $object ) {\n $args = array( .... );\n $object = new WP_Query( $args );\n wp_cache_set( 'my_object', $object );\n } \n return $object;\n}\n\nclass cyb_my_widget extends WP_Widget {\n\n function __construct() {\n // ...\n }\n\n function widget( $args, $instance ) {\n // ...\n $object = get_my_object();\n }\n\n function update( $new_instance, $old_instance ) {\n // ...\n }\n\n function form( $instance ) {\n // ...\n }\n}\n</code></pre>\n"
},
{
"answer_id": 241189,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>The easy way would be to generate a global variable or <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">transient</a> (in case you want to use the object on multiple pages) in your template and have the widgets access that.</p>\n\n<p>A programmatically more sound approach would be quite some work and go like this:</p>\n\n<ol>\n<li>Build a widget that runs the query and returns your object. Normally a <a href=\"https://developer.wordpress.org/reference/classes/wp_widget/\" rel=\"nofollow noreferrer\">WP_widget</a> instance will use the parent's <a href=\"http://php.net/manual/en/language.oop5.decon.php\" rel=\"nofollow noreferrer\">constructor</a> to initialize. However, when you are extending the WP_Widget class, you can also include an additional constructor. Here you generate the possibility to pass an additional argument to a widget instance, your object.</li>\n<li>The other widgets you define not as extensions of WP_Widget, but as extensions of your parent widget, so they can take an extra argument.</li>\n<li>Inside the parent widget use <a href=\"https://codex.wordpress.org/Function_Reference/the_widget\" rel=\"nofollow noreferrer\"><code>the_widget</code></a> to display other widgets, <a href=\"https://stackoverflow.com/questions/9346856/php-constructor-with-parameter\">passing the object</a>.</li>\n</ol>\n\n<p>I'm sure there must be other approaches, but this is the course I would be exploring. Note: I haven't felt the need to do something like this, so this approach is offered 'as is'.</p>\n"
}
] |
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 content, rather than trying to add a large number of extra content blocks to the edit screen.</p>\n\n<p>Here's what I use, the basics of which I think I got from the Codex originally, a long time ago.</p>\n\n<pre><code>// Callback function to insert 'styleselect' into the $buttons array\nfunction wpse241267_mce_buttons_2( $buttons ) {\n array_unshift( $buttons, 'styleselect' );\n return $buttons;\n}\n\nadd_filter('mce_buttons_2', 'wpse241267_mce_buttons_2');\n</code></pre>\n\n<p>This just enables the Style dropdown menu at the left hand end of the second row of Visual Editor buttons.</p>\n\n<p>Now for the meat:</p>\n\n<pre><code>function wpse241267_mce_insert_formats( $init_array ) { \n\n $style_formats = array( \n // Each array child is a format with its own settings\n\n array( \n 'title' => 'Find Us Block', \n 'block' => 'div', \n 'classes' => 'find-us',\n 'wrapper' => true,\n 'exact' => true,\n\n ),\n ); \n\n // Insert the array, JSON ENCODED, into 'style_formats'\n\n $init_array['style_formats'] = json_encode( $style_formats ); \n\n return $init_array; \n\n} \n\nadd_filter( 'tiny_mce_before_init', 'wpse241267_mce_insert_formats' );\n</code></pre>\n\n<p>You can use IDs instead of classes if you want, but I don't think there's anything to prevent a user adding more than one into a page.</p>\n\n<p>Then in the Visual Editor you can highlight some content, apply this style from the dropdown and the highlighted content will be surrounded by a <code>div</code> with the class <code>find-us</code>.</p>\n\n<p>The <code>exact</code> argument prevents the editor merging multiple adjacent blocks. Depending on your case you may wish to remove this.</p>\n"
},
{
"answer_id": 241537,
"author": "Dalton Rooney",
"author_id": 799,
"author_profile": "https://wordpress.stackexchange.com/users/799",
"pm_score": 2,
"selected": false,
"text": "<p>This sounds to me like a perfect use of <a href=\"https://www.advancedcustomfields.com/resources/flexible-content/\" rel=\"nofollow\">Advanced Custom Fields \"flexible content\"</a> 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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
}
] |
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 content, rather than trying to add a large number of extra content blocks to the edit screen.</p>\n\n<p>Here's what I use, the basics of which I think I got from the Codex originally, a long time ago.</p>\n\n<pre><code>// Callback function to insert 'styleselect' into the $buttons array\nfunction wpse241267_mce_buttons_2( $buttons ) {\n array_unshift( $buttons, 'styleselect' );\n return $buttons;\n}\n\nadd_filter('mce_buttons_2', 'wpse241267_mce_buttons_2');\n</code></pre>\n\n<p>This just enables the Style dropdown menu at the left hand end of the second row of Visual Editor buttons.</p>\n\n<p>Now for the meat:</p>\n\n<pre><code>function wpse241267_mce_insert_formats( $init_array ) { \n\n $style_formats = array( \n // Each array child is a format with its own settings\n\n array( \n 'title' => 'Find Us Block', \n 'block' => 'div', \n 'classes' => 'find-us',\n 'wrapper' => true,\n 'exact' => true,\n\n ),\n ); \n\n // Insert the array, JSON ENCODED, into 'style_formats'\n\n $init_array['style_formats'] = json_encode( $style_formats ); \n\n return $init_array; \n\n} \n\nadd_filter( 'tiny_mce_before_init', 'wpse241267_mce_insert_formats' );\n</code></pre>\n\n<p>You can use IDs instead of classes if you want, but I don't think there's anything to prevent a user adding more than one into a page.</p>\n\n<p>Then in the Visual Editor you can highlight some content, apply this style from the dropdown and the highlighted content will be surrounded by a <code>div</code> with the class <code>find-us</code>.</p>\n\n<p>The <code>exact</code> argument prevents the editor merging multiple adjacent blocks. Depending on your case you may wish to remove this.</p>\n"
},
{
"answer_id": 241537,
"author": "Dalton Rooney",
"author_id": 799,
"author_profile": "https://wordpress.stackexchange.com/users/799",
"pm_score": 2,
"selected": false,
"text": "<p>This sounds to me like a perfect use of <a href=\"https://www.advancedcustomfields.com/resources/flexible-content/\" rel=\"nofollow\">Advanced Custom Fields \"flexible content\"</a> 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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
}
] |
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, will include the <code>_embedded.[wp:featuredmedia]</code> object, which includes all the images, just like the <code>/media/$id</code> resource. If you want an specific size, just access it by its property name, i.e.: <code>_embedded[wp:featuredmedia][0].media_details.sizes.full.source_url</code> or for its thumbnail: <code>_embedded[wp:featuredmedia][0].media_details.sizes.thumbnail.source_url</code></p>\n\n<p>That is, the wp:featuredmedia embedded object includes all the URLs and details for every size available for your post, but if you want just the original featured image, you can use the value in this key: <code>post._embedded[\"wp:featuredmedia\"][0].source_url</code></p>\n\n<p>I use it in a site with something like this (use your own domain, of course):</p>\n\n<pre><code>$.get('https://example.com/wp-json/wp/v2/posts/?categories=3&_embed', \n function(posts) { \n var elems = '';\n posts.forEach(function(post){ \n var link = post.link;\n var title = post.title.rendered;\n var pic = post._embedded[\"wp:featuredmedia\"][0].source_url);\n elems += '<div class=\"this_week\"><a href=\"' + link + '\" target=\"_blank\">';\n elems += '<img src=\"' + pic + '\" title=\"' + title + '\"/><span class=\"title\">';\n elems += title + '</span></a></div>';\n });\n $('#blockbusters').html(elems);\n });\n});\n</code></pre>\n\n<p>See? No need for two queries, just add <code>_embed</code> as a query argument, and then you have all the information you need to use the best size for your view.</p>\n"
},
{
"answer_id": 249769,
"author": "StephanieQ",
"author_id": 109262,
"author_profile": "https://wordpress.stackexchange.com/users/109262",
"pm_score": 6,
"selected": true,
"text": "<p>Ah I just had this problem myself! And while <code>_embed</code> is great, in my experience it is very slow, and the point of JSON is to be fast :D</p>\n\n<p>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 <code>function.php</code> file.</p>\n\n<p><code>php</code></p>\n\n<pre><code>add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );\nfunction add_thumbnail_to_JSON() {\n//Add featured image\nregister_rest_field( \n 'post', // Where to add the field (Here, blog posts. Could be an array)\n 'featured_image_src', // Name of new field (You can call this anything)\n array(\n 'get_callback' => 'get_image_src',\n 'update_callback' => null,\n 'schema' => null,\n )\n );\n}\n\nfunction get_image_src( $object, $field_name, $request ) {\n $feat_img_array = wp_get_attachment_image_src(\n $object['featured_media'], // Image attachment ID\n 'thumbnail', // Size. Ex. \"thumbnail\", \"large\", \"full\", etc..\n true // Whether the image should be treated as an icon.\n );\n return $feat_img_array[0];\n}\n</code></pre>\n\n<p>Now in your JSON response you should see a new field called <code>\"featured_image_src\":</code> containing a url to the thumbnail.</p>\n\n<p>Read more about modifying responses here:<br>\n<a href=\"http://v2.wp-api.org/extending/modifying/\" rel=\"noreferrer\">http://v2.wp-api.org/extending/modifying/</a> </p>\n\n<p>And here's more information on the<code>register_rest_field</code> and <code>wp_get_attachment_image_src()</code> functions:<br>\n1.) <a href=\"https://developer.wordpress.org/reference/functions/register_rest_field/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/register_rest_field/</a><br>\n2.) <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n\n<p>**Note: Don't forget <code><?php ?></code> tags if this is a new php file!</p>\n"
},
{
"answer_id": 377663,
"author": "Idriss elbaz",
"author_id": 197054,
"author_profile": "https://wordpress.stackexchange.com/users/197054",
"pm_score": 2,
"selected": false,
"text": "<p>Adding &_embed to your URL will add the wp:featuremedia to your JSON\neven if you have custom posts,\nExample</p>\n<pre><code>https://example.com/wp-json/wp/v2/posts?search=Sometitlepost&_embed&order=asc\n</code></pre>\n"
}
] |
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 locating files as per your current folder structure.</p>\n\n<p>I have added convert function and updated your autoloader function.</p>\n\n<p>In <code>wp-plugin-template/autoloader.php</code>:</p>\n\n<pre><code><?php\nspl_autoload_register( 'autoload_function' );\nfunction autoload_function( $classname ) {\n $class = str_replace( '\\\\', DIRECTORY_SEPARATOR, str_replace( '_', '-', strtolower(convert($classname)) ) );\n # Create the actual file-path\n $path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $class . '.php';\n # Check if the file exists\n if ( file_exists( $path ) ) {\n # Require once on the file\n require_once $path;\n }\n}\n\nfunction convert($class){\n $class = preg_replace('#([A-Z\\d]+)([A-Z][a-z])#','\\1_\\2', $class);\n $class = preg_replace('#([a-z\\d])([A-Z])#', '\\1_\\2', $class);\n return $class;\n}\n</code></pre>\n\n<p>Also you have to update your top level namespace to <code>WpPluginTemplate</code> in both <code>wp-plugin-template.php</code> and <code>admin/plugin-meta.php</code> as you are using wp-plugin-template as your plugin folder name.</p>\n\n<p>UPDATE:</p>\n\n<p>When autoloader tries to find <code>Plugin_Meta</code> class, it will look into YOUR_PLUGIN_DIR/wp-plugin-template/admin/plugin-meta.php</p>\n\n<p>In <code>wp-plugin-template.php</code></p>\n\n<pre><code><?php\n/**\n * Plugin Name: WP Plugin Template\n */\n# If accessed directly, exit\nif ( ! defined( 'ABSPATH' ) ) exit;\n# Call the autoloader\nrequire_once( 'autoloader.php' );\n\nuse WpPluginTemplate\\admin\\Plugin_Meta;\nnew Plugin_Meta;\n</code></pre>\n\n<p>In <code>wp-plugin-template/admin/plugin-meta.php</code></p>\n\n<pre><code><?php\nnamespace WpPluginTemplate\\admin;\nclass Plugin_Meta {\n public function __construct() {\n add_action( 'plugins_loaded', array($this, 'test' ) );\n }\n\n public function test() {\n echo 'It works!';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 241297,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p><em>Just some additional note about your autoloader:</em></p>\n\n<p>If the <code>$classname</code> input is <code>PluginTemplate\\admin\\Plugin_Meta</code> then the <code>$path</code> becomes</p>\n\n<pre><code>/full/path/to/wp-content/plugins/plugintemplate/admin/plugin-meta.php\n</code></pre>\n\n<p>and this file doesn't exists and the <code>Plugin_Meta</code> class definition isn't loaded.</p>\n\n<p>It's also <a href=\"https://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Constants\" rel=\"nofollow\">not recommended</a> to use the <code>WP_PLUGIN_DIR</code> constant directly, there are alternatives, like <code>plugin_dir_path( __FILE__ )</code>.</p>\n\n<p>There are more complete autoloaders out there, e.g. the <a href=\"https://getcomposer.org/doc/01-basic-usage.md#autoloading\" rel=\"nofollow\">generated autoloader in Composer</a>.</p>\n"
}
] |
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><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{QUERY_STRING} ^taxo=([^&]+)&([^=]+)=([^&]+)&([^=]+)=([^&]+)&([^=]+)=(.*)$\nRewriteRule ^/?$ /%1/%2/%3/%4/%5/%6/%7? [L,R=301]\n</IfModule>\n</code></pre>\n\n<p>Clear your browser's cache and any domain that follows this structure:</p>\n\n<pre><code>http://www.example.com/?page_id=7848&preview=true\n</code></pre>\n\n<p>Will redirect to:</p>\n\n<pre><code>http://www.example.com/index.php?page_id=7848&preview=true\n</code></pre>\n\n<p>This has been verified and tested on my end using the <a href=\"http://htaccess.mwl.be/\" rel=\"nofollow\">htaccess tester</a>.</p>\n"
},
{
"answer_id": 241305,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>Don't change your rewrites. Put the content of the HTML file into a front-page.php template file in your theme. </p>\n"
}
] |
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><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{QUERY_STRING} ^taxo=([^&]+)&([^=]+)=([^&]+)&([^=]+)=([^&]+)&([^=]+)=(.*)$\nRewriteRule ^/?$ /%1/%2/%3/%4/%5/%6/%7? [L,R=301]\n</IfModule>\n</code></pre>\n\n<p>Clear your browser's cache and any domain that follows this structure:</p>\n\n<pre><code>http://www.example.com/?page_id=7848&preview=true\n</code></pre>\n\n<p>Will redirect to:</p>\n\n<pre><code>http://www.example.com/index.php?page_id=7848&preview=true\n</code></pre>\n\n<p>This has been verified and tested on my end using the <a href=\"http://htaccess.mwl.be/\" rel=\"nofollow\">htaccess tester</a>.</p>\n"
},
{
"answer_id": 241305,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>Don't change your rewrites. Put the content of the HTML file into a front-page.php template file in your theme. </p>\n"
}
] |
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-create-additional-image-sizes-in-wordpress/\" rel=\"nofollow\"><code>add_image_size()</code></a>, for example:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'cyb_add_image_sizes' );\nfunction cyb_add_image_sizes() {\n add_image_size( 'my-image-size-name', 120, 120, true );\n}\n</code></pre>\n\n<p>Then, you can use the <code>image_size_names_choose</code> filter (you have misspelled it with <code>image_size_names_chooser</code>):</p>\n\n<pre><code>add_filter( 'image_size_names_choose', 'rudr_new_image_sizes' );\nfunction rudr_new_image_sizes( $sizes ) {\n\n $addsizes = array(\n \"my-image-size-name\" => 'Misha size'\n );\n\n $newsizes = array_merge( $sizes, $addsizes );\n\n return $newsizes;\n\n}\n</code></pre>\n"
},
{
"answer_id": 278801,
"author": "Ravi Patel",
"author_id": 35477,
"author_profile": "https://wordpress.stackexchange.com/users/35477",
"pm_score": 0,
"selected": false,
"text": "<p>You have used wrong filter function right name is <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/image_size_names_choose\" rel=\"nofollow noreferrer\">image_size_names_choose</a></p>\n\n<pre><code>Old : add_filter('image_size_names_chooser', 'new_image_sizes');\n\nReplace : add_filter('image_size_names_choose', 'new_image_sizes');\n</code></pre>\n\n<p>IF Need to display this option on old images (before applied this code) resize again using image resize plugin. </p>\n"
},
{
"answer_id": 291179,
"author": "Hudri",
"author_id": 134963,
"author_profile": "https://wordpress.stackexchange.com/users/134963",
"pm_score": 0,
"selected": false,
"text": "<p>I've had a very similar issue, and in my case it was the browser's adblocker addon:</p>\n\n<p>I've added 3 new image sizes, and while all three were generated correctly, one specific size did not show up in the editor. It turned out that AdblockPlus was blocking images by sizes names, and the image size I had used was coincidentally used for ad banners.</p>\n\n<p>There is a HUGE list of blocked images like\n<code>-300x250.</code>\n<code>-468x60.</code>\n<code>-500-100.</code>\nwhich is exactly Wordpress' image naming scheme.</p>\n\n<p>Disable the ad blocker and everything worked fine again.</p>\n"
}
] |
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 showing up, is that your browser caches the files. Reloading with ctrl-F5 might do the trick.</p>\n\n<p>Another way to force the browser to reload all style sheets would be to attach a version number to it. The version is in the header of <code>style.css</code>. You can append it to all stylesheets like this:</p>\n\n<pre><code>$theme_data = wp_get_theme();\nwp_enqueue_style('style1', get_template_directory_uri() . '/style1.css', '', $theme_data['version'], false);\nwp_enqueue_style('style2', get_template_directory_uri() . '/style2.css', '', $theme_data['version'], false);\n... and so on ...\n</code></pre>\n\n<p>Every time you change the version in <code>style.css</code> the browser will think all stylesheets have a new version and reload them</p>\n"
},
{
"answer_id": 241444,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 2,
"selected": false,
"text": "<p>You are calling your css files with wrong function like in following line of your code</p>\n\n<pre><code>wp_enqueue_style( 'parent-style', get_directory_directory_uri() . 'style.css' );\n</code></pre>\n\n<p>You are using <code>get_directory_directory_uri()</code> function to call files which is not event a function in wordpress.</p>\n\n<p>Files must be called with one of the following two functions</p>\n\n<ol>\n<li><p><strong>get_stylesheeet_directory_uri()</strong> : This function will search files in your active theme's folder. By active theme means, theme that is activated by user from <code>dashboard -> appearace -> theme</code>. In your case child theme is active, so it will search file in your child theme folder.</p></li>\n<li><p><strong>get_template_directory_uri()</strong> : This function will search files in your parent theme's folder.</p></li>\n</ol>\n\n<p>If your files are present in child theme's folder then add this code in <code>functions.php</code> to call your css files</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); \nfunction my_theme_enqueue_styles() { \n wp_enqueue_style( 'parent-style', get_stylesheet_uri() ); //It will call your style.css file\n wp_enqueue_style( 'style1', get_stylesheeet_directory_uri() . '/rtl.css' );\n wp_enqueue_style( 'style2', get_stylesheeet_directory_uri() . '/assets/stylesheet/main.css' ); \n wp_enqueue_style( 'style3', get_stylesheeet_directory_uri() . '/assets/stylesheet/bootstrap.css' ); \n}\n</code></pre>\n\n<p>In the above code <code>parent-style</code>, <code>style1</code>,<code>style2</code>,<code>style1</code> are the user assign name and that name must be unique. \nAnd 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.</p>\n\n<p><strong>Note</strong>: If your files are present in Parent theme's then you need to replace <code>get_stylesheeet_directory_uri</code> with <code>get_template_directory_uri</code> in above code.</p>\n\n<p>For more detail read this <a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"nofollow\">article</a>.</p>\n"
}
] |
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 showing up, is that your browser caches the files. Reloading with ctrl-F5 might do the trick.</p>\n\n<p>Another way to force the browser to reload all style sheets would be to attach a version number to it. The version is in the header of <code>style.css</code>. You can append it to all stylesheets like this:</p>\n\n<pre><code>$theme_data = wp_get_theme();\nwp_enqueue_style('style1', get_template_directory_uri() . '/style1.css', '', $theme_data['version'], false);\nwp_enqueue_style('style2', get_template_directory_uri() . '/style2.css', '', $theme_data['version'], false);\n... and so on ...\n</code></pre>\n\n<p>Every time you change the version in <code>style.css</code> the browser will think all stylesheets have a new version and reload them</p>\n"
},
{
"answer_id": 241444,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 2,
"selected": false,
"text": "<p>You are calling your css files with wrong function like in following line of your code</p>\n\n<pre><code>wp_enqueue_style( 'parent-style', get_directory_directory_uri() . 'style.css' );\n</code></pre>\n\n<p>You are using <code>get_directory_directory_uri()</code> function to call files which is not event a function in wordpress.</p>\n\n<p>Files must be called with one of the following two functions</p>\n\n<ol>\n<li><p><strong>get_stylesheeet_directory_uri()</strong> : This function will search files in your active theme's folder. By active theme means, theme that is activated by user from <code>dashboard -> appearace -> theme</code>. In your case child theme is active, so it will search file in your child theme folder.</p></li>\n<li><p><strong>get_template_directory_uri()</strong> : This function will search files in your parent theme's folder.</p></li>\n</ol>\n\n<p>If your files are present in child theme's folder then add this code in <code>functions.php</code> to call your css files</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); \nfunction my_theme_enqueue_styles() { \n wp_enqueue_style( 'parent-style', get_stylesheet_uri() ); //It will call your style.css file\n wp_enqueue_style( 'style1', get_stylesheeet_directory_uri() . '/rtl.css' );\n wp_enqueue_style( 'style2', get_stylesheeet_directory_uri() . '/assets/stylesheet/main.css' ); \n wp_enqueue_style( 'style3', get_stylesheeet_directory_uri() . '/assets/stylesheet/bootstrap.css' ); \n}\n</code></pre>\n\n<p>In the above code <code>parent-style</code>, <code>style1</code>,<code>style2</code>,<code>style1</code> are the user assign name and that name must be unique. \nAnd 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.</p>\n\n<p><strong>Note</strong>: If your files are present in Parent theme's then you need to replace <code>get_stylesheeet_directory_uri</code> with <code>get_template_directory_uri</code> in above code.</p>\n\n<p>For more detail read this <a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"nofollow\">article</a>.</p>\n"
}
] |
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>. Hope this will solve the problem.</p>\n"
},
{
"answer_id": 242018,
"author": "kaska3er",
"author_id": 104146,
"author_profile": "https://wordpress.stackexchange.com/users/104146",
"pm_score": 1,
"selected": true,
"text": "<p>I solved it!\nYou need to var_dump wp_query on 1st page and on 404 page</p>\n\n<pre><code>add_action( 'pre_get_posts', 'elo_jlb' );\nfunction elo_jlb($query)\n{\n if(!is_admin())\n {\n $query->set('paged', $query->get('page'));\n $query->set('HERE_POST_TYPE_NAME', '');\n }\n}\n</code></pre>\n"
}
] |
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
[email protected]. 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 = '[email protected]';
//$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"
},
{
"answer_id": 337866,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is two-fold. First, setting the <code>$emailTo</code> <strong>after</strong> the header value where that variable is used (so it's empty in the header). </p>\n\n<p>Second, the <code>$header</code> value that is set is not used in the actual call to <code>wp_mail()</code>. Instead it passes an empty value. (It is set in the line before, but it is commented out, presumably for testing.)</p>\n\n<p>Here's the problematic section:</p>\n\n<pre><code>$headers = 'From: \"Klantenservice\"<' . $emailTo . '>' . \"\\r\\n\";\n$emailTo = '[email protected]';\n//$mail = wp_mail($user_email, $subject, $body, $headers);\n$mail = wp_mail($emailTo, 'Contact verzoek', $body, '');\n</code></pre>\n\n<p>Here's what it should be:</p>\n\n<pre><code>$emailTo = '[email protected]';\n$headers = 'From: \"Klantenservice\"<' . $emailTo . '>' . \"\\r\\n\";\n//$mail = wp_mail($user_email, $subject, $body, $headers);\n$mail = wp_mail($emailTo, 'Contact verzoek', $body, $headers);\n</code></pre>\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
[email protected]. 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 = '[email protected]';
//$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 functions.php and change the \"message\" accordingly. Happy coding :) </p>\n\n<pre><code><?php add_filter( 'the_password_form', 'custom_password_form' );\nfunction custom_password_form() {\nglobal $post;\n$label = 'pwbox-'.(empty($post->ID) ? rand() : $post->ID);\n$output = '<form action=\"' . get_option('siteurl') . '/wp-pass.php\" method=\"post\">\n<p>' . __(\"This section of the site is password protected. To view it please enter your password below:\") . '</p>\n<p><label for=\"' . $label . '\">' . __(\"Password:\") . ' <input name=\"post_password\" id=\"' . $label . '\" type=\"password\" size=\"20\" /></label> <input type=\"submit\" name=\"Submit\" value=\"' . esc_attr__(\"Submit\") . '\" /></p>\n</form>';\n\n if (isset($_COOKIE['wp-postpass_' . COOKIEHASH])\n and $_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password){ ?>\n <p style=\"color:#C00;\">Password Invalid, please try again.</p>\n\n <?php } else { ?>\n</code></pre>\n\n \n \n"
},
{
"answer_id": 241427,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a combination of these two great answers (<a href=\"https://wordpress.stackexchange.com/questions/21697/password-protected-post-or-page-error-message-by-wrong-password\">21697</a> & <a href=\"https://wordpress.stackexchange.com/questions/71284/add-error-message-on-password-protected-page\">71284</a>) to similar questions.</p>\n\n<p><code>wpse241424_check_post_pass()</code> runs early on the <code>wp</code> hook on single password protected pages. If an invalid password is entered, the <code>INVALID_POST_PASS</code> 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.</p>\n\n<p><code>wpse241424_post_password_message()</code> is run right before rendering the password form. It checks for the <code>INVALID_POST_PASS</code> constant that it set earlier when an invalid password is encountered, and adds the error message to the form.</p>\n\n<pre><code>function wpse241424_check_post_pass() {\n\n if ( ! is_single() || ! post_password_required() ) {\n return;\n }\n\n if ( isset( $_COOKIE['wp-postpass_' . COOKIEHASH ] ) ) {\n define( 'INVALID_POST_PASS', true );\n\n // Tell the browser to remove the cookie so the message doesn't show up every time\n setcookie( 'wp-postpass_' . COOKIEHASH, NULL, -1, COOKIEPATH );\n }\n}\nadd_action( 'wp', 'wpse241424_check_post_pass' );\n\n\n/**\n * Add a message to the password form if an invalid password has been entered.\n *\n * @wp-hook the_password_form\n * @param string $form\n * @return string\n */\nfunction wpse241424_post_password_message( $form ) {\n if ( ! defined( 'INVALID_POST_PASS' ) ) {\n return $form;\n }\n\n // Translate and escape.\n $msg = esc_html__( 'Sorry, your password is wrong.', 'your_text_domain' );\n\n // We have a cookie, but it doesn’t match the password.\n $msg = \"<p class='custom-password-message'>$msg</p>\";\n\n return $msg . $form;\n}\nadd_filter( 'the_password_form', 'wpse241424_post_password_message' );\n</code></pre>\n"
},
{
"answer_id": 382668,
"author": "Carolina Lallana",
"author_id": 201324,
"author_profile": "https://wordpress.stackexchange.com/users/201324",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'the_password_form', 'wpse_71284_custom_post_password_msg' );\n\n/**\n * Add a message to the password form.\n *\n * @wp-hook the_password_form\n * @param string $form\n * @return string\n */\nfunction wpse_71284_custom_post_password_msg( $form )\n{\n // No cookie, the user has not sent anything until now.\n if ( ! isset ( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) )\n return $form;\n\n // Translate and escape.\n $msg = esc_html__( 'La contraseña es incorrecta o ya ha sido utilizada.', 'your_text_domain' );\n\n // We have a cookie, but it doesn’t match the password.\n $msg = "<p class='custom-password-message'>$msg</p>";\n\n return $msg . $form;\n}\n\nadd_action('init', 'myStartSession', 1);\nadd_action('wp_logout', 'myEndSession');\nadd_action('wp_login', 'myEndSession');\nfunction myStartSession() {\n if(!session_id()) {\n session_start();\n }\n}\nfunction myEndSession() {\n session_destroy ();\n}\n\n\nif ( post_password_required() ) {\n $session_id = 'wp-postpass_' . get_the_ID();\n //onload\n $current_cookie = wp_unslash($_COOKIE[ 'wp-postpass_' . COOKIEHASH ]);\n //get old cookie \n $old_cookie = isset( $_SESSION[ $session_id ] ) ? $_SESSION[ $session_id ] : '';\n //set new session\n $_SESSION[ $session_id ] = $current_cookie;\n if ( $current_cookie != $old_cookie && !empty( $old_cookie ) ){\n error_notification('<b>Error!</b> Authentication failed!');\n }\n }\n?>\n</code></pre>\n"
}
] |
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/body_class/\" rel=\"nofollow\">class <code>logged-in</code> added to the body</a> whenever a user is logged in. You could use this class to differentiate the view for members (if they are logged in) and non-members.</p>\n\n<p>Beware that the html sent to the browser will be identical in both cases. This means users can add/remove the <code>logged-in</code> tag in their browser and the css will give the other view. So, this is not a good course if you want to show exlusive information to members. Non-members will be able to see it in the html source.</p>\n"
},
{
"answer_id": 241456,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": true,
"text": "<p>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. </p>\n\n<pre><code>body > footer {\n background: black;\n}\n\nbody.logged-in > footer {\n background: red;\n}\n</code></pre>\n\n<p>for example. </p>\n\n<p>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. </p>\n"
},
{
"answer_id": 242698,
"author": "Babidi",
"author_id": 48839,
"author_profile": "https://wordpress.stackexchange.com/users/48839",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this with CSS only but is not safe if you want to display information for only logged in users. Because they can rename the 'logged-in' class in an inspector.</p>\n\n<p>You can use the function <code>is_user_logged_in()</code>and put it in an <code>if else</code> statement for showing different footer styles or HTML markup.\n<a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/is_user_logged_in/</a></p>\n"
}
] |
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>'terms' => array( $MyCustomField ),\n</code></pre>\n\n<p>The query consider it as only one value: <code>'64,72'</code>, a string.</p>\n\n<p>So try:</p>\n\n<pre><code>$MyCustomFieldValues = array_map( 'intval', explode( ',', $MyCustomField ) );\n</code></pre>\n\n<p>This will also ensure your values are integers. </p>\n\n<p>Then: </p>\n\n<pre><code>'terms' => $MyCustomFieldValues,\n</code></pre>\n"
},
{
"answer_id": 241482,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 2,
"selected": false,
"text": "<p>If you are passing in the text (string) \"64,72\" to a function that expects an array of integers, then you need to translate that incoming string into an integer array. Try adding this statement before your <code>$args =</code> statement:</p>\n\n<pre><code>$MyCustomField = array_map('intval', explode(',', $MyCustomField));\n</code></pre>\n"
},
{
"answer_id": 241483,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 2,
"selected": false,
"text": "<p>From the WordPress codex:</p>\n\n<blockquote>\n <p>relation (string) - The logical relationship between each inner\n taxonomy array when there is more than one. Possible values are 'AND',\n 'OR'. Do not use with a single inner taxonomy array.</p>\n</blockquote>\n\n<p>Few other things too, you should be saving the values to the custom meta as an array, WordPress will automatically serialize that value:</p>\n\n<p>Using <code>update_post_meta</code> will automatically serialize any array you pass it:</p>\n\n<pre><code>update_post_meta( $post_id, 'MyCustomField', array( 64, 72 ) );\n</code></pre>\n\n<p>Then you can just unserialize it when pulling the value:</p>\n\n<pre><code>$MyCustomField = maybe_unserialize( get_post_meta( $post->ID, 'MyCustomField', TRUE ) );\n</code></pre>\n\n<p>You should probably also check to make sure you have a value before making the WP_Query call</p>\n\n<pre><code>if( ! empty( $MyCustomField ) ){\n\n $args = array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n 'posts_per_page' => '3',\n 'orderby' => 'rand',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'product_cat',\n 'field' => 'term_id',\n 'terms' => $MyCustomField,\n ),\n ),\n );\n\n}\n</code></pre>\n\n<p>If your plan is to add these values through the WP Admin interface (meaning you want to input a CSV), then you should use @ClemC approach, and use <code>explode</code>, with <code>array_map</code> to convert to integers</p>\n"
}
] |
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.wordpress.org/plugins/simple-contact-form/\" rel=\"nofollow noreferrer\">this</a> Simple Contact Form -- try changing the name to something like \"Wilco's Simple Contact Form\". </p>\n\n<p>You'll need to update the plugin folder name and the main plugin file name as well.</p>\n\n<p><strong>Update</strong></p>\n\n<p>As <a href=\"https://wordpress.stackexchange.com/users/104130/aniket\">Aniket</a> 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 <code>http://yourwebsite.com/wp-admin/update-core.php?force-check=1</code></p>\n"
},
{
"answer_id": 241479,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>As i can see you have named your custom form as 'Simple Contact Form' which conflicts with this plugin name <a href=\"https://wordpress.org/plugins/simple-contact-form/\" rel=\"nofollow\">Simple Contact Form</a>. Try changing the name.<br/>\n<strong>Edit1:</strong> You can also change the version if you don't want to change the name of the plugin. For eg: if you are prompted something like </p>\n\n<blockquote>\n <p>There is a new version of Simple Contact Form. <a href=\"http://#\" rel=\"nofollow\">View version 14.13 details</a> or <a href=\"http://#\" rel=\"nofollow\">update now</a>.</p>\n</blockquote>\n\n<p>then just rename the version of your plugin to 14.13 or above</p>\n"
}
] |
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/Filter_Reference/comments_template\" rel=\"nofollow\">an absolute filepath to the comments template</a> - use <code>comment_form_defaults</code> and set the <code>class_form</code> argument:</p>\n\n<pre><code>add_filter( 'comment_form_defaults', function ( $args ) {\n $args['class_form'] = 'my form classes';\n return $args;\n});\n</code></pre>\n"
},
{
"answer_id": 241507,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>The filter you are using is <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/comments_template\" rel=\"nofollow\">about the template path</a>, it doesn't do anything with the form output. The class you want to add doesn't need a filter. You can set it when you set the arguments for your call to <a href=\"https://developer.wordpress.org/reference/functions/comment_form/\" rel=\"nofollow\"><code>comment_form</code></a> in your template.</p>\n\n<pre><code>$comment_args = array (\n 'id_form' => 'comment-form',\n 'class_form' => 'comment-form pure-form',\n ....\n );\n$comment_form ($comment_args);\n</code></pre>\n"
}
] |
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' => 'bob', 'password' => '1234xyz' ),\n</code></pre>\n\n<p>read <a href=\"https://codex.wordpress.org/Function_Reference/wp_remote_post\" rel=\"nofollow\">more</a> for details.</p>\n\n<p>p.s. I doubt when you converted <code>$xml</code> to array, it couldnt work, because in that case you could have got:</p>\n\n<pre><code>'body' => array( array(........)) \n</code></pre>\n"
},
{
"answer_id": 241571,
"author": "Jason",
"author_id": 104148,
"author_profile": "https://wordpress.stackexchange.com/users/104148",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<p>Here is the working code in case it helps someone else:</p>\n\n<pre><code>// Sends the xml request to the API\n$result = wp_remote_post(\n $this->settings['api_url'],\n array(\n 'method' => 'POST',\n 'timeout' => 45,\n 'redirection' => 5,\n 'httpversion' => '1.1',\n 'headers' => array(\n 'Content-Type' => 'text/xml'\n ),\n 'body' => $xml,\n 'sslverify' => 'false'\n )\n);\n</code></pre>\n"
}
] |
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>number_format() is the php function that is setting the decimals in your first bit of code above.</p>\n\n<p>See <a href=\"http://php.net/manual/en/function.number-format.php\" rel=\"nofollow\">http://php.net/manual/en/function.number-format.php</a></p>\n"
},
{
"answer_id": 241564,
"author": "Nik",
"author_id": 104225,
"author_profile": "https://wordpress.stackexchange.com/users/104225",
"pm_score": 0,
"selected": false,
"text": "<p>Using Jason's answer this is what I came up with that works. If you need a subtotal minus the orders discount this should work.</p>\n\n<pre><code>$orderSubtotal = $order->get_subtotal();\n$discountsTotal = $order->get_total_discount();\necho $sign.number_format( ($orderSubtotal - $discountsTotal), 2);\n</code></pre>\n"
}
] |
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 --cat=your_category_ID --format=ids)\n</code></pre>\n\n<p><strong>Or</strong> directly:</p>\n\n<pre><code>wp db query [<your_sql_query>]\n</code></pre>\n\n<p>For more info:</p>\n\n<pre><code>wp post delete --help\nwp post list --help\nwp db query --help\n</code></pre>\n"
},
{
"answer_id": 358614,
"author": "makmour",
"author_id": 182687,
"author_profile": "https://wordpress.stackexchange.com/users/182687",
"pm_score": 0,
"selected": false,
"text": "<p>Actually update wp-cli needs to use the following command to delete all products for a category of Woocommerce installation:</p>\n\n<pre><code>wp post delete $(wp wc product list --category=category_id --user=admin_username) --force\n</code></pre>\n\n<p>Since Woo only allows to delete 100 products per time you can use the following <strong>bash command to create loops using a step value of 100.</strong></p>\n\n<pre><code>for run in {1..2}; do wp post delete $(wp wc product list --category=category_id --user=admin_username) --force; done\n</code></pre>\n\n<p>this one deletes 200 products in 2 steps of 100 product each</p>\n\n<pre><code>for run in {1..3}; do wp post delete $(wp wc product list\n--category=category_id --user=admin_username) --force; done\n</code></pre>\n\n<p>this one deletes 300 products in 3 steps of 100 product each</p>\n\n<p>and so on...</p>\n"
}
] |
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 --cat=your_category_ID --format=ids)\n</code></pre>\n\n<p><strong>Or</strong> directly:</p>\n\n<pre><code>wp db query [<your_sql_query>]\n</code></pre>\n\n<p>For more info:</p>\n\n<pre><code>wp post delete --help\nwp post list --help\nwp db query --help\n</code></pre>\n"
},
{
"answer_id": 358614,
"author": "makmour",
"author_id": 182687,
"author_profile": "https://wordpress.stackexchange.com/users/182687",
"pm_score": 0,
"selected": false,
"text": "<p>Actually update wp-cli needs to use the following command to delete all products for a category of Woocommerce installation:</p>\n\n<pre><code>wp post delete $(wp wc product list --category=category_id --user=admin_username) --force\n</code></pre>\n\n<p>Since Woo only allows to delete 100 products per time you can use the following <strong>bash command to create loops using a step value of 100.</strong></p>\n\n<pre><code>for run in {1..2}; do wp post delete $(wp wc product list --category=category_id --user=admin_username) --force; done\n</code></pre>\n\n<p>this one deletes 200 products in 2 steps of 100 product each</p>\n\n<pre><code>for run in {1..3}; do wp post delete $(wp wc product list\n--category=category_id --user=admin_username) --force; done\n</code></pre>\n\n<p>this one deletes 300 products in 3 steps of 100 product each</p>\n\n<p>and so on...</p>\n"
}
] |
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>publish</em>.</p>\n\n<p>You should also use <code>=</code> instead of <code>LIKE</code>, to avoid using <code>LIKE '%%'</code> in the SQL query.</p>\n\n<p>So try to add this:</p>\n\n<pre><code>'post_status' => 'inherit'\n</code></pre>\n\n<p>and</p>\n\n<pre><code>'compare' => '='\n</code></pre>\n\n<p>into your query arguments, to match the empty <code>_wp_attachment_image_alt</code> string values.</p>\n"
},
{
"answer_id": 241606,
"author": "pawan",
"author_id": 104260,
"author_profile": "https://wordpress.stackexchange.com/users/104260",
"pm_score": -1,
"selected": false,
"text": "<pre><code>'meta_query' => array(\n array(\n 'key' => '_wp_attachment_image_alt',\n 'compare' => 'NOT EXISTS' // this should work...\n ),\n)\n</code></pre>\n"
}
] |
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 the DB and then generated using PHP functions, I don't think you can get this using the default wp-cli commands.</p>\n\n<p>However you can install the <a href=\"https://wp-cli.org/restful/\" rel=\"nofollow\">RESTful wp-cli package</a> as well as the WordPress <a href=\"https://wordpress.org/plugins/rest-api/\" rel=\"nofollow\">REST API plugin</a> to get the image URL easily, just do:</p>\n\n<pre><code># Install dependencies\nwp package install wp-cli/restful && wp plugin install rest-api --activate\n\n# Print URL\nwp rest attachment get $image_id --field=source_url\n</code></pre>\n"
},
{
"answer_id": 246208,
"author": "Ezra Free",
"author_id": 73451,
"author_profile": "https://wordpress.stackexchange.com/users/73451",
"pm_score": 2,
"selected": true,
"text": "<p>Assuming the attachment ID were in a variable of <code>$attachment_id</code> you could use the following command:</p>\n\n<pre><code># get attachment URL\nwp db query \"SELECT guid FROM $(wp db tables *_posts) WHERE ID=\\\"$attachment_id\\\"\" | head -n 2 | tail -1\n</code></pre>\n\n<p>I use the <code>$(wp db tables *_posts)</code> bit just in case the <code>wp_</code> table prefix is non-default.</p>\n"
},
{
"answer_id": 252283,
"author": "Mateusz Marchel",
"author_id": 83704,
"author_profile": "https://wordpress.stackexchange.com/users/83704",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to get original uploaded file url, you can do it this way:</p>\n\n<pre><code>wp post get <ID> --field='guid'\n</code></pre>\n\n<p>This will return <code>guid</code> column (which is absolute url) from wp_posts table for given ID.</p>\n\n<p>If you want to get some file generated from your original file, you have to alter filename at the end of the url to reflect some of the generated sizes. You can get filenames for all sizes from serialized array stored in wp_postmeta for this image. Meta key is <code>_wp_attachment_metadata</code>. Try following command to get this with wp cli </p>\n\n<pre><code> wp post meta get <ID> _wp_attachment_metadata\n</code></pre>\n"
},
{
"answer_id": 315451,
"author": "GainRider",
"author_id": 151459,
"author_profile": "https://wordpress.stackexchange.com/users/151459",
"pm_score": 2,
"selected": false,
"text": "<p>WP-CLI as of v1.4.0 can extract and store serialized data with the \"pluck\" and \"patch\" commands.</p>\n\n<p>In the above case, a problem I needed to solve, I use the expression below to obtain the source image filename from a post ID (the post the image is attached to):</p>\n\n<pre><code>wp post meta pluck $(wp post meta get <post_ID> _thumbnail_id) _wp_attachment_metadata file\n</code></pre>\n\n<p>Note that this code will pull the relative post media path, e.g.: 2018/09/. The dirname portion can easily be stripped with e.g.:</p>\n\n<pre><code>basename \"$(wp post meta pluck $(wp post meta get <post_ID> _thumbnail_id) _wp_attachment_metadata file)\"\n</code></pre>\n"
}
] |
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 holders to proper html content.</p>\n"
},
{
"answer_id": 241645,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 2,
"selected": false,
"text": "<p>Please have a try with this-</p>\n\n<pre><code><a href=\"https://example.com/folder/edit.php?action=someaction&id=<?php echo do_shortcode(\"[foocode parameter='value']\"); ?>&edittoken=<?php echo do_shortcode(\"[foocode parameter='othervalue']\"); ?>\">linktext</a>\n</code></pre>\n"
},
{
"answer_id": 260578,
"author": "Máximo Obed Leza Correa",
"author_id": 115724,
"author_profile": "https://wordpress.stackexchange.com/users/115724",
"pm_score": 3,
"selected": false,
"text": "<p>Hope this helps someone:</p>\n<p>Instead of doing this: <code><a href="https://example.com/folder/edit.php?action=someaction&id=[foocode parameter='value']&edittoken=[foocode parameter='othervalue']">linktext</a></code></p>\n<p>You can do this: <code>[foocode parameter1=value parameter2=othervalue]</code> and then do this:</p>\n<pre><code>add_shortcode( 'foocode', 'prefix_foocode' );\n\nfunction prefix_foocode( $atts ) {\n\n // Normalize $atts, set defaults and do whatever you want with $atts.\n\n $html = '<a href="https://example.com/folder/edit.php?action=someaction&id=' . $atts['parameter1'] .'&edittoken=' . $atts['parameter2'] . '">linktext</a>';\nreturn $html;\n}\n</code></pre>\n"
},
{
"answer_id": 272785,
"author": "Crazycoolcam",
"author_id": 28144,
"author_profile": "https://wordpress.stackexchange.com/users/28144",
"pm_score": 2,
"selected": false,
"text": "<p>For what it's worth, shortcodes that don't accept any parameters appear to work in HTML tags. It's the ones that have parameters that don't.</p>\n\n<p>Ex: <code><a href=\"https://example.com/folder/edit.php?action=someaction&id=[foocode parameter='value']&edittoken=[foocode parameter='othervalue']\">linktext</a></code> doesn't work</p>\n\n<p>Ex: <code><a href=\"https://example.com/folder/edit.php?action=someaction&id=[foocode]&edittoken=[foo-other-code]\">linktext</a></code> does work (at least for me)</p>\n\n<p>I have used a simple shortcode like this to output the path for images on my site so I don't have to remember the path each time (I don't use the media manager).</p>\n\n<p>Hope this helps someone who may stumble on this question later. </p>\n"
},
{
"answer_id": 298176,
"author": "sheetal",
"author_id": 111904,
"author_profile": "https://wordpress.stackexchange.com/users/111904",
"pm_score": 0,
"selected": false,
"text": "<p>For executing the shortcode inside the raw HTML element you would have to find the callback function that is being called via shortcode and then echo that function out in the raw html element.</p>\n\n<p>For example if your shortcode is <code>[foo_code]</code>, then find out which function is being called back when this function is being executed by finding the add_shortcode() for this shortcode (in this case [foo_code])-</p>\n\n<pre><code>add_shortcode('foo_code', 'foo_callback_function');\n</code></pre>\n\n<p>Now, when you know which function is being called you can simply echo this function in the raw html like:</p>\n\n<pre><code>[echo foo_callback_function();]\n</code></pre>\n\n<p>For more details, about why it works checkout <a href=\"https://wordpress.stackexchange.com/a/177412/111904\" title=\"this answer\">this answer</a>.\nHope it helps!</p>\n"
}
] |
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-latex/\" rel=\"nofollow\">https://en-gb.wordpress.org/plugins/wp-latex/</a> (caveat - although I'm familiar with LaTeX, I haven't personally used this). You can set up an image generation server locally or use WordPress's own.</p>\n"
},
{
"answer_id": 241657,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>The Wordpress-produced plugin Jetpack has LaTeX support. See this <a href=\"https://jetpack.com/support/beautiful-math-with-latex/\" rel=\"nofollow\">link</a>. 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.</p>\n"
}
] |
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 noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>orderby should be <code>meta_value</code></p>\n\n<blockquote>\n <p>'meta_value' - Note that a 'meta_key=keyname' must also be present in the query.</p>\n</blockquote>\n\n<p>Your key name should be one of the: CPU, OS, RAM ...</p>\n\n<p>Also you can consider the <code>WP_Meta_Query</code> class.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Meta_Query</a></p>\n\n<hr>\n\n<h2>The Update</h2>\n\n<hr>\n\n<p>I got this result</p>\n\n<pre><code> Array\n(\n [0] => WP_Post Object\n (\n [ID] => 3233\n [post_author] => 1\n [post_date] => 2016-11-19 12:51:43\n [post_date_gmt] => 2016-11-19 12:51:43\n [post_content] => abc\n [post_title] => Mac Air Pro 9G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-3\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:19\n [post_modified_gmt] => 2016-11-19 12:52:19\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/laptop/mac-air-pro-1-copy/\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n [1] => WP_Post Object\n (\n [ID] => 3232\n [post_author] => 1\n [post_date] => 2016-11-19 12:46:50\n [post_date_gmt] => 2016-11-19 12:46:50\n [post_content] => abc\n [post_title] => Mac Air Pro 8G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-2\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:47\n [post_modified_gmt] => 2016-11-19 12:52:47\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/laptop/mac-air-pro-1-copy/\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n [2] => WP_Post Object\n (\n [ID] => 3231\n [post_author] => 1\n [post_date] => 2016-11-19 12:12:38\n [post_date_gmt] => 2016-11-19 12:12:38\n [post_content] => abc\n [post_title] => Mac Air Pro 4G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-1\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:57\n [post_modified_gmt] => 2016-11-19 12:52:57\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/?post_type=laptop&#038;p=3231\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n)\n</code></pre>\n\n<p>Here is the content of the single-laptop.php file:</p>\n\n<pre><code><?php\n/**\n * The template for displaying all single posts.\n *\n * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\n *\n * @package microformats\n */\n\nget_header(); \n\n\n// WP_Query arguments\n$args = array (\n 'post_type' => array( 'laptop' ),\n 'post_status' => array( 'published' ),\n //'s' => 'atom', // only if you need that\n 'nopaging' => true,\n 'posts_per_page' => '-1',\n 'ignore_sticky_posts' => true,\n // order\n 'orderby' => 'meta_value', \n 'meta_key' => 'ram',\n 'order' =>'DESC',\n /* you will need this only if\n 'meta_query' => array(\n array(\n 'key' => 'ram', // or os, or cpu\n 'value' => '4', // meaning 4G of ram\n 'compare' => '>', // meaning only biggar\n 'type' => 'NUMERIC',\n ),\n ),\n */\n);\n\n\n// The Query\n$query = new WP_Query( $args );\nprint_r($query->posts);\n\n\n?>\n\n <div id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\" role=\"main\">\n\n <?php while ( have_posts() ) : the_post(); ?>\n\n <?php get_template_part( 'template-parts/content', 'single' ); ?>\n\n <?php\n // If comments are open or we have at least one comment, load up the comment template.\n if ( comments_open() || get_comments_number() ) :\n comments_template();\n endif;\n ?>\n\n\n <hr class=\"fat\" /> \n\n <?php endwhile; // End of the loop. ?>\n\n </main><!-- #main -->\n </div><!-- #primary -->\n\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 258877,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": true,
"text": "<p>To follow up on @rock3t's comment, do you really have to query the backend whenever a user clicks on a column header?</p>\n\n<p>Have you looking into using the jQuery <a href=\"https://plugins.jquery.com/tablesorter/\" rel=\"nofollow noreferrer\">tablesorter</a>? It allows an end-user to sort an HTML table by doing DOM manipulations.</p>\n\n<p>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 <strong>very</strong> configurable, so I'm sure it will satisfy your needs.</p>\n\n<p>tablesorter is <strong>not</strong> 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:</p>\n\n<pre><code>(function ($) {\n $(document).ready (function () { \n $('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ; \n }) ;\n})(jQuery) ;\n</code></pre>\n\n<p>You can read more about how to use tablesort in their <a href=\"https://mottie.github.io/tablesorter/docs/index.html\" rel=\"nofollow noreferrer\">docs</a>, including various other parms to the <code>tablesorter()</code> method.</p>\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 noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>orderby should be <code>meta_value</code></p>\n\n<blockquote>\n <p>'meta_value' - Note that a 'meta_key=keyname' must also be present in the query.</p>\n</blockquote>\n\n<p>Your key name should be one of the: CPU, OS, RAM ...</p>\n\n<p>Also you can consider the <code>WP_Meta_Query</code> class.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Meta_Query</a></p>\n\n<hr>\n\n<h2>The Update</h2>\n\n<hr>\n\n<p>I got this result</p>\n\n<pre><code> Array\n(\n [0] => WP_Post Object\n (\n [ID] => 3233\n [post_author] => 1\n [post_date] => 2016-11-19 12:51:43\n [post_date_gmt] => 2016-11-19 12:51:43\n [post_content] => abc\n [post_title] => Mac Air Pro 9G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-3\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:19\n [post_modified_gmt] => 2016-11-19 12:52:19\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/laptop/mac-air-pro-1-copy/\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n [1] => WP_Post Object\n (\n [ID] => 3232\n [post_author] => 1\n [post_date] => 2016-11-19 12:46:50\n [post_date_gmt] => 2016-11-19 12:46:50\n [post_content] => abc\n [post_title] => Mac Air Pro 8G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-2\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:47\n [post_modified_gmt] => 2016-11-19 12:52:47\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/laptop/mac-air-pro-1-copy/\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n [2] => WP_Post Object\n (\n [ID] => 3231\n [post_author] => 1\n [post_date] => 2016-11-19 12:12:38\n [post_date_gmt] => 2016-11-19 12:12:38\n [post_content] => abc\n [post_title] => Mac Air Pro 4G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-1\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:57\n [post_modified_gmt] => 2016-11-19 12:52:57\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/?post_type=laptop&#038;p=3231\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n)\n</code></pre>\n\n<p>Here is the content of the single-laptop.php file:</p>\n\n<pre><code><?php\n/**\n * The template for displaying all single posts.\n *\n * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\n *\n * @package microformats\n */\n\nget_header(); \n\n\n// WP_Query arguments\n$args = array (\n 'post_type' => array( 'laptop' ),\n 'post_status' => array( 'published' ),\n //'s' => 'atom', // only if you need that\n 'nopaging' => true,\n 'posts_per_page' => '-1',\n 'ignore_sticky_posts' => true,\n // order\n 'orderby' => 'meta_value', \n 'meta_key' => 'ram',\n 'order' =>'DESC',\n /* you will need this only if\n 'meta_query' => array(\n array(\n 'key' => 'ram', // or os, or cpu\n 'value' => '4', // meaning 4G of ram\n 'compare' => '>', // meaning only biggar\n 'type' => 'NUMERIC',\n ),\n ),\n */\n);\n\n\n// The Query\n$query = new WP_Query( $args );\nprint_r($query->posts);\n\n\n?>\n\n <div id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\" role=\"main\">\n\n <?php while ( have_posts() ) : the_post(); ?>\n\n <?php get_template_part( 'template-parts/content', 'single' ); ?>\n\n <?php\n // If comments are open or we have at least one comment, load up the comment template.\n if ( comments_open() || get_comments_number() ) :\n comments_template();\n endif;\n ?>\n\n\n <hr class=\"fat\" /> \n\n <?php endwhile; // End of the loop. ?>\n\n </main><!-- #main -->\n </div><!-- #primary -->\n\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 258877,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": true,
"text": "<p>To follow up on @rock3t's comment, do you really have to query the backend whenever a user clicks on a column header?</p>\n\n<p>Have you looking into using the jQuery <a href=\"https://plugins.jquery.com/tablesorter/\" rel=\"nofollow noreferrer\">tablesorter</a>? It allows an end-user to sort an HTML table by doing DOM manipulations.</p>\n\n<p>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 <strong>very</strong> configurable, so I'm sure it will satisfy your needs.</p>\n\n<p>tablesorter is <strong>not</strong> 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:</p>\n\n<pre><code>(function ($) {\n $(document).ready (function () { \n $('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ; \n }) ;\n})(jQuery) ;\n</code></pre>\n\n<p>You can read more about how to use tablesort in their <a href=\"https://mottie.github.io/tablesorter/docs/index.html\" rel=\"nofollow noreferrer\">docs</a>, including various other parms to the <code>tablesorter()</code> method.</p>\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 noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>orderby should be <code>meta_value</code></p>\n\n<blockquote>\n <p>'meta_value' - Note that a 'meta_key=keyname' must also be present in the query.</p>\n</blockquote>\n\n<p>Your key name should be one of the: CPU, OS, RAM ...</p>\n\n<p>Also you can consider the <code>WP_Meta_Query</code> class.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Meta_Query</a></p>\n\n<hr>\n\n<h2>The Update</h2>\n\n<hr>\n\n<p>I got this result</p>\n\n<pre><code> Array\n(\n [0] => WP_Post Object\n (\n [ID] => 3233\n [post_author] => 1\n [post_date] => 2016-11-19 12:51:43\n [post_date_gmt] => 2016-11-19 12:51:43\n [post_content] => abc\n [post_title] => Mac Air Pro 9G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-3\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:19\n [post_modified_gmt] => 2016-11-19 12:52:19\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/laptop/mac-air-pro-1-copy/\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n [1] => WP_Post Object\n (\n [ID] => 3232\n [post_author] => 1\n [post_date] => 2016-11-19 12:46:50\n [post_date_gmt] => 2016-11-19 12:46:50\n [post_content] => abc\n [post_title] => Mac Air Pro 8G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-2\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:47\n [post_modified_gmt] => 2016-11-19 12:52:47\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/laptop/mac-air-pro-1-copy/\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n [2] => WP_Post Object\n (\n [ID] => 3231\n [post_author] => 1\n [post_date] => 2016-11-19 12:12:38\n [post_date_gmt] => 2016-11-19 12:12:38\n [post_content] => abc\n [post_title] => Mac Air Pro 4G\n [post_excerpt] => \n [post_status] => publish\n [comment_status] => closed\n [ping_status] => closed\n [post_password] => \n [post_name] => mac-air-pro-1\n [to_ping] => \n [pinged] => \n [post_modified] => 2016-11-19 12:52:57\n [post_modified_gmt] => 2016-11-19 12:52:57\n [post_content_filtered] => \n [post_parent] => 0\n [guid] => http://steve.com/?post_type=laptop&#038;p=3231\n [menu_order] => 0\n [post_type] => laptop\n [post_mime_type] => \n [comment_count] => 0\n [filter] => raw\n )\n\n)\n</code></pre>\n\n<p>Here is the content of the single-laptop.php file:</p>\n\n<pre><code><?php\n/**\n * The template for displaying all single posts.\n *\n * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post\n *\n * @package microformats\n */\n\nget_header(); \n\n\n// WP_Query arguments\n$args = array (\n 'post_type' => array( 'laptop' ),\n 'post_status' => array( 'published' ),\n //'s' => 'atom', // only if you need that\n 'nopaging' => true,\n 'posts_per_page' => '-1',\n 'ignore_sticky_posts' => true,\n // order\n 'orderby' => 'meta_value', \n 'meta_key' => 'ram',\n 'order' =>'DESC',\n /* you will need this only if\n 'meta_query' => array(\n array(\n 'key' => 'ram', // or os, or cpu\n 'value' => '4', // meaning 4G of ram\n 'compare' => '>', // meaning only biggar\n 'type' => 'NUMERIC',\n ),\n ),\n */\n);\n\n\n// The Query\n$query = new WP_Query( $args );\nprint_r($query->posts);\n\n\n?>\n\n <div id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\" role=\"main\">\n\n <?php while ( have_posts() ) : the_post(); ?>\n\n <?php get_template_part( 'template-parts/content', 'single' ); ?>\n\n <?php\n // If comments are open or we have at least one comment, load up the comment template.\n if ( comments_open() || get_comments_number() ) :\n comments_template();\n endif;\n ?>\n\n\n <hr class=\"fat\" /> \n\n <?php endwhile; // End of the loop. ?>\n\n </main><!-- #main -->\n </div><!-- #primary -->\n\n<?php get_sidebar(); ?>\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 258877,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": true,
"text": "<p>To follow up on @rock3t's comment, do you really have to query the backend whenever a user clicks on a column header?</p>\n\n<p>Have you looking into using the jQuery <a href=\"https://plugins.jquery.com/tablesorter/\" rel=\"nofollow noreferrer\">tablesorter</a>? It allows an end-user to sort an HTML table by doing DOM manipulations.</p>\n\n<p>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 <strong>very</strong> configurable, so I'm sure it will satisfy your needs.</p>\n\n<p>tablesorter is <strong>not</strong> 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:</p>\n\n<pre><code>(function ($) {\n $(document).ready (function () { \n $('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ; \n }) ;\n})(jQuery) ;\n</code></pre>\n\n<p>You can read more about how to use tablesort in their <a href=\"https://mottie.github.io/tablesorter/docs/index.html\" rel=\"nofollow noreferrer\">docs</a>, including various other parms to the <code>tablesorter()</code> method.</p>\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 can fetch all the datas you need.\nIn your theme functions.php</p>\n\n<pre><code>add_shortcode('casestudy', 'myfunction');\nfunction myfunction($atts){\n\n $a = shortcode_atts( array(\n 'study_type' => 'mountain'\n ), $atts );\n $content='';\n // Get your data with get_post_meta\n\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 241754,
"author": "ClemC",
"author_id": 73239,
"author_profile": "https://wordpress.stackexchange.com/users/73239",
"pm_score": 1,
"selected": true,
"text": "<p>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.<br>\nAssuming we have the following shortcode that the user has put inside a <strong>normal</strong> post's content and that this shortcode will pull information from your custom post type <code>case_studies</code>:</p>\n\n<pre><code>[casestudy study_type=\"mountain\"] \n</code></pre>\n\n<p>So firstly, your shortcode handler:</p>\n\n<pre><code>add_shortcode( 'casestudy', 'my_shortcode' );\n\nfunction my_shortcode( $atts ) {\n $a = shortcode_atts( array(\n 'study_type' => 'mountain',\n ), $atts );\n\n $content = my_template( $a );\n\n return $content;\n}\n</code></pre>\n\n<p>Pay close attention to the <a href=\"https://codex.wordpress.org/Function_Reference/shortcode_atts\" rel=\"nofollow\"><code>shortocode_atts()</code></a> function. It's meant to filter the <strong>accepted</strong> parameters that your template function's query below will be able to handle.</p>\n\n<p>Then, your template:</p>\n\n<pre><code>function my_template( $a ) {\n /**\n * I believe we should be in the loop already when this function is being called.\n * So to get the category slug of the current post in which the user has put the shortcode, you can try this.\n */\n $category_terms = get_the_category();\n\n $args = array(\n 'post_type' => 'case_studies',\n 'name' => $a['study_type'],\n 'category_name' => $category_terms[0]->slug,\n 'posts_per_page' => 1,\n );\n\n $query = new WP_Query( $args );\n\n ob_start();\n\n if ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n the_post();\n\n echo '<h3>' . get_the_title() . '</h3>';\n echo '<p>' . get_the_content() . '</p>';\n }\n\n reset_postdata();\n }\n\n return ob_get_clean();\n\n}\n</code></pre>\n"
}
] |
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><code>add_action('wp_enqueue_scripts', array($this, 'enqueue_bootstrap');\n\npublic function enqueue_bootstrap(){\n wp_register_script( 'bootstrap', plugins_url( 'your-plugin/assets/js/bootstrap.min.js' ) );\n wp_enqueue_script( 'bootstrap' );\n}\n</code></pre>\n\n<p>EDIT: </p>\n\n<p>You need to add $content argument to your function.\nAs the codex says </p>\n\n<blockquote>\n <p>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. </p>\n</blockquote>\n\n<p>in your case: </p>\n\n<pre><code>public function dmd_fav_modal_box($content) {\n\n $modal = '<div class=\"modal fade\" id=\"dmd_favorite_modal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"dmd_favorite_modalLabel\">\n <div class=\"modal-dialog\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n </div>\n <div class=\"modal-body\">\n <p>Test</p>\n </div>\n <!--div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n <button type=\"button\" class=\"btn btn-primary\">Save changes</button>\n </div-->\n </div>\n </div>\n</div>';\nreturn $modal.$content;\n</code></pre>\n"
},
{
"answer_id": 241746,
"author": "mattkrupnik",
"author_id": 68981,
"author_profile": "https://wordpress.stackexchange.com/users/68981",
"pm_score": 0,
"selected": false,
"text": "<p>Just in <strong>__construct</strong> add this <strong>add add_action('wp_footer', ''array( $this, 'dmd_fav_modal_box') );</strong> then html part will be added to footer section and should work, also not sure, because when You added it in <strong>wp_head</strong> it also should work but this solution is not recommended. Are You able to post here all class ?</p>\n"
}
] |
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 can add that phrase manually without button). And then just add this code in <code>funcitons.php</code>:</p>\n\n<pre><code>add_shortcode('post_shrtl', function($atts){\n return $GLOBALS['post']->guid;\n});\n</code></pre>\n"
},
{
"answer_id": 241804,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": true,
"text": "<p>If you mean the <em>link dialog</em>, then we can modify the <em>permalinks</em> with the <a href=\"https://developer.wordpress.org/reference/hooks/wp_link_query/\" rel=\"nofollow\"><code>wp_link_query</code></a> filter:</p>\n\n<pre><code>add_filter( 'wp_link_query', function( $results )\n{\n foreach( $results as &$result )\n $result['permalink'] = wp_get_shortlink( $result['ID'] );\n\n return $results;\n} );\n</code></pre>\n\n<p>where we use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_shortlink\" rel=\"nofollow\"><code>wp_get_shortlink()</code></a> to get the <em>short links</em>.</p>\n"
}
] |
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-api-modifying-the-json-response\" rel=\"nofollow noreferrer\">post</a>.</p>\n<p>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:</p>\n<pre><code>function ag_filter_post_json($response, $post, $context) {\n $tags = wp_get_post_tags($post->ID);\n $response->data['tag_names'] = [];\n\n foreach ($tags as $tag) {\n $response->data['tag_names'][] = $tag->name;\n }\n\n return $response;\n}\n\nadd_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 );\n</code></pre>\n<p>It adds the tag names as a new property called <code>tag_names</code>. The rest of the heavy lifting is done by the <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_tags\" rel=\"nofollow noreferrer\"><code>wp_get_post_tags</code></a> function.</p>\n"
},
{
"answer_id": 402866,
"author": "user219393",
"author_id": 219393,
"author_profile": "https://wordpress.stackexchange.com/users/219393",
"pm_score": 0,
"selected": false,
"text": "<p>The approved answer wasn't working for me in Wordpress 5.9. Changing <code>$tags = wp_get_post_tags($post->ID);</code> to <code>$tags = get_the_tags($post->ID);</code>did the trick.</p>\n<p>Also, if you need the slug rather than the name, just update <code>$response->data['tag_names'][] = $tag->name;</code> to <code>$response->data['tag_names'][] = $tag->slug;</code></p>\n"
}
] |
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 * Find the last period in the excerpt and remove everything after it.\n * If no period is found, just return the entire excerpt.\n *\n * @param string $excerpt The post excerpt.\n */\nfunction end_with_sentence( $excerpt ) {\n\n if ( ( $pos = mb_strrpos( $excerpt, '.' ) ) !== false ) {\n $excerpt = substr( $excerpt, 0, $pos + 1 );\n }\n\n return $excerpt;\n}\nadd_filter( 'the_excerpt', 'end_with_sentence' );\n</code></pre>\n"
},
{
"answer_id": 241840,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 0,
"selected": false,
"text": "<p>You need to <code>echo</code> the function <code>get_the_excerpt()</code>.</p>\n\n<p>So in your template use:</p>\n\n<pre><code>echo get_the_excerpt();\n</code></pre>\n"
},
{
"answer_id": 241841,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 1,
"selected": false,
"text": "<p>This will take anything you throw at it ;-) Plus, it's easy to read (kidding, I'm just kidding). </p>\n\n<p>P.S. must be PHP 5.4 or greater...</p>\n\n<pre><code>function end_with_sentence( $excerpt ) {\n // change the '...' to whatever your \"read more\" string is; default in WP is '...'\n $excerpt = explode( '(#~)', str_replace( ['...','? ','! ','. '], ['($/s$/)','?(#~)','!(#~)','. (#~)'], preg_replace( '!\\s+!', ' ', trim( $excerpt ) ) ) );\n return ( !strpos( end( $excerpt ), '($/s$/)' ) ) ? implode( ' ', $excerpt ) : implode( ' ', array_slice( $excerpt, 0, -1 ) );\n}\n</code></pre>\n"
}
] |
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 * Find the last period in the excerpt and remove everything after it.\n * If no period is found, just return the entire excerpt.\n *\n * @param string $excerpt The post excerpt.\n */\nfunction end_with_sentence( $excerpt ) {\n\n if ( ( $pos = mb_strrpos( $excerpt, '.' ) ) !== false ) {\n $excerpt = substr( $excerpt, 0, $pos + 1 );\n }\n\n return $excerpt;\n}\nadd_filter( 'the_excerpt', 'end_with_sentence' );\n</code></pre>\n"
},
{
"answer_id": 241840,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 0,
"selected": false,
"text": "<p>You need to <code>echo</code> the function <code>get_the_excerpt()</code>.</p>\n\n<p>So in your template use:</p>\n\n<pre><code>echo get_the_excerpt();\n</code></pre>\n"
},
{
"answer_id": 241841,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 1,
"selected": false,
"text": "<p>This will take anything you throw at it ;-) Plus, it's easy to read (kidding, I'm just kidding). </p>\n\n<p>P.S. must be PHP 5.4 or greater...</p>\n\n<pre><code>function end_with_sentence( $excerpt ) {\n // change the '...' to whatever your \"read more\" string is; default in WP is '...'\n $excerpt = explode( '(#~)', str_replace( ['...','? ','! ','. '], ['($/s$/)','?(#~)','!(#~)','. (#~)'], preg_replace( '!\\s+!', ' ', trim( $excerpt ) ) ) );\n return ( !strpos( end( $excerpt ), '($/s$/)' ) ) ? implode( ' ', $excerpt ) : implode( ' ', array_slice( $excerpt, 0, -1 ) );\n}\n</code></pre>\n"
}
] |
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 you are not logged in and you are in the frontend, you need to pass the URL to the script.</p>\n\n<p>In your code, you are using this:</p>\n\n<pre><code>url: myMainAjaxObject.ajaxUrl,\n</code></pre>\n\n<p>but <code>myMainAjaxObject.ajaxUrl</code> is not defined. You could do it like this:</p>\n\n<pre><code>wp_localize_script(\n 'my_custom_js', 'myGeoipAjaxObject', \n array( \n 'myGeoipNonce' => wp_create_nonce('my_geoip_nonce'),\n 'ajaxUrl' => admin_url( 'admin-ajax.php' )\n )\n);\n</code></pre>\n\n<p>Now, you can use <code>myMainAjaxObject.ajaxUrl</code> in the frontend and for non-logged in users.</p>\n"
},
{
"answer_id": 241958,
"author": "Dmitry Gamolin",
"author_id": 86509,
"author_profile": "https://wordpress.stackexchange.com/users/86509",
"pm_score": 4,
"selected": true,
"text": "<p>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).</p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
}
] |
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 your own register form and use <a href=\"https://codex.wordpress.org/Function_Reference/register_new_user\" rel=\"nofollow\"><code>register_new_user()</code></a>. You could even manipulate <a href=\"https://codex.wordpress.org/Function_Reference/wp_registration_url\" rel=\"nofollow\"><code>wp_registration_url()</code></a> with the filter <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/register_url\" rel=\"nofollow\"><code>register_url</code></a>, so the register link would point to your new register page.</p>\n\n<p>If you want to use it with the standard interface provided by <em>wp-login.php</em>, 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:</p>\n\n<pre><code>add_action( 'register_form', function() {\n ?><style>#registerform > p:first-child{display:none;}</style><?php\n} );\n</code></pre>\n\n<p>Sidenote: There is also a possibility to enqueue stylesheets into the <em>wp-login.php</em> using the <code>login_enqueue_scripts</code> action.</p>\n\n<p>But if you do so you will send an empty username, so you have to hook into two filters: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/sanitize_user\" rel=\"nofollow\"><code>sanitize_user</code></a> and <code>validate_username</code>.</p>\n\n<pre><code>add_filter( 'sanitize_user', function( $sanitized_user, $raw_user, $strict ) {\n if ( $raw_user != '' ) {\n return $sanitized_user;\n }\n\n if ( ! empty ( $_REQUEST['action'] ) && $_REQUEST['action'] === 'register' && is_email( $_POST['user_email'] ) ) {\n return $_POST['user_email'];\n }\n\n return $sanitized_user;\n}, 10, 3 );\n\nadd_filter( 'validate_username', function( $valid, $username ) {\n if ( $valid ) {\n return $valid;\n }\n\n if ( ! empty ( $_REQUEST['action'] ) && $_REQUEST['action'] === 'register' && is_email( $_POST['user_email'] ) ) {\n return true;\n }\n\n return is_email( $username );\n}, 10, 2 );\n</code></pre>\n\n<p>In <code>sanitize_user</code> we replace the empty string with the email address. Later the username will be validated with <code>validate_username</code>, but again, the empty username will be used, so we need to catch this too.</p>\n\n<p>But I think to create an own form would be preferred and less hacky.</p>\n"
},
{
"answer_id": 283615,
"author": "squarecandy",
"author_id": 41488,
"author_profile": "https://wordpress.stackexchange.com/users/41488",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what I used:</p>\n\n<pre><code>jQuery(document).ready(function($){\n // hide the username field.\n $('input#user_login').parent().parent().hide();\n // force username to mirror the input of the email field\n $('input#email').on('change',function(){\n $('#user_login').val($(this).val());\n });\n});\n</code></pre>\n\n<p>Nice and simple.</p>\n"
},
{
"answer_id": 327606,
"author": "Fred Autier",
"author_id": 160312,
"author_profile": "https://wordpress.stackexchange.com/users/160312",
"pm_score": 2,
"selected": false,
"text": "<p>Add this in functions.php (or other php file) :</p>\n\n<pre><code>add_action('login_footer', function() {\n?><script type=\"text/javascript\">\n document.querySelector('input#user_login').parentElement.hidden = true ;\n document.querySelector('input#user_email').onchange = function(){\n document.querySelector('input#user_login').value = this.value ;\n } ;\n</script><?php\n} );\n</code></pre>\n\n<p>The action will print the script in the wp-login.php \"footer\". The javascript hide the \"user_login\" label and input, and set its value with the e-mail input value. </p>\n"
}
] |
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 them as .pdf files. There are several plugins which can embed pdf's into a page, and most browsers have the ability to view and print direct from a pdf link. </p>\n"
},
{
"answer_id": 241995,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>The real problem here is the download offer. Let's separate the two tasks first, to see that better.</p>\n\n<h2>Upload</h2>\n\n<h3>1. … from Word directly</h3>\n\n<p>Word can communicate with WordPress directly per <code>xmlrpc.php</code>. When you ope a new file, select <strong>Blog post</strong> 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.</p>\n\n<p>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.</p>\n\n<p>There is a <a href=\"https://premium.wpmudev.org/blog/how-to-use-microsoft-word-to-publish-directly-to-your-wordpress-site/\" rel=\"nofollow noreferrer\">post on WPMU Dev about the details</a>.</p>\n\n<h2>2. … as PDF</h2>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<h2>Download</h2>\n\n<p>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 <a href=\"https://github.com/PHPOffice/PHPWord\" rel=\"nofollow noreferrer\">PHPWord</a>. </p>\n\n<p>The actual WordPress handler could listen on the actions in <code>wp-admin/admin-post.php</code> as described in Export data as <a href=\"https://wordpress.stackexchange.com/a/102452/73\">CSV in back end with proper HTTP headers</a>:</p>\n\n<pre><code>if ( is_admin() )\n{\n $action = 'print_doc';\n add_action( \"admin_post_nopriv_{$action}\", 'print_word' );\n add_action( \"admin_post_{$action}\", 'print_word' );\n}\n\nfunction print_word()\n{\n $post_id = filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT );\n\n if ( ! $post_id )\n return;\n\n $post = get_post( $post_id );\n\n status_header( 200 );\n header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');\n header('Content-Disposition: attachment; filename=' . $post->post_name . '.docx');\n header('Pragma: no-cache');\n\n // Convert $post->post_content to Word\n // Output the Word document\n exit;\n}\n</code></pre>\n\n<p>To create the link on the front end, you can filter <code>the_content</code>:</p>\n\n<pre><code>if ( ! is_admin() )\n{\n add_filter( 'the_content', function( $content ) {\n\n if ( ! is_singular() )\n return $content;\n\n $post_id = get_the_ID();\n $url = admin_url( 'admin-post.php' );\n\n $link = sprintf(\n '<p class=\"download-link\"><a href=\"%s\">Download</a></p>',\n admin_url( 'admin-post.php' ) . '?action=print_doc&amp;id=' . $post_id\n );\n\n return $content . $link;\n });\n}\n</code></pre>\n\n<p>If you have uploaded the file as PDF, use <code>get_attached_media()</code> here, filter its return value for PDF. and create the link the same way as above.</p>\n"
}
] |
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 url<br>\n<a href=\"http://news.bbc.co.uk/2/hi/help/rss/default.stm\" rel=\"nofollow noreferrer\">http://news.bbc.co.uk/2/hi/help/rss/default.stm</a> </p>\n\n<p>then you could incorporate it feed in your site using transient so that you can set the appropriate time to fetch the new data. And with the DOMDocument element you can get the values/data</p>\n\n<p>Below is just a sample function where i have prepare a function to take your RSS feed url. </p>\n\n<pre><code>function vp_get_rss_feed($feed_url) {\n $expires = 7200; // 2hours\n\n delete_transient( 'rss_bbc_feed_world' );\n $feed = get_transient( 'rss_bbc_feed_world' );\n if ( false === ( $rss = $feed ) ) :\n $rss = new DOMDocument();\n $rss->load($feed_url);\n\n $feed = array();\n $i=1;\n foreach ($rss->getElementsByTagName('item') as $node) {\n\n $link = $node->getElementsByTagName('link')->item(0)->nodeValue;\n $title = $node->getElementsByTagName('title')->item(0)->nodeValue;\n $slug = sanitize_title($title);\n $desc = $node->getElementsByTagName('description')->item(0)->nodeValue;\n\n\n $item[$slug] = array (\n 'title' => $title,\n 'slug' => $slug,\n 'desc' => $desc,\n 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,\n );\n\n }\n array_push( $feed, $item );\n set_transient( 'rss_bbc_feed_world', $feed, $expires );\n endif;\n return $feed;\n}\n</code></pre>\n\n<p>This function takes your RSS feed and store on a array and return that array( $feed )</p>\n\n<p>You can then loop through that $feed in your desire location to where you would like to show the RSS feed data in your desire html styles.</p>\n\n<p>FOR REFERENCE:<br>\n<a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Transients_API</a><br>\n<a href=\"http://php.net/manual/en/class.domdocument.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/class.domdocument.php</a> </p>\n\n<p>Hope that helps!! </p>\n"
},
{
"answer_id": 380366,
"author": "Shivanand Sharma",
"author_id": 116231,
"author_profile": "https://wordpress.stackexchange.com/users/116231",
"pm_score": 1,
"selected": false,
"text": "<pre><code>// make request... (optionally save in transient for faster future fetches)\n$dom = new DOMDocument();\n$dom->loadHTML(wp_remote_retrieve_body($request));\n$sections=$dom->getElementsByTagName("section");\nforeach ($sections as $section) {\n // Do something...\n }\n</code></pre>\n"
}
] |
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:</p>\n\n<ol>\n<li><p>I put the following:</p>\n\n<pre><code> if ( \"\" === $post->post_content )\n {\n the_post_thumbnail();\n }\n else\n {\n the_content();\n } \n</code></pre>\n\n<p>in the wrong place.</p>\n\n<p>I should have put this bellow the line:</p>\n\n<pre><code>if( $name ) { ?>\n <a href=\"<?php echo $name; ?>\"target=\"_blank\"><?php the_post_thumbnail(); ?></a>\n <?php } else {\n //MY CODE SHOULD GO HERE\n} \n</code></pre>\n\n<ol start=\"2\">\n<li><p>The only code I should have put instead of the code under point 1 is:</p>\n\n<pre><code>the_content();\n</code></pre></li>\n</ol></li>\n</ol>\n\n<p>That got me what I wanted. And problem solved. I hope someone finds this helpful in future. P.s. I tried formatting the answer, but something is wrong. I would gladly accept edit to make it look as it should.</p>\n"
},
{
"answer_id": 241901,
"author": "David",
"author_id": 104457,
"author_profile": "https://wordpress.stackexchange.com/users/104457",
"pm_score": 3,
"selected": true,
"text": "<p>the_post_thumbnail will echo out the thumbnail so maybe try </p>\n\n<pre><code>if ( has_post_thumbnail() ) {\n the_post_thumbnail();\n} else {\n the_content();\n}\n</code></pre>\n\n<p>Hope this helps</p>\n"
}
] |
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 the files.</p>\n\n<p>If you update the active theme in this way, some unexpected results may occur for pages that are generated halway the uploading, part by the old theme, part by the new theme.</p>\n"
},
{
"answer_id": 241923,
"author": "RyanCameron.Me",
"author_id": 100537,
"author_profile": "https://wordpress.stackexchange.com/users/100537",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the Easy Theme and Plugin Upgrades plugin: <a href=\"https://en-ca.wordpress.org/plugins/easy-theme-and-plugin-upgrades/\" rel=\"nofollow\">https://en-ca.wordpress.org/plugins/easy-theme-and-plugin-upgrades/</a></p>\n\n<p>Download the plugin and upload your updated theme. The plugin will replace your outdated theme with your new one. I've used it on many sites, it's quick and easy and your site won't go into maintenance mode.</p>\n"
},
{
"answer_id": 353403,
"author": "Feriman",
"author_id": 78021,
"author_profile": "https://wordpress.stackexchange.com/users/78021",
"pm_score": 1,
"selected": true,
"text": "<p>3 years later I solved this issue with this below shell script:</p>\n\n<pre><code>#Getting list of outdated themes\n/usr/local/bin/wp theme list --update=available --allow-root --path=/var/www | sed -n '1!p' | awk '{print $1}' > /tmp/theme.list\n\n#Update them one by one\nwhile read -r themename\ndo\n #Store the old version number of theme\n OLDVER=\"$(grep Version: /var/www/wp-content/themes/\"$themename\"/style.css)\"\n\n #Download theme\n wget -q https://downloads.wordpress.org/theme/\"$themename\".zip -P /tmp/\n\n #Uncompress .zip file\n unzip -oq /tmp/\"$themename\".zip -d /var/www/wp-content/themes/\n\n #Store the new version number of theme\n NEWVER=\"$(grep Version: /var/www/wp-content/themes/\"$themename\"/style.css)\"\n\n #Create simple log file of theme update\n [[ \"$OLDVER\" != \"$NEWVER\" ]] && echo \"$themename\" >> /tmp/success.list || echo \"$themename\" >> /tmp/failed.list\n\n #Remove downloaded theme file\n rm /tmp/\"$themename\".zip\ndone < /tmp/theme.list\nrm /tmp/theme.list\n</code></pre>\n"
}
] |
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 scaffolding.less overrides the WordPress defaults with:</p>\n\n<pre><code>// Body reset\n\nhtml {\n font-size: 10px;\n -webkit-tap-highlight-color: rgba(0,0,0,0);\n}\n\nbody {\n font-family: @font-family-base;\n font-size: @font-size-base;\n line-height: @line-height-base;\n color: @text-color;\n background-color: @body-bg;\n}\n</code></pre>\n\n<p>I just added this to my custom CSS File (original WordPress CSS) with !important:</p>\n\n<pre><code>/* Override Bootstrap Reset with WP default */\nbody {\n font-family: -apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Oxygen-Sans,Ubuntu,Cantarell,\"Helvetica Neue\",sans-serif !important;\n}\n</code></pre>\n\n<p>Now WordPress looks like it should again.</p>\n"
},
{
"answer_id": 278944,
"author": "Farhad Sakhaei",
"author_id": 114465,
"author_profile": "https://wordpress.stackexchange.com/users/114465",
"pm_score": -1,
"selected": false,
"text": "<p>Use this plugin to insert and load Font Awesome Icons and Bootstrap</p>\n\n<p><a href=\"https://wordpress.org/plugins/best-editor/\" rel=\"nofollow noreferrer\">Best Editor</a></p>\n"
}
] |
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 how can I rename the wp-content for the second wordpress installation. I found a simple tutorial <a href=\"http://www.hongkiat.com/blog/renaming-wordpress-wp-content-folder/\" rel=\"nofollow\">here</a> and after made everything from tutorial with the rename procedure now all resources are available. </p>\n"
},
{
"answer_id": 241932,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": -1,
"selected": false,
"text": "<p>I think you are doing everything wrong. You should just use 1 WP installation and <strong>ENABLE MULTI-SITE feature</strong>, and then you can open as many separate WP sites as you want! </p>\n\n<h1><strong>NO NEED TO INSTALL separate WORDPRESS installations.</strong></h1>\n"
}
] |
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 over https to it (<code>wp_get_remote</code> for example). HTTPS traffic can be terminated on a load balancer and the traffic between it and wordpress done over http, therefor it is not obvious you will find any HTTPS specific configuration (there has to be one somewhere, but it will change from site to site).</p>\n"
},
{
"answer_id": 242194,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": true,
"text": "<p>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.</p>\n\n<p>However, one automated way is to check if the site URL has <code>https://</code> 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:</p>\n\n<pre><code>add_action( 'template_redirect', 'wpse_241934_redirect_https', 1, 1 );\nfunction redirect_https() {\n # If 'https://' is in the website's site URL and SSL is not being used, force HTTPS\n if ( preg_match( '/https:\\/\\//', site_url() ) && ! is_ssl() ) {\n wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );\n exit;\n }\n}\n</code></pre>\n\n<p>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.</p>\n"
}
] |
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 over https to it (<code>wp_get_remote</code> for example). HTTPS traffic can be terminated on a load balancer and the traffic between it and wordpress done over http, therefor it is not obvious you will find any HTTPS specific configuration (there has to be one somewhere, but it will change from site to site).</p>\n"
},
{
"answer_id": 242194,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": true,
"text": "<p>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.</p>\n\n<p>However, one automated way is to check if the site URL has <code>https://</code> 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:</p>\n\n<pre><code>add_action( 'template_redirect', 'wpse_241934_redirect_https', 1, 1 );\nfunction redirect_https() {\n # If 'https://' is in the website's site URL and SSL is not being used, force HTTPS\n if ( preg_match( '/https:\\/\\//', site_url() ) && ! is_ssl() ) {\n wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );\n exit;\n }\n}\n</code></pre>\n\n<p>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.</p>\n"
}
] |
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 screen. First, you'll want to add a custom stylesheet by hooking into <code>login_enqueue_scripts</code>.</p>\n\n<pre><code>add_action( 'login_enqueue_scripts', 'wpse_login_styles' );\nfunction wpse_login_styles() {\n wp_enqueue_style( 'wpse-custom-login', get_stylesheet_directory_uri() . '/style-login.css' );\n}\n</code></pre>\n\n<p>Then you can create a <code>styles-login.css</code> file in the root of your child theme directory (or adjust the path in <code>wp_enqueue_script</code> based on your needs).</p>\n\n<p>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 <a href=\"https://codex.wordpress.org/Customizing_the_Login_Form#Change_the_Login_Logo\" rel=\"nofollow\">the Codex</a>:</p>\n\n<pre><code>#login h1 a, .login h1 a {\n background-image: url(path/to/login/logo.png);\n padding-bottom: 30px;\n}\n</code></pre>\n\n<p>Beyond CSS, you can also change the URL and site title on this page using the <code>login_headerurl</code> and <code>login_headertitle</code> hooks, also described in the above Codex link.</p>\n\n<p>If you want to go further like adding elements to the page, or even creating a custom login page, that's all described <a href=\"https://codex.wordpress.org/Customizing_the_Login_Form#Login_Hooks\" rel=\"nofollow\">here</a> and <a href=\"https://codex.wordpress.org/Customizing_the_Login_Form#Make_a_Custom_Login_Page\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 242347,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>You can check out the code on the plugin I made a while back, WP Login Flow:\n<a href=\"https://github.com/tripflex/wp-login-flow\" rel=\"nofollow\">https://github.com/tripflex/wp-login-flow</a></p>\n\n<p>Everything in the plugin for customizing wp-login.php should still work just fine, but I haven't updated it in a while after they made the change to the way the user passwords were handled. If anything the code should give you a good idea of how to completely customize it</p>\n"
}
] |
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\"; die;}\n</code></pre>\n\n<p>Try changing <code>die;</code> to <code>die();</code></p>\n"
},
{
"answer_id": 242005,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 0,
"selected": false,
"text": "<p>You can try to return à json response:</p>\n\n<pre><code>echo json_encode(array('message'=> 'the message'));\ndie();\n</code></pre>\n\n<p>Then in the js script you need to parse the json response with var json = $.parseJSON(response);</p>\n"
}
] |
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 the best way would be to do this on the client side.</p>\n\n<p><strong>Method with maximum height</strong></p>\n\n<p>Let's say your post template has its content like this:</p>\n\n<pre><code><div id=\"content\"><?php the_content(); ?></div>\n</code></pre>\n\n<p>You need to add a button after this div, so it would become:</p>\n\n<pre><code><div id=\"content\"><?php the_content(); ?></div>\n<button class=\"show-more\">Show more</button>\n</code></pre>\n\n<p>Then you add CSS to only show the content up to specific height, in your style.css add:</p>\n\n<pre><code>#content { max-height: 100px; overflow: hidden; }\n.show-more { margin-top: 15px; }\n</code></pre>\n\n<p>Finally, add a script that would show the full height of content and remove \"show-more\" button after it's clicked:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n $('.show-more').click(function() {\n $('#content').css('max-height', 'none');\n $(this).remove();\n });\n});\n</code></pre>\n\n<p>It's just a basic setup, so feel free to adjust the styles and the script as you'd like.</p>\n\n<p>Here's a link to the fiddle where you can try it out: <a href=\"https://jsfiddle.net/psxtur2L/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/psxtur2L/</a></p>\n\n<p><strong>Method with replacing the content</strong></p>\n\n<p>If you want to specifically show the excerpt as a short version, you can do it this way.</p>\n\n<p>In your template, you add both the excerpt and the content, and a button, like this:</p>\n\n<pre><code><div id=\"excerpt\"><?php the_excerpt(); ?></div>\n<div id=\"content\"><?php the_content(); ?></div>\n<button class=\"show-more\">Show more</button>\n</code></pre>\n\n<p>In CSS you just hide the content by default:</p>\n\n<pre><code>#content { display: none; }\n.show-more { margin-top: 15px; }\n</code></pre>\n\n<p>And then you hide the excerpt and show the content when the user clicks on the button:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n $('.show-more').click(function() {\n $('#excerpt').hide();\n $('#content').show();\n $(this).remove();\n });\n});\n</code></pre>\n\n<p>Here's a fiddle for that: <a href=\"https://jsfiddle.net/o7z2Lsks/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/o7z2Lsks/</a></p>\n\n<p>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.</p>\n"
},
{
"answer_id": 396637,
"author": "Marc",
"author_id": 66405,
"author_profile": "https://wordpress.stackexchange.com/users/66405",
"pm_score": 0,
"selected": false,
"text": "<p>I just wrote a snippet that works with the wordpress built in <strong>Read More Tag</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/E9iK5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E9iK5.png\" alt=\"Wordpress read more tag in editor\" /></a></p>\n<p>The result is shown in the following images:\nFront end text with read more link:</p>\n<p><a href=\"https://i.stack.imgur.com/sl3iP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sl3iP.png\" alt=\"Front end text with read more link\" /></a></p>\n<p>Front end text with read less link:</p>\n<p><a href=\"https://i.stack.imgur.com/wAehI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wAehI.png\" alt=\"Front end text with read less link\" /></a></p>\n<p>The code part:</p>\n<p>PHP:</p>\n<pre><code><div class="js-read-more"><?php the_content(); ?></div>\n</code></pre>\n<p>JQUERY:</p>\n<pre><code>if($('.js-read-more').length > 0){\n\n var _more = $('.js-read-more').find('[id^=more]');\n\n var _p = _more.parent();\n\n var _before = $('<div class="before"></div>');\n var _after = $('<div class="after transition-5 overflow-hidden"></div>');\n var _link_more = $('<a class="ml-2 arrow-after-right" href="#">Read More</a>');\n var _link_less = $('<a class="ml-2 arrow-after-up" href="#">Read Less</a>');\n\n _before.append(_p.prevAll());\n _after.append(_p.nextAll());\n\n $('.js-read-more').append(_before);\n _before.children().last().append(_link_more);\n $('.js-read-more').append(_after);\n _after.children().last().append(_link_less);\n\n var _h = _after.outerHeight();\n _after.css('max-height', 0);\n\n _link_more.click(function(){\n _after.css('max-height', _h);\n $(this).fadeOut();\n });\n\n _link_less.click(function(){\n _after.css('max-height', 0);\n _link_more.fadeIn();\n });\n\n}\n</code></pre>\n<p>It uses some tailwindcss classes in the js, that can be deducted by reading.</p>\n"
}
] |
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 the best way would be to do this on the client side.</p>\n\n<p><strong>Method with maximum height</strong></p>\n\n<p>Let's say your post template has its content like this:</p>\n\n<pre><code><div id=\"content\"><?php the_content(); ?></div>\n</code></pre>\n\n<p>You need to add a button after this div, so it would become:</p>\n\n<pre><code><div id=\"content\"><?php the_content(); ?></div>\n<button class=\"show-more\">Show more</button>\n</code></pre>\n\n<p>Then you add CSS to only show the content up to specific height, in your style.css add:</p>\n\n<pre><code>#content { max-height: 100px; overflow: hidden; }\n.show-more { margin-top: 15px; }\n</code></pre>\n\n<p>Finally, add a script that would show the full height of content and remove \"show-more\" button after it's clicked:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n $('.show-more').click(function() {\n $('#content').css('max-height', 'none');\n $(this).remove();\n });\n});\n</code></pre>\n\n<p>It's just a basic setup, so feel free to adjust the styles and the script as you'd like.</p>\n\n<p>Here's a link to the fiddle where you can try it out: <a href=\"https://jsfiddle.net/psxtur2L/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/psxtur2L/</a></p>\n\n<p><strong>Method with replacing the content</strong></p>\n\n<p>If you want to specifically show the excerpt as a short version, you can do it this way.</p>\n\n<p>In your template, you add both the excerpt and the content, and a button, like this:</p>\n\n<pre><code><div id=\"excerpt\"><?php the_excerpt(); ?></div>\n<div id=\"content\"><?php the_content(); ?></div>\n<button class=\"show-more\">Show more</button>\n</code></pre>\n\n<p>In CSS you just hide the content by default:</p>\n\n<pre><code>#content { display: none; }\n.show-more { margin-top: 15px; }\n</code></pre>\n\n<p>And then you hide the excerpt and show the content when the user clicks on the button:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n $('.show-more').click(function() {\n $('#excerpt').hide();\n $('#content').show();\n $(this).remove();\n });\n});\n</code></pre>\n\n<p>Here's a fiddle for that: <a href=\"https://jsfiddle.net/o7z2Lsks/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/o7z2Lsks/</a></p>\n\n<p>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.</p>\n"
},
{
"answer_id": 396637,
"author": "Marc",
"author_id": 66405,
"author_profile": "https://wordpress.stackexchange.com/users/66405",
"pm_score": 0,
"selected": false,
"text": "<p>I just wrote a snippet that works with the wordpress built in <strong>Read More Tag</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/E9iK5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E9iK5.png\" alt=\"Wordpress read more tag in editor\" /></a></p>\n<p>The result is shown in the following images:\nFront end text with read more link:</p>\n<p><a href=\"https://i.stack.imgur.com/sl3iP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sl3iP.png\" alt=\"Front end text with read more link\" /></a></p>\n<p>Front end text with read less link:</p>\n<p><a href=\"https://i.stack.imgur.com/wAehI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wAehI.png\" alt=\"Front end text with read less link\" /></a></p>\n<p>The code part:</p>\n<p>PHP:</p>\n<pre><code><div class="js-read-more"><?php the_content(); ?></div>\n</code></pre>\n<p>JQUERY:</p>\n<pre><code>if($('.js-read-more').length > 0){\n\n var _more = $('.js-read-more').find('[id^=more]');\n\n var _p = _more.parent();\n\n var _before = $('<div class="before"></div>');\n var _after = $('<div class="after transition-5 overflow-hidden"></div>');\n var _link_more = $('<a class="ml-2 arrow-after-right" href="#">Read More</a>');\n var _link_less = $('<a class="ml-2 arrow-after-up" href="#">Read Less</a>');\n\n _before.append(_p.prevAll());\n _after.append(_p.nextAll());\n\n $('.js-read-more').append(_before);\n _before.children().last().append(_link_more);\n $('.js-read-more').append(_after);\n _after.children().last().append(_link_less);\n\n var _h = _after.outerHeight();\n _after.css('max-height', 0);\n\n _link_more.click(function(){\n _after.css('max-height', _h);\n $(this).fadeOut();\n });\n\n _link_less.click(function(){\n _after.css('max-height', 0);\n _link_more.fadeIn();\n });\n\n}\n</code></pre>\n<p>It uses some tailwindcss classes in the js, that can be deducted by reading.</p>\n"
}
] |
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 */\nfunction q242068_limit_depth( $hook ) {\n if ( $hook != 'nav-menus.php' ) return;\n\n // override default value right after 'nav-menu' JS\n wp_add_inline_script( 'nav-menu', 'wpNavMenu.options.globalMaxDepth = 1;', 'after' );\n}\nadd_action( 'admin_enqueue_scripts', 'q242068_limit_depth' );\n</code></pre>\n"
},
{
"answer_id": 358691,
"author": "squarecandy",
"author_id": 41488,
"author_profile": "https://wordpress.stackexchange.com/users/41488",
"pm_score": 1,
"selected": false,
"text": "<p>Follow up on @jmarceli's great answer to target specific menu locations</p>\n<pre><code>function squarecandy_menu_admin_limit_depth( $hook ) {\n if ( 'nav-menus.php' !== $hook ) {\n return;\n }\n\n wp_enqueue_script( 'squarecandy-admin-menu-depth', get_stylesheet_directory_uri() . '/js/admin-menu-depth.js', array(), '1.0.0', true );\n}\nadd_action( 'admin_enqueue_scripts', 'squarecandy_menu_admin_limit_depth' );\n</code></pre>\n<p>js</p>\n<pre><code>// Force Menu Depth to Match Front End\n\n// main menu can only have one child level\nif ( document.getElementById("locations-main-menu").checked ) {\n wpNavMenu.options.globalMaxDepth = 1;\n}\n\n// footer menu have only top level\nif ( document.getElementById("locations-footer-menu").checked ) {\n wpNavMenu.options.globalMaxDepth = 0;\n}\n\n// all other menu locations stay at the WP default\n</code></pre>\n"
},
{
"answer_id": 377002,
"author": "Davey",
"author_id": 109296,
"author_profile": "https://wordpress.stackexchange.com/users/109296",
"pm_score": 3,
"selected": true,
"text": "<p>Follow up on @jmarceli's and @squarecandy's great answers. Here is a solution that allows for:</p>\n<ul>\n<li>Easier scaling (set an object in the php action)</li>\n<li>Updates to the correct menu depth when the location checkboxes are changed</li>\n</ul>\n<pre><code>/**\n * Limit max menu depth in admin panel \n */\n\nfunction limit_admin_menu_depth($hook)\n{\n if ($hook != 'nav-menus.php') return;\n\n wp_register_script('limit-admin-menu-depth', get_stylesheet_directory_uri() . '/js/admin/limit-menu-depth.js', array(), '1.0.0', true);\n wp_localize_script(\n 'limit-admin-menu-depth',\n 'myMenuDepths',\n array(\n 'primary' => 1, // <-- Set your menu location and max depth here\n 'footer' => 0 // <-- Add as many as you like\n )\n );\n wp_enqueue_script('limit-admin-menu-depth');\n}\nadd_action( 'admin_enqueue_scripts', 'limit_admin_menu_depth' );\n</code></pre>\n<p>js</p>\n<pre><code>/**\n * Limit max menu depth in admin panel\n * Expects wp_localize_script to have set an object of menu locations\n * in the shape of { location: maxDepth, location2: maxDepth2 }\n * e.g var menu-depths = {"primary":"1","footer":"0"};\n */\n(function ($) {\n // Get initial maximum menu depth, so that we may restore to it later.\n var initialMaxDepth = wpNavMenu.options.globalMaxDepth;\n\n function setMaxDepth() {\n // Loop through each of the menu locations\n $.each(myMenuDepths, function (location, maxDepth) {\n if (\n $('#locations-' + location).prop('checked') &&\n maxDepth < wpNavMenu.options.globalMaxDepth\n ) {\n // If this menu location is checked\n // and if the max depth for this location is less than the current globalMaxDepth\n // Then set globalMaxDepth to the max depth for this location\n wpNavMenu.options.globalMaxDepth = maxDepth;\n }\n });\n }\n\n // Run the function once on document ready\n setMaxDepth();\n\n // Re-run the function if the menu location checkboxes are changed\n $('.menu-theme-locations input').on('change', function () {\n wpNavMenu.options.globalMaxDepth = initialMaxDepth;\n setMaxDepth();\n });\n})(jQuery);\n\n</code></pre>\n"
}
] |
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$sessions->destroy_all();\n</code></pre>\n\n<p>I don't think you have to set the variable inside of the brackets, you just need to pass the ID of the user (which is done for you by <a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow\">get_current_user_id</a> function).</p>\n\n<p>Here's a <a href=\"https://developer.wordpress.org/reference/classes/wp_session_tokens/get_instance/\" rel=\"nofollow\">reference to the get_instance function</a>, in case you haven't read it.</p>\n"
},
{
"answer_id": 242178,
"author": "Bysander",
"author_id": 47618,
"author_profile": "https://wordpress.stackexchange.com/users/47618",
"pm_score": 2,
"selected": false,
"text": "<p>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.</p>\n\n<p>The lines that look like this:</p>\n\n<pre><code>define('AUTH_KEY', ':u(rb=Ys8*2x^rVisqX(9=10a*.euPdYEBo6p_ZBB2CDG|rv~Ju)sh+6@=L6p_:l');\ndefine('SECURE_AUTH_KEY', '-`<iUz(4olJ`m&}1kA*{v&OX;Kq?W+!7ppF!tWb}cM<R=d<s=(oL]]04%AA@juZB');\ndefine('LOGGED_IN_KEY', '$KA]84n3ZT}v6m7c:r+!6l}R||)<_$3GxJ%F6Y?MopvxydJ@PRcmZ0-Hyq(EuEZt');\ndefine('NONCE_KEY', 'qT=]!^BARWEMUD(G6]#~q$PAv-N[#^uE991w7HJNN<*mXavH)@o0TkFKVFUNIDN#');\ndefine('AUTH_SALT', 'c W#7TWk{L1+n0A+^:|FHYL#-;*#<8U :v%>~S!45$bbYM09Iwe;@=uk^xeJd_D`');\ndefine('SECURE_AUTH_SALT', 'h3&dgYcQE0uTaxd5bX$&1wC]yKP^?W8#q#>IJ*)ggf_Rc+6f+oZa?#JVS[HmO?=O');\ndefine('LOGGED_IN_SALT', '_L:n)>u>-31YK_ftTp_ZV>-y)qG)so|sOoWgYC9Ju!q_!%f.60g?I~]~lNZ6&o!0');\ndefine('NONCE_SALT', '.KI_*}ONxh/uwZv~!qYqOW+OL;?qvgaEqayN8>i+B.WY$e}+M9.Xqxwlf+?v 1k=');\n</code></pre>\n\n<p><a href=\"https://api.wordpress.org/secret-key/1.1/salt/\" rel=\"nofollow\">This website</a> is a good tool for generating new secure keys to put in.</p>\n\n<p>If you want to change the amount of time you can be logged in for you can use the below code in your themes <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for' );\n\nfunction keep_me_logged_in_for( $expirein ) {\n return 86400; // time in seconds\n}\n</code></pre>\n"
}
] |
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$sessions->destroy_all();\n</code></pre>\n\n<p>I don't think you have to set the variable inside of the brackets, you just need to pass the ID of the user (which is done for you by <a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow\">get_current_user_id</a> function).</p>\n\n<p>Here's a <a href=\"https://developer.wordpress.org/reference/classes/wp_session_tokens/get_instance/\" rel=\"nofollow\">reference to the get_instance function</a>, in case you haven't read it.</p>\n"
},
{
"answer_id": 242178,
"author": "Bysander",
"author_id": 47618,
"author_profile": "https://wordpress.stackexchange.com/users/47618",
"pm_score": 2,
"selected": false,
"text": "<p>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.</p>\n\n<p>The lines that look like this:</p>\n\n<pre><code>define('AUTH_KEY', ':u(rb=Ys8*2x^rVisqX(9=10a*.euPdYEBo6p_ZBB2CDG|rv~Ju)sh+6@=L6p_:l');\ndefine('SECURE_AUTH_KEY', '-`<iUz(4olJ`m&}1kA*{v&OX;Kq?W+!7ppF!tWb}cM<R=d<s=(oL]]04%AA@juZB');\ndefine('LOGGED_IN_KEY', '$KA]84n3ZT}v6m7c:r+!6l}R||)<_$3GxJ%F6Y?MopvxydJ@PRcmZ0-Hyq(EuEZt');\ndefine('NONCE_KEY', 'qT=]!^BARWEMUD(G6]#~q$PAv-N[#^uE991w7HJNN<*mXavH)@o0TkFKVFUNIDN#');\ndefine('AUTH_SALT', 'c W#7TWk{L1+n0A+^:|FHYL#-;*#<8U :v%>~S!45$bbYM09Iwe;@=uk^xeJd_D`');\ndefine('SECURE_AUTH_SALT', 'h3&dgYcQE0uTaxd5bX$&1wC]yKP^?W8#q#>IJ*)ggf_Rc+6f+oZa?#JVS[HmO?=O');\ndefine('LOGGED_IN_SALT', '_L:n)>u>-31YK_ftTp_ZV>-y)qG)so|sOoWgYC9Ju!q_!%f.60g?I~]~lNZ6&o!0');\ndefine('NONCE_SALT', '.KI_*}ONxh/uwZv~!qYqOW+OL;?qvgaEqayN8>i+B.WY$e}+M9.Xqxwlf+?v 1k=');\n</code></pre>\n\n<p><a href=\"https://api.wordpress.org/secret-key/1.1/salt/\" rel=\"nofollow\">This website</a> is a good tool for generating new secure keys to put in.</p>\n\n<p>If you want to change the amount of time you can be logged in for you can use the below code in your themes <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for' );\n\nfunction keep_me_logged_in_for( $expirein ) {\n return 86400; // time in seconds\n}\n</code></pre>\n"
}
] |
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 limit\". The limit is there because if the response is unbounded everybody would be able to simply DOS any site by crashing the webserver or DB by asking to get all posts in one request. </p>\n\n<p>Even without that consideration getting even 100 is likely to be slowish. If you want to use the REST API, just get the data in small amounts only when it is actually needed.</p>\n\n<p>Still want to get more than 100? Write your own json end point and handler.</p>\n"
},
{
"answer_id": 242214,
"author": "db306",
"author_id": 90056,
"author_profile": "https://wordpress.stackexchange.com/users/90056",
"pm_score": -1,
"selected": false,
"text": "<p>You can <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">add a route</a> to your wordpress REST api. Make it so you can extract as many images as you need. You can copy the current route for getting the images and delete the maximum filter so you do not run into this issue.</p>\n"
},
{
"answer_id": 255705,
"author": "r_alex_hall",
"author_id": 71643,
"author_profile": "https://wordpress.stackexchange.com/users/71643",
"pm_score": 1,
"selected": false,
"text": "<p>Add a page number query to your request URL, and continue querying next page numbers until you get an empty result:</p>\n\n<pre><code><your_wordpress_install_base_url>/wp-json/wp/v2/media/?per_page=100&page=2\n</code></pre>\n\n<p>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:</p>\n\n<pre><code><your_wordpress_install_base_url>/wp-json/wp/v2/media/?per_page=25&page=3\n</code></pre>\n\n<p>Note also that (for me at least) these query URLs work if constructed as just ~/<code>media?per_page=3</code> (instead of ~/<code>media/?per_page=3</code>). I don't know whether one or the other is preferred.</p>\n\n<p>Thanks, incidentally, for the <code>/media/?per_page=100</code> part of your example. I'd been stumped about getting empty results when querying just <code>/media</code> :)</p>\n"
},
{
"answer_id": 309141,
"author": "Goran Stanković",
"author_id": 101159,
"author_profile": "https://wordpress.stackexchange.com/users/101159",
"pm_score": -1,
"selected": false,
"text": "<p>Create new php file with following content and use it as a new endpoint:</p>\n\n<pre><code>header('Access-Control-Allow-Origin: *', 'Content-Type: application/json'); // Avoid cross origin block\n\n$url1 = 'https://www.example.com/wp/v2/posts?per_page=100&page=1'; // path to your JSON file\n$url2 = 'https://www.example.com/wp/v2/posts?per_page=100&page=2'; // path to your JSON file\n$json1 = file_get_contents($url1);\n$json2 = file_get_contents($url2);\n\n$my_array1 = json_decode($json1, true);\n$my_array2 = json_decode($json2, true);\n$res = array_merge($my_array1, $my_array2);\n$json_merge = json_encode($res);\n\necho $json_merge; // new json\n</code></pre>\n\n<p>And use it as a new endpoint. This is an example for 200 posts, you can add more input endpoints as you want.</p>\n"
}
] |
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/single-vs-double-quotes-vs\">this question</a></p>\n<p>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:</p>\n<ul>\n<li>You may end up breaking your WordPress core</li>\n<li>You will lose all changes next time you will update your WordPress</li>\n<li>You will have to go case by case as situations like these may appear:</li>\n</ul>\n<p><code>echo <link rel='" . echo $bar . "' href="' . echo $foo . '";</code></p>\n<p>in which case you will have to invert double quotes for single quotes and vice versa.</p>\n<p>This will be very time consuming for what you will get in return.</p>\n<p>As a matter of fact WordPress coding standards accept both quotation styles:</p>\n<p>See <a href=\"https://developer.wordpress.org/coding-standards/wordpress-coding-standards/html/#quotes\" rel=\"nofollow noreferrer\">WordPress HTML Coding Standards on Quotes</a></p>\n"
},
{
"answer_id": 242384,
"author": "Richard",
"author_id": 104742,
"author_profile": "https://wordpress.stackexchange.com/users/104742",
"pm_score": 2,
"selected": false,
"text": "<p>How desperate are you to do this? This <a href=\"https://stackoverflow.com/a/22818089/3350811\">answer</a> explains how to capture the final output, then you can use <a href=\"http://php.net/manual/en/domdocument.loadhtml.php\" rel=\"nofollow noreferrer\"><code>DOMDocument::loadHTML</code></a> to load in the final output and re-emit with <code>::saveHTML</code> which will output the quotes the way you like. It may also eat something else in the page, but it will sort out the quotes.</p>\n"
}
] |
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 would be better if you limit the origin to <strong>one</strong> specific remote domain from which you are consuming the API, like <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin\" rel=\"noreferrer\">this example</a>:</p>\n\n<pre><code>header(\"Access-Control-Allow-Origin: http://mozilla.com\");\n</code></pre>\n\n<p>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.</p>\n\n<p>Even better, you can limit your request to <a href=\"https://es.stackoverflow.com/a/20431/2162\">only the methods you really need to allow</a>, the gist is this snippet, and it works for several domains, <strong>if you have the <code>$_SERVER['HTTP_ORIGIN']</code> variable populated</strong>:</p>\n\n<pre><code>add_action('rest_api_init', function() {\n\n /* unhook default function */\n remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');\n\n /* then add your own filter */\n add_filter('rest_pre_serve_request', function( $value ) {\n $origin = get_http_origin();\n $my_sites = array( 'http://site1.org/', 'http://site2.net', );\n if ( in_array( $origin, $my_sites ) ) {\n header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );\n } else {\n header( 'Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ) );\n }\n header( 'Access-Control-Allow-Methods: GET' );\n\n return $value;\n });\n}, 15);\n</code></pre>\n\n<p>As you can see, this snippet uses the function <a href=\"https://developer.wordpress.org/reference/functions/get_http_origin/\" rel=\"noreferrer\">get_http_origin</a> provided by WordPress, but it will return null or empty, if the key <code>HTTP_ORIGIN</code> is not populated in the <code>$_SERVER</code> 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 <code><?php phpinfo(); ?></code>, if you have this variable populated.</p>\n\n<p>Maybe the origin site it's populated in another header by cloudflare, and you could use it in a function hooked to the <code>http_origin</code> 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.</p>\n\n<p>I'd be glad to help.</p>\n"
},
{
"answer_id": 242327,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>background - browsers are restricting remote access from scripts to only the site from which it was loaded. If this kind of check wasn't done, while visiting a site X it would have been possible for it to submit data to your gmail account (if you are logged in) without even needing to guess your user and password, because the browser would have sent the proper authentication cookies to gmail.</p>\n\n<p>The CORS \"protocol\" is there to help you relax this restriction when needed.</p>\n\n<p>So the question that you should ask yourself, is do I need it? On the one hand, I can't see why would 99% of wordpress sites need it, on the other hand, wordpress cookies are relatively short lived and 99% of wordpress sites are not going to be a target to such a random attack. </p>\n\n<p>I would say, that since the rest API is a mutating one, and have access to private information, you should not use rest api in your solution if you need to enable cors, you better write your own \"read only\" API.</p>\n"
}
] |
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 it.</p>\n\n<p>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.</p>\n\n<p>Check out these resources that have more information specifically on the structure of the HTML and javascript</p>\n\n<p><a href=\"https://css-tricks.com/snippets/jquery/display-loading-graphic-until-page-fully-loaded/\" rel=\"nofollow noreferrer\">https://css-tricks.com/snippets/jquery/display-loading-graphic-until-page-fully-loaded/</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/11072759/display-a-loading-bar-before-the-entire-page-is-loaded\">https://stackoverflow.com/questions/11072759/display-a-loading-bar-before-the-entire-page-is-loaded</a></p>\n\n<p><a href=\"http://smallenvelop.com/display-loading-icon-page-loads-completely/\" rel=\"nofollow noreferrer\">http://smallenvelop.com/display-loading-icon-page-loads-completely/</a></p>\n"
},
{
"answer_id": 307086,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 0,
"selected": false,
"text": "<p>Add below CSS in your CSS file.</p>\n\n<pre><code>/** Body Overlay **/\nbody #load {\n display: block;\n height: 100%;\n overflow: hidden;\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n z-index: 9901;\n opacity: 1;\n background-color: #FFFFFF;\n visibility: visible;\n -webkit-transition: all .35s ease-out;\n transition: all .35s ease-out;\n}\nbody #load.loader-removed {\n opacity: 0;\n visibility: hidden;\n}\n.spinner-loader .load-wrap {\n background-image: url(\"images/loader.png\");\n background-position: center center;\n background-repeat: no-repeat;\n text-align: center;\n width: 100%;\n height: 100%;\n}\n</code></pre>\n\n<p>Add below code just after the opening tag in your website.</p>\n\n<pre><code><div id=\"load\" class=\"spinner-loader\"><div class=\"load-wrap\"></div></div>\n<script type=\"text/javascript\">\n // Javascript function to display loader on page load\n document.addEventListener(\"DOMContentLoaded\", function(event) {\n var $load = document.getElementById(\"load\");\n var removeLoading = setTimeout(function() {\n $load.className += \" loader-removed\";\n }, 500);\n });\n</script>\n</code></pre>\n\n<p>Hope this helps..!!</p>\n"
}
] |
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 = baseurl + ''; //WHAT IS THIS?!?!\njQuery.post(ajaxurl, data, function(response) {\n alert('Got this from the server: ' + response);\n console.log(response);\n});\n</code></pre>\n\n<p>And your PHP in functions.php</p>\n\n<pre><code>//Called by Ajax from App - list the contents of the folder so they can be downloaded and stored locally\nfunction folder_contents() {\n\n$folderPath = $_POST['path'] ;\n$files = array_diff(scandir($path), array('.', '..'));\nprint_r($files);\nreturn $files;\n\ndie(); \n}\n\nadd_action('wp_ajax_folder_contents', 'folder_contents');\nadd_action('wp_ajax_nopriv_folder_contents', 'folder_contents');\n</code></pre>\n\n<p>The above add your function as an ajax action. You then call the function name in your AJAX.</p>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)</a></p>\n"
},
{
"answer_id": 242336,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">WP Codex</a> states that you can use the global variable <code>ajaxurl</code> without declaring it first. In other words, comment out this line:</p>\n<p><code>var ajaxurl = ajax_params.ajax_url;</code></p>\n<p>...and see if that works.</p>\n"
},
{
"answer_id": 242344,
"author": "SdeWijs",
"author_id": 73911,
"author_profile": "https://wordpress.stackexchange.com/users/73911",
"pm_score": 1,
"selected": false,
"text": "<p>In your code I see you localize the 'ajax-js' script, but is the script itself enqueued? I had to use wp_localize scripts a few weeks ago and I had to enqueue my JS script inside the function that called wp_localize script. For example:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'google_js_script' );\n\nfunction google_js_script()\n{\n // Enqueue the js script \n wp_enqueue_script('google-js', GOOGLE_PLG_URL . 'assets/js/google-places.js', array('jquery'), true);\n\n // Localize the enqueued JS script\n wp_localize_script( 'google-js', 'ajax_object',\n array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'place' => '' ) );\n}\n</code></pre>\n\n<p>Hope this helps to debug the issue.</p>\n"
}
] |
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)>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.