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
185,318
<p>From what I understand <code>esc_attr_e</code> is ideally used for escaping values in attributes - Is it right that the usage of <code>esc_attr_e</code> can also be worked in with non attribute values, such as the h3 and label elements in the example below?</p> <pre><code>&lt;h3&gt;&lt;?php esc_attr_e( 'Some Text', 'my-plugin' ); ?&gt;&lt;/h3&gt; &lt;form name="myplugin_form" method="post" action=""&gt; &lt;input type="hidden" name="myplugin_form_submitted" value="Y"&gt; &lt;table class="form-table"&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="ng_plugin_menu"&gt;&lt;?php esc_attr_e( 'Plugin Menu Name', 'my-plugin' ); ?&gt;&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input name="ng_plugin_menu" id="ng_plugin_menu" type="text" value="&lt;?php esc_attr_e ($my_plugin_label, 'my_plugin'); ?&gt;" class="regular-text" placeholder="&lt;?php esc_attr_e ('Placeholder Text', 'my_plugin'); ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p&gt;&lt;input class="button-primary" type="submit" name="my_plugin_menu_submit" value="Save" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>So using <code>esc_attr_e</code> it instead of <code>_e</code>, I was told by a senior developer that this is valid, but am looking for confirmation. It is also the purpose of my sample code that I want to allow translation for all strings.</p>
[ { "answer_id": 185320, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>I would suggest using <code>esc_html</code> instead of <code>esc_attr</code> for that, e.g.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo esc_url( $url );?&gt;\" class=\"&lt;?php echo esc_attr( $classes ); ?&gt;\"&gt;\n &lt;?php echo esc_html( $title ); ?&gt;\n&lt;/a&gt;\n&lt;div&gt;\n &lt;?php echo wp_kses_post( $html_with_safe_tags );?&gt;\n&lt;/div&gt;\n&lt;script&gt;\n &lt;?php echo wp_json_encode( $data_for_js ); ?&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>There is also:</p>\n\n<ul>\n<li><code>esc_html__</code> <code>esc_attr__</code> etc ( escape translations too! )</li>\n<li><code>esc_js</code> - escape strings for javascript e.g. <code>console.log(&lt;?php echo esc_js($var); ?&gt;);</code></li>\n<li><code>esc_url_raw</code> when redirecting, use this instead</li>\n<li><code>esc_sql</code></li>\n<li><code>esc_textarea</code></li>\n<li><code>sanitize_text_field</code></li>\n<li>Whitelisting values</li>\n<li>type casting with <code>(int)</code> or <code>absint</code></li>\n<li>and others</li>\n</ul>\n" }, { "answer_id": 267814, "author": "Filip Hanes", "author_id": 120280, "author_profile": "https://wordpress.stackexchange.com/users/120280", "pm_score": 0, "selected": false, "text": "<p>yes, it is valid.\nas stands in reference <a href=\"https://developer.wordpress.org/reference/functions/esc_attr_e/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/esc_attr_e/</a>\nThis function displays translated text that has been escaped for safe use in an attribute and what is safe for attribute is certainly safe in html text.</p>\n\n<p>For simple strings (like 'Plugin Menu Name') this functions returns same output, but if you can, I recommend using appropriate function as already Tom J Nowell listed.</p>\n" } ]
2015/04/25
[ "https://wordpress.stackexchange.com/questions/185318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70831/" ]
From what I understand `esc_attr_e` is ideally used for escaping values in attributes - Is it right that the usage of `esc_attr_e` can also be worked in with non attribute values, such as the h3 and label elements in the example below? ``` <h3><?php esc_attr_e( 'Some Text', 'my-plugin' ); ?></h3> <form name="myplugin_form" method="post" action=""> <input type="hidden" name="myplugin_form_submitted" value="Y"> <table class="form-table"> <tr> <td><label for="ng_plugin_menu"><?php esc_attr_e( 'Plugin Menu Name', 'my-plugin' ); ?></label></td> <td><input name="ng_plugin_menu" id="ng_plugin_menu" type="text" value="<?php esc_attr_e ($my_plugin_label, 'my_plugin'); ?>" class="regular-text" placeholder="<?php esc_attr_e ('Placeholder Text', 'my_plugin'); ?>" /></td> </tr> </table> <p><input class="button-primary" type="submit" name="my_plugin_menu_submit" value="Save" /></p> </form> ``` So using `esc_attr_e` it instead of `_e`, I was told by a senior developer that this is valid, but am looking for confirmation. It is also the purpose of my sample code that I want to allow translation for all strings.
I would suggest using `esc_html` instead of `esc_attr` for that, e.g. ``` <a href="<?php echo esc_url( $url );?>" class="<?php echo esc_attr( $classes ); ?>"> <?php echo esc_html( $title ); ?> </a> <div> <?php echo wp_kses_post( $html_with_safe_tags );?> </div> <script> <?php echo wp_json_encode( $data_for_js ); ?> </script> ``` There is also: * `esc_html__` `esc_attr__` etc ( escape translations too! ) * `esc_js` - escape strings for javascript e.g. `console.log(<?php echo esc_js($var); ?>);` * `esc_url_raw` when redirecting, use this instead * `esc_sql` * `esc_textarea` * `sanitize_text_field` * Whitelisting values * type casting with `(int)` or `absint` * and others
185,326
<p>I'm creating a custom registration form which works using username and email inputs, but when I include First and Last name fields it won't let me register. </p> <p>Here is the form: </p> <pre><code>&lt;form id="_wb_register" action="&lt;?php echo home_url(); ?&gt;" method="post"&gt; &lt;p&gt; &lt;label for="_wb_register_username"&gt;&lt;?php _e('Username:', 'wb'); ?&gt;&lt;/label&gt; &lt;input type="text" name="username" id="_wb_register_username" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="_wb_register_user_first_name"&gt;&lt;?php _e('First Name:', 'wb'); ?&gt;&lt;/label&gt; &lt;input type="text" name="user_first_name" id="_wb_register_user_first_name" value="&lt;?php echo esc_attr( wp_unslash( $first_name ) ); ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="_wb_register_user_last_name"&gt;&lt;?php _e('Last Name:', 'wb'); ?&gt;&lt;/label&gt; &lt;input type="text" name="user_last_name" id="_wb_register_user_last_name" value="&lt;?php echo esc_attr( wp_unslash( $last_name ) ); ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="_wb_register_email"&gt;&lt;?php _e('Email:', 'wb'); ?&gt;&lt;/label&gt; &lt;input type="email" name="email" id="_wb_register_email" /&gt; &lt;/p&gt; &lt;div class="padding" style="height: 5px;"&gt;&lt;/div&gt; &lt;?php do_action('wb_user_panel_registration_form_bottom'); ?&gt; &lt;p&gt;&lt;input type="submit" value="&lt;?php _e('Sign Up', 'wb'); ?&gt;" class="button-primary" /&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <p>And here is the function used to create the user upon finishing the registration form:</p> <pre><code>add_action('wp_ajax__wb_register', '_wb_register_function'); add_action('wp_ajax_nopriv__wb_register', '_wb_register_function'); function _wb_register_function() { $return = array(); $return['error'] = false; $return['message'] = array(); //// VERIFIES NONCE $nonce = isset($_POST['nonce']) ? trim($_POST['nonce']) : ''; if(!wp_verify_nonce($nonce, 'wb-register-nonce')) die('Busted!'); //// VERIFIES CREDENTIALS $username = isset($_POST['username']) ? trim($_POST['username']) : ''; $first_name = isset($_POST['user_first_name']) ? trim($_POST['user_first_name']) : ''; $last_name = isset($_POST['user_last_name']) ? trim($_POST['user_last_name']) : ''; $email = isset($_POST['email']) ? trim($_POST['email']) : ''; //// MAKES SURE USER HAS FILLED USERNAME AND EMAIL if($email == '' || !is_email($email)) { $return['error'] = true; $return['message'] = __('Please type in a valid email address.', 'wb'); } if($last_name == '') { $return['error'] = true; $return['message'] = __('Please enter your last name.', 'wb'); } if($first_name == '') { $return['error'] = true; $return['message'] = __('Please enter your first name.', 'wb'); } if($username == '') { $return['error'] = true; $return['message'] = __('Please choose an username.', 'wb'); } ///// IF USER HAS FILLED USER, PASS, FIRST AND LAST if($return['error'] == false) { $return_registration = _wb_process_user_registration($return, $email, $username, $first_name, $last_name); $return = $return_registration; } echo json_encode($return); exit; } ////////////////////////////////////////////////////////////////////// ///// THIS FUNCTION PROCESSES REGISTRATIONS ////////////////////////////////////////////////////////////////////// function _wb_process_user_registration($return, $email, $username, $first_name, $last_name) { //// CHECKS IF USERNAME EXISTS $user = new WP_User('', $username); if(!$user-&gt;exists()) { //// CHECK FOR USERNAMES EMAIL $user = get_user_by('email', $email); if(!$user) { $password = wp_generate_password(); //// NOW WE CAN FINALLY REGISTER THE USER $args = array( 'user_login' =&gt; esc_attr($username), 'first_name' =&gt; $first_name, 'last_name' =&gt; $last_name, 'user_email' =&gt; $email, 'user_pass' =&gt; $password, 'role' =&gt; 'submitter', ); //// CREATES THE USER $user = wp_insert_user($args); if(!is_object($user)) { //// MAKES SURE HE CAN"T SEE THE ADMIN BAR update_user_meta($user, 'show_admin_bar_front', 'false'); $user = new WP_User($user); </code></pre> <p>When I submit the registration form it gives me the 'Please enter your first name.' error, so at least that part of the function is working. I don't understand why the First and Last names are not being registered when the Username and Email work just fine. Is there something I'm missing?</p>
[ { "answer_id": 185320, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>I would suggest using <code>esc_html</code> instead of <code>esc_attr</code> for that, e.g.</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo esc_url( $url );?&gt;\" class=\"&lt;?php echo esc_attr( $classes ); ?&gt;\"&gt;\n &lt;?php echo esc_html( $title ); ?&gt;\n&lt;/a&gt;\n&lt;div&gt;\n &lt;?php echo wp_kses_post( $html_with_safe_tags );?&gt;\n&lt;/div&gt;\n&lt;script&gt;\n &lt;?php echo wp_json_encode( $data_for_js ); ?&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>There is also:</p>\n\n<ul>\n<li><code>esc_html__</code> <code>esc_attr__</code> etc ( escape translations too! )</li>\n<li><code>esc_js</code> - escape strings for javascript e.g. <code>console.log(&lt;?php echo esc_js($var); ?&gt;);</code></li>\n<li><code>esc_url_raw</code> when redirecting, use this instead</li>\n<li><code>esc_sql</code></li>\n<li><code>esc_textarea</code></li>\n<li><code>sanitize_text_field</code></li>\n<li>Whitelisting values</li>\n<li>type casting with <code>(int)</code> or <code>absint</code></li>\n<li>and others</li>\n</ul>\n" }, { "answer_id": 267814, "author": "Filip Hanes", "author_id": 120280, "author_profile": "https://wordpress.stackexchange.com/users/120280", "pm_score": 0, "selected": false, "text": "<p>yes, it is valid.\nas stands in reference <a href=\"https://developer.wordpress.org/reference/functions/esc_attr_e/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/esc_attr_e/</a>\nThis function displays translated text that has been escaped for safe use in an attribute and what is safe for attribute is certainly safe in html text.</p>\n\n<p>For simple strings (like 'Plugin Menu Name') this functions returns same output, but if you can, I recommend using appropriate function as already Tom J Nowell listed.</p>\n" } ]
2015/04/25
[ "https://wordpress.stackexchange.com/questions/185326", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70006/" ]
I'm creating a custom registration form which works using username and email inputs, but when I include First and Last name fields it won't let me register. Here is the form: ``` <form id="_wb_register" action="<?php echo home_url(); ?>" method="post"> <p> <label for="_wb_register_username"><?php _e('Username:', 'wb'); ?></label> <input type="text" name="username" id="_wb_register_username" /> </p> <p> <label for="_wb_register_user_first_name"><?php _e('First Name:', 'wb'); ?></label> <input type="text" name="user_first_name" id="_wb_register_user_first_name" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" /> </p> <p> <label for="_wb_register_user_last_name"><?php _e('Last Name:', 'wb'); ?></label> <input type="text" name="user_last_name" id="_wb_register_user_last_name" value="<?php echo esc_attr( wp_unslash( $last_name ) ); ?>" /> </p> <p> <label for="_wb_register_email"><?php _e('Email:', 'wb'); ?></label> <input type="email" name="email" id="_wb_register_email" /> </p> <div class="padding" style="height: 5px;"></div> <?php do_action('wb_user_panel_registration_form_bottom'); ?> <p><input type="submit" value="<?php _e('Sign Up', 'wb'); ?>" class="button-primary" /></p> </form> ``` And here is the function used to create the user upon finishing the registration form: ``` add_action('wp_ajax__wb_register', '_wb_register_function'); add_action('wp_ajax_nopriv__wb_register', '_wb_register_function'); function _wb_register_function() { $return = array(); $return['error'] = false; $return['message'] = array(); //// VERIFIES NONCE $nonce = isset($_POST['nonce']) ? trim($_POST['nonce']) : ''; if(!wp_verify_nonce($nonce, 'wb-register-nonce')) die('Busted!'); //// VERIFIES CREDENTIALS $username = isset($_POST['username']) ? trim($_POST['username']) : ''; $first_name = isset($_POST['user_first_name']) ? trim($_POST['user_first_name']) : ''; $last_name = isset($_POST['user_last_name']) ? trim($_POST['user_last_name']) : ''; $email = isset($_POST['email']) ? trim($_POST['email']) : ''; //// MAKES SURE USER HAS FILLED USERNAME AND EMAIL if($email == '' || !is_email($email)) { $return['error'] = true; $return['message'] = __('Please type in a valid email address.', 'wb'); } if($last_name == '') { $return['error'] = true; $return['message'] = __('Please enter your last name.', 'wb'); } if($first_name == '') { $return['error'] = true; $return['message'] = __('Please enter your first name.', 'wb'); } if($username == '') { $return['error'] = true; $return['message'] = __('Please choose an username.', 'wb'); } ///// IF USER HAS FILLED USER, PASS, FIRST AND LAST if($return['error'] == false) { $return_registration = _wb_process_user_registration($return, $email, $username, $first_name, $last_name); $return = $return_registration; } echo json_encode($return); exit; } ////////////////////////////////////////////////////////////////////// ///// THIS FUNCTION PROCESSES REGISTRATIONS ////////////////////////////////////////////////////////////////////// function _wb_process_user_registration($return, $email, $username, $first_name, $last_name) { //// CHECKS IF USERNAME EXISTS $user = new WP_User('', $username); if(!$user->exists()) { //// CHECK FOR USERNAMES EMAIL $user = get_user_by('email', $email); if(!$user) { $password = wp_generate_password(); //// NOW WE CAN FINALLY REGISTER THE USER $args = array( 'user_login' => esc_attr($username), 'first_name' => $first_name, 'last_name' => $last_name, 'user_email' => $email, 'user_pass' => $password, 'role' => 'submitter', ); //// CREATES THE USER $user = wp_insert_user($args); if(!is_object($user)) { //// MAKES SURE HE CAN"T SEE THE ADMIN BAR update_user_meta($user, 'show_admin_bar_front', 'false'); $user = new WP_User($user); ``` When I submit the registration form it gives me the 'Please enter your first name.' error, so at least that part of the function is working. I don't understand why the First and Last names are not being registered when the Username and Email work just fine. Is there something I'm missing?
I would suggest using `esc_html` instead of `esc_attr` for that, e.g. ``` <a href="<?php echo esc_url( $url );?>" class="<?php echo esc_attr( $classes ); ?>"> <?php echo esc_html( $title ); ?> </a> <div> <?php echo wp_kses_post( $html_with_safe_tags );?> </div> <script> <?php echo wp_json_encode( $data_for_js ); ?> </script> ``` There is also: * `esc_html__` `esc_attr__` etc ( escape translations too! ) * `esc_js` - escape strings for javascript e.g. `console.log(<?php echo esc_js($var); ?>);` * `esc_url_raw` when redirecting, use this instead * `esc_sql` * `esc_textarea` * `sanitize_text_field` * Whitelisting values * type casting with `(int)` or `absint` * and others
185,340
<p>I have a custom PHP application and a Wordpress instance running as 2 completely separate codebases on the same server. I would like my custom PHP application to be able to consume content from the Wordpress instance as and when it is published or updated.</p> <p>I am using the excellent <a href="http://wp-api.org/" rel="nofollow">WP API</a> to retrieve JSON encoded Wordpress post(s) from my Wordpress instance. This plugin can retrieve all posts or an individual post (specified by id).</p> <p>This currently involves actively polling the Wordpress instance for all posts and then figuring out which are new or have been modified, which is not ideal.</p> <p>I would like Wordpress to notify my PHP application when a new post is created or updated. I realise there are numerous email notification plugins for Wordpress (the best one being <a href="https://wordpress.org/plugins/bnfw/" rel="nofollow">Better Notifications for Wordpress</a>). But I do not want the overhead of having to run an SMTP server and parsing email content.</p> <p>I have been looking for a solution which simply uses REST to send a POST or GET request to my application, passing the ID of the (recently published or updated) Wordpress post. I am not aware of any built-in Wordpress functionality or plugins which exist to achieve this.</p>
[ { "answer_id": 185348, "author": "gpnalin", "author_id": 68734, "author_profile": "https://wordpress.stackexchange.com/users/68734", "pm_score": -1, "selected": false, "text": "<p>You can use WP's <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">save_post</a> action hook with <a href=\"http://wp-api.org/guides/extending.html\" rel=\"nofollow\">extending WP-API plugin</a>.</p>\n" }, { "answer_id": 185365, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": true, "text": "<p>Use the <a href=\"https://codex.wordpress.org/HTTP_API\" rel=\"nofollow\">HTTP API</a> to send a \"ping\" on the <code>wp_insert_post</code> action, which is fired whenever a post is created/updated:</p>\n\n<pre><code>/**\n * @param int $post_id The ID of the post.\n * @param WP_Post $post The post object.\n * @param bool $update True if the post already exists and is being updated\n */\nfunction wpse_185340_post_ping( $post_id, $post, $update ) {\n if ( $post-&gt;post_status === 'publish' ) { // Only fire when published\n wp_remote_post(\n 'http://example.com/application/notify',\n array(\n // https://codex.wordpress.org/HTTP_API\n 'blocking' =&gt; false, // If you don't need to know the response, disable blocking for an \"async\" request\n 'body' =&gt; array(\n 'post_id' =&gt; $post_id,\n 'post' =&gt; json_encode( $post ),\n 'update' =&gt; ( int ) $update,\n // or whatever\n )\n )\n );\n } \n}\n\nadd_action( 'wp_insert_post', 'wpse_185340_post_ping', 10, 3 );\n</code></pre>\n" } ]
2015/04/25
[ "https://wordpress.stackexchange.com/questions/185340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71163/" ]
I have a custom PHP application and a Wordpress instance running as 2 completely separate codebases on the same server. I would like my custom PHP application to be able to consume content from the Wordpress instance as and when it is published or updated. I am using the excellent [WP API](http://wp-api.org/) to retrieve JSON encoded Wordpress post(s) from my Wordpress instance. This plugin can retrieve all posts or an individual post (specified by id). This currently involves actively polling the Wordpress instance for all posts and then figuring out which are new or have been modified, which is not ideal. I would like Wordpress to notify my PHP application when a new post is created or updated. I realise there are numerous email notification plugins for Wordpress (the best one being [Better Notifications for Wordpress](https://wordpress.org/plugins/bnfw/)). But I do not want the overhead of having to run an SMTP server and parsing email content. I have been looking for a solution which simply uses REST to send a POST or GET request to my application, passing the ID of the (recently published or updated) Wordpress post. I am not aware of any built-in Wordpress functionality or plugins which exist to achieve this.
Use the [HTTP API](https://codex.wordpress.org/HTTP_API) to send a "ping" on the `wp_insert_post` action, which is fired whenever a post is created/updated: ``` /** * @param int $post_id The ID of the post. * @param WP_Post $post The post object. * @param bool $update True if the post already exists and is being updated */ function wpse_185340_post_ping( $post_id, $post, $update ) { if ( $post->post_status === 'publish' ) { // Only fire when published wp_remote_post( 'http://example.com/application/notify', array( // https://codex.wordpress.org/HTTP_API 'blocking' => false, // If you don't need to know the response, disable blocking for an "async" request 'body' => array( 'post_id' => $post_id, 'post' => json_encode( $post ), 'update' => ( int ) $update, // or whatever ) ) ); } } add_action( 'wp_insert_post', 'wpse_185340_post_ping', 10, 3 ); ```
185,359
<p>My category structure is as follows:</p> <pre><code>- Top Category ---- Sub Category 1 ------- Sub Sub Category 1.1 ------- Sub Sub Category 1.2 ------- Sub Sub Category 1.3 ---- Sub Category 2 ------- Sub Sub Category 2.1 ------- Sub Sub Category 2.2 ------- Sub Sub Category 2.3 </code></pre> <p>I'm on a post under 1.2 so it would be:</p> <pre><code>Top Category -&gt; Sub Category 1 -&gt; Sub Sub Category 1.2 -&gt; Current Post </code></pre> <p>NB: In the post ONLY "Sub Category 1" and "Sub Sub Category 1.2" are selected as categories ("Top Category" is not checked).</p> <p>Now, how do I get get the slug of the Top Category ("top-category"), navigating backward?</p> <p>Thanks!</p>
[ { "answer_id": 212570, "author": "thebigtine", "author_id": 76059, "author_profile": "https://wordpress.stackexchange.com/users/76059", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://codex.wordpress.org/Function_Reference/get_ancestors\" rel=\"nofollow\"><code>get_ancestors()</code></a> returns an array containing the parents of any given object. </p>\n\n<p>This example has two categories. The parent with the id of 447 and the child with a id of 448 and returns the a category hierarchy (with IDs):</p>\n\n<pre><code>get_ancestors( 448, 'category' ); \n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>Array\n(\n [0] =&gt; 447\n) \n</code></pre>\n\n<h2><a href=\"http://codex.wordpress.org/Function_Reference/get_ancestors\" rel=\"nofollow\">get_ancestors Codex Page</a></h2> \n" }, { "answer_id": 348714, "author": "geokha29", "author_id": 122449, "author_profile": "https://wordpress.stackexchange.com/users/122449", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_ancestors/\" rel=\"nofollow noreferrer\">get_ancestors()</a></p>\n\n<p>Is the correct way to get all the parent categories of a specific category in the hierarchical order, so to get the highest level parent you could extract the last item of the array returned like this:</p>\n\n<pre><code>// getting all the ancestors of the categories \n$ancestor_cat_ids = get_ancestors( $queried_cat_id, 'category');\n\n// getting the last item of the array of ids returned by the get_ancestors() function\n$highest_ancestor = $ancestor_cat_ids[count($ancestor_cat_ids) - 1];\n</code></pre>\n" } ]
2015/04/25
[ "https://wordpress.stackexchange.com/questions/185359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56525/" ]
My category structure is as follows: ``` - Top Category ---- Sub Category 1 ------- Sub Sub Category 1.1 ------- Sub Sub Category 1.2 ------- Sub Sub Category 1.3 ---- Sub Category 2 ------- Sub Sub Category 2.1 ------- Sub Sub Category 2.2 ------- Sub Sub Category 2.3 ``` I'm on a post under 1.2 so it would be: ``` Top Category -> Sub Category 1 -> Sub Sub Category 1.2 -> Current Post ``` NB: In the post ONLY "Sub Category 1" and "Sub Sub Category 1.2" are selected as categories ("Top Category" is not checked). Now, how do I get get the slug of the Top Category ("top-category"), navigating backward? Thanks!
[`get_ancestors()`](http://codex.wordpress.org/Function_Reference/get_ancestors) returns an array containing the parents of any given object. This example has two categories. The parent with the id of 447 and the child with a id of 448 and returns the a category hierarchy (with IDs): ``` get_ancestors( 448, 'category' ); ``` returns: ``` Array ( [0] => 447 ) ``` [get\_ancestors Codex Page](http://codex.wordpress.org/Function_Reference/get_ancestors) ----------------------------------------------------------------------------------------
185,366
<p>I'm currently transitioning a website from their existing CMS to WordPress.</p> <p>I have a custom post type of 'Episodes', with a URL of myurl.com/episodes/</p> <p>There is also an existing directory at myurl.com/episodes/ which needs to remain in place for historical reasons - it contains a large number of images and static HTML files which will still need to resolve.</p> <p>At the moment, because the /episodes/ directory exists, WordPress won't go anywhere near it, so the pages under my custom post type don't load.</p> <p>This happens because WordPress's default .htaccess has two rules, which state that any existing file or existing directory should be not be handled by WordPress:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d </code></pre> <p>But these rules stops /episodes/ from being handled by WordPress at all. I want WordPress to handle /episodes/ by default, and only not do so if the file in question exists.</p> <p>But having the first line on its own - i.e. pass everything to WordPress unless the file in question exists - doesn't seem to do the trick.</p> <p>Is there a way I can re-write these rewrite rules so that WordPress will still handle the request if the directory exists, but not if the <em><strong>file</strong></em> exists?</p>
[ { "answer_id": 185369, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Not using WordPress. With that directory in place, your web server doesn't even touch WordPress when it handles the request.</p>\n\n<p>I would:</p>\n\n<ul>\n<li>Move as much of your stuff as possible away from using that folder</li>\n<li>Rename the rewrite rule so that it's not just <code>/episodes/</code> so that it doesn't clash</li>\n</ul>\n\n<p>You could try moving the folder and adding redirects, but at that level you're at the Apache/Nginx level, not the WordPress level</p>\n" }, { "answer_id": 185374, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>broad lines of what you need to do</p>\n\n<ol>\n<li>change the .htaccess to let wordpress have priority over the directory</li>\n<li>handle wordpress url parsing </li>\n</ol>\n\n<p>You have two good options for handling the parsing</p>\n\n<ul>\n<li>hook on the init action and check if the url is of a file that exists in the directory</li>\n<li>do the file check in your theme's 404.php file before outputting any html.</li>\n</ul>\n\n<p>(step skipped: detecting the file type and sending it with the proper encoding via php functions)</p>\n\n<p>I think that the 404 approach is more robust as it gives the lowest priority to those historical files. You can find the hook that is called to load the theme's 404 file and use it if you prefer to leave the functionality out of the presentation oriented code.</p>\n\n<p>The biggest problem you might face is performance as for each small file you will have to load wordpress, connect to the DB etc. It might not be a huge problem if there is no traffic going to those files, but it is a risk.</p>\n\n<p>Therefor what you should consider is refining the .htaccess to keep the current algorithm of files first when the url ends with .png .jpg .gif .pdf and only if not go pass control to wordpress.</p>\n" } ]
2015/04/25
[ "https://wordpress.stackexchange.com/questions/185366", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71175/" ]
I'm currently transitioning a website from their existing CMS to WordPress. I have a custom post type of 'Episodes', with a URL of myurl.com/episodes/ There is also an existing directory at myurl.com/episodes/ which needs to remain in place for historical reasons - it contains a large number of images and static HTML files which will still need to resolve. At the moment, because the /episodes/ directory exists, WordPress won't go anywhere near it, so the pages under my custom post type don't load. This happens because WordPress's default .htaccess has two rules, which state that any existing file or existing directory should be not be handled by WordPress: ``` RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d ``` But these rules stops /episodes/ from being handled by WordPress at all. I want WordPress to handle /episodes/ by default, and only not do so if the file in question exists. But having the first line on its own - i.e. pass everything to WordPress unless the file in question exists - doesn't seem to do the trick. Is there a way I can re-write these rewrite rules so that WordPress will still handle the request if the directory exists, but not if the ***file*** exists?
Not using WordPress. With that directory in place, your web server doesn't even touch WordPress when it handles the request. I would: * Move as much of your stuff as possible away from using that folder * Rename the rewrite rule so that it's not just `/episodes/` so that it doesn't clash You could try moving the folder and adding redirects, but at that level you're at the Apache/Nginx level, not the WordPress level
185,444
<p>I would like to use a different menu for my mobile website than my desktop website. With different I mean the content not the layout. I just want to use the mobile menu of the twentytwelve theme.</p> <p>What I've done so far:</p> <p>In my child functions.php i've added the following code:</p> <pre><code> register_nav_menus( array( 'primary' =&gt; __( 'Primary Navigation', 'twentytwelve' ), 'mobile' =&gt; __( 'Mobile Navigation', 'mobile'), ) ); </code></pre> <p>Now i'm able to create two menus in my dashboard. (dashboard>menu>locaties)</p> <p>In the header.php I don't know exactly what to change so my mobile menu is loaded instead of my primary menu.</p> <pre><code> &lt;nav id="site-navigation" class="main-navigation" role="navigation"&gt; &lt;button class="menu-toggle"&gt;&lt;?php _e( 'Menu', 'twentytwelve' ); ?&gt;&lt;/button&gt; &lt;a class="assistive-text" href="#content" title="&lt;?php esc_attr_e( 'Skip to content', 'twentytwelve' ); ?&gt;"&gt;&lt;?php _e( 'Skip to content', 'twentytwelve' ); ?&gt;&lt;/a&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'menu_class' =&gt; 'nav-menu' ) ); ?&gt; &lt;/nav&gt;&lt;!-- #site-navigation --&gt; </code></pre> <p>I've tried to change the <code>&lt;?php _e( 'Menu', 'twentytwelve' ); ?&gt;</code> to <code>&lt;?php _e( 'Menu', 'mobile' ); ?&gt;</code>, but this didn't change the menu content to my mobile menu.</p> <p>I'm not that familiar with this code so hopefully someone can point me in de right direction.</p> <p>Thank you for your help!</p>
[ { "answer_id": 190832, "author": "Nikolai", "author_id": 74343, "author_profile": "https://wordpress.stackexchange.com/users/74343", "pm_score": 3, "selected": false, "text": "<p>As recommended in a similar post: <a href=\"https://wordpress.stackexchange.com/a/156494/74343\">https://wordpress.stackexchange.com/a/156494/74343</a> </p>\n\n<p>1.) Create the <a href=\"https://codex.wordpress.org/Appearance_Menus_Screen\" rel=\"nofollow noreferrer\">menus</a> as you want them, and name them as you like, as an example \"<strong>mobile-menu</strong>\" and \"<strong>desktop-menu</strong>\".</p>\n\n<p>2.) In your <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> in the header.php you could switch according to the wp_is_mobile() flag like this:</p>\n\n<pre><code>if ( wp_is_mobile() ) {\n wp_nav_menu( array( 'menu' =&gt; 'mobile-menu' ) );\n} else {\n wp_nav_menu( array( 'menu' =&gt; 'desktop-menu' ) );\n}\n</code></pre>\n\n<p><strong>However</strong> I used the \"WP Responsive Menu\" plugin, which allowed me to select a menu for mobile as well. In the configuration of the \"WP Responsive Menu\" one needs to select the element NOT to show on mobile, which in the case of the twenty twelve theme is: \"#site-navigation\".</p>\n\n<p>Happy coding!</p>\n" }, { "answer_id": 294964, "author": "Jordan", "author_id": 137440, "author_profile": "https://wordpress.stackexchange.com/users/137440", "pm_score": 2, "selected": false, "text": "<p>If anyone is still watching this thread, I had been struggling with this for a while, none of these worked... I could do it with CSS! </p>\n\n<p>Basically, create one giant menu with all the items you want on mobile and desktop. Then, add classes: \"hide-mobile\" and \"hide-desktop\" on their respective menu items. </p>\n\n<p>Use this CSS: </p>\n\n<pre><code>@media (min-width: 980px){\n\n .hide-desktop{\n display: none !important;\n }\n\n}\n\n @media (max-width: 980px){\n .hide-mobile{\n display: none !important;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 310511, "author": "Jeroen Onstenk", "author_id": 148102, "author_profile": "https://wordpress.stackexchange.com/users/148102", "pm_score": 0, "selected": false, "text": "<p>In addition to Jordans comment, it is important to know how to add a class to a menu item in Wordpress:</p>\n\n<p>To add CSS classes to a WordPress menu, first go to Appearance > Menus in your WordPress theme. Next, find the Screen Options tab at the top right of the screen. Click to open the panel, and check the box labelled CSS Classes. Select the menu you want to edit, and click the link you want to add a CSS class to.</p>\n" }, { "answer_id": 346783, "author": "BrianHenryIE", "author_id": 129606, "author_profile": "https://wordpress.stackexchange.com/users/129606", "pm_score": 0, "selected": false, "text": "<p>Another approach which doesn't involve overriding theme files/templates:</p>\n\n<p>In the child theme's <code>functions.php</code> add:</p>\n\n<pre><code>/**\n * Register the 'mobile' menu location with WordPress so it can be configured in the admin UI.\n */\nregister_nav_menus( array(\n 'mobile' =&gt; 'Mobile Replace Primary',\n) );\n\n/**\n * When building menus, if the menu location 'primary' is being used, and we're on mobile,\n * swap it out for the menu location 'mobile'.\n * \n * @see wp_nav_menu()\n */\nadd_filter( 'wp_nav_menu_args', function( $args ) {\n\n if( 'primary' === $args['theme_location'] &amp;&amp; wp_is_mobile() ) {\n $args['theme_location'] = 'mobile';\n }\n\n return $args;\n} );\n</code></pre>\n\n<p>Then configure your mobile menu in <code>wp-admin</code> / <code>Appearance</code> / <code>Menus</code>.</p>\n" } ]
2015/04/26
[ "https://wordpress.stackexchange.com/questions/185444", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71216/" ]
I would like to use a different menu for my mobile website than my desktop website. With different I mean the content not the layout. I just want to use the mobile menu of the twentytwelve theme. What I've done so far: In my child functions.php i've added the following code: ``` register_nav_menus( array( 'primary' => __( 'Primary Navigation', 'twentytwelve' ), 'mobile' => __( 'Mobile Navigation', 'mobile'), ) ); ``` Now i'm able to create two menus in my dashboard. (dashboard>menu>locaties) In the header.php I don't know exactly what to change so my mobile menu is loaded instead of my primary menu. ``` <nav id="site-navigation" class="main-navigation" role="navigation"> <button class="menu-toggle"><?php _e( 'Menu', 'twentytwelve' ); ?></button> <a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentytwelve' ); ?>"><?php _e( 'Skip to content', 'twentytwelve' ); ?></a> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?> </nav><!-- #site-navigation --> ``` I've tried to change the `<?php _e( 'Menu', 'twentytwelve' ); ?>` to `<?php _e( 'Menu', 'mobile' ); ?>`, but this didn't change the menu content to my mobile menu. I'm not that familiar with this code so hopefully someone can point me in de right direction. Thank you for your help!
As recommended in a similar post: <https://wordpress.stackexchange.com/a/156494/74343> 1.) Create the [menus](https://codex.wordpress.org/Appearance_Menus_Screen) as you want them, and name them as you like, as an example "**mobile-menu**" and "**desktop-menu**". 2.) In your [child theme](https://codex.wordpress.org/Child_Themes) in the header.php you could switch according to the wp\_is\_mobile() flag like this: ``` if ( wp_is_mobile() ) { wp_nav_menu( array( 'menu' => 'mobile-menu' ) ); } else { wp_nav_menu( array( 'menu' => 'desktop-menu' ) ); } ``` **However** I used the "WP Responsive Menu" plugin, which allowed me to select a menu for mobile as well. In the configuration of the "WP Responsive Menu" one needs to select the element NOT to show on mobile, which in the case of the twenty twelve theme is: "#site-navigation". Happy coding!
185,456
<p>Is it possible to display the author on all pages (not blog-entries) who created it? Every plugin I find is for blog-posts. </p>
[ { "answer_id": 185459, "author": "Ben H", "author_id": 64567, "author_profile": "https://wordpress.stackexchange.com/users/64567", "pm_score": 1, "selected": false, "text": "<p>If I have understood correctly you should be able to edit your page template to include the below. I'm not sure on any plugin to do this though. </p>\n\n<p>More info: <a href=\"https://codex.wordpress.org/Function_Reference/get_the_author\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_the_author</a></p>\n\n<pre><code> &lt;?php $author = get_the_author(); echo \"$author\"; ?&gt;\n</code></pre>\n\n<p>** This is untested</p>\n" }, { "answer_id": 185461, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 3, "selected": true, "text": "<p>You need to add the following code to content-page.php in your theme folder.</p>\n\n<pre><code>&lt;?php the_author(); ?&gt;\n</code></pre>\n" } ]
2015/04/26
[ "https://wordpress.stackexchange.com/questions/185456", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71223/" ]
Is it possible to display the author on all pages (not blog-entries) who created it? Every plugin I find is for blog-posts.
You need to add the following code to content-page.php in your theme folder. ``` <?php the_author(); ?> ```
185,462
<p>We have one custom requirement that when we add an image (suppose a car image) in the homepage, after that when I'm creating a new page, I always want that car image to appear on the right hand side by default. So whenever I'm changing the homepage car image to some other image, it should reflect on other pages also.</p> <p>I'm just unable implement this requirement, how to go about it? </p>
[ { "answer_id": 185459, "author": "Ben H", "author_id": 64567, "author_profile": "https://wordpress.stackexchange.com/users/64567", "pm_score": 1, "selected": false, "text": "<p>If I have understood correctly you should be able to edit your page template to include the below. I'm not sure on any plugin to do this though. </p>\n\n<p>More info: <a href=\"https://codex.wordpress.org/Function_Reference/get_the_author\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_the_author</a></p>\n\n<pre><code> &lt;?php $author = get_the_author(); echo \"$author\"; ?&gt;\n</code></pre>\n\n<p>** This is untested</p>\n" }, { "answer_id": 185461, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 3, "selected": true, "text": "<p>You need to add the following code to content-page.php in your theme folder.</p>\n\n<pre><code>&lt;?php the_author(); ?&gt;\n</code></pre>\n" } ]
2015/04/26
[ "https://wordpress.stackexchange.com/questions/185462", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71224/" ]
We have one custom requirement that when we add an image (suppose a car image) in the homepage, after that when I'm creating a new page, I always want that car image to appear on the right hand side by default. So whenever I'm changing the homepage car image to some other image, it should reflect on other pages also. I'm just unable implement this requirement, how to go about it?
You need to add the following code to content-page.php in your theme folder. ``` <?php the_author(); ?> ```
185,473
<p>I am trying to do a query to grab all the pages that have the tickbox checked <code>"feature_on_front_page"</code> which has the value <code>"featured"</code> with label <code>"Featured"</code>.</p> <p>I added this checkbox with ACF.</p> <p>My query is:</p> <pre><code> &lt;?php wp_reset_query(); // Restore global post data stomped by the_post(). ?&gt; &lt;?php // args $args = array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'page', 'meta_key' =&gt; 'feature_on_front_page', 'meta_value' =&gt; 'featured' ); // query $the_query = new WP_Query( $args ); ?&gt; &lt;?php if( $the_query-&gt;have_posts() ): ?&gt; &lt;ul&gt; &lt;?php while( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;li&gt; do some stuff &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); // Restore global post data stomped by the_post(). ?&gt; </code></pre> <p>It brings back 0 results. I looked in database and the <code>"feature_on_front_page"</code> key has data value <code>"a:1:{i:0;s:8:"featured";}"</code></p> <p>I have tried using array instead of string but I can't work out exactly what I am doing wrong</p> <p>I tried:</p> <pre><code>'meta_value' =&gt; array('Featured' =&gt; 'featured') </code></pre> <p>and</p> <pre><code>'meta_value' =&gt; array('featured') </code></pre> <p>and various other variations. I know this is simple but I can't see where I am going wrong.</p> <p>Here is what it looks like in database:</p> <p><img src="https://i.stack.imgur.com/YDgcr.png" alt="enter image description here"></p>
[ { "answer_id": 185477, "author": "Rituparna sonowal", "author_id": 71232, "author_profile": "https://wordpress.stackexchange.com/users/71232", "pm_score": -1, "selected": false, "text": "<p>Try \"posts_per_page\" in place of \"numberposts\". numberposts is not a valid parameter of WP_Query.</p>\n\n<p>if you are using \"ACF\", then I think this will not work with WP_Query. This is not logical but I had same kind of bad experience. Try once</p>\n" }, { "answer_id": 185478, "author": "sqrbrkt", "author_id": 71174, "author_profile": "https://wordpress.stackexchange.com/users/71174", "pm_score": 2, "selected": true, "text": "<p>UPDATE: Ok this should work, according to ACF's documentation:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'page',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'feature_on_front_page',\n 'value' =&gt; 'featured',\n 'compare' =&gt; 'LIKE'\n ),\n )\n);\n</code></pre>\n\n<hr>\n\n<p>Your code works for me. </p>\n\n<p>Can you see the <code>feature_on_front_page</code> custom field when you view the page(s) in the WordPress admin area?</p>\n\n<p>Or perhaps the problem lies in the <code>do some stuff</code> section you've omitted?</p>\n" } ]
2015/04/26
[ "https://wordpress.stackexchange.com/questions/185473", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70230/" ]
I am trying to do a query to grab all the pages that have the tickbox checked `"feature_on_front_page"` which has the value `"featured"` with label `"Featured"`. I added this checkbox with ACF. My query is: ``` <?php wp_reset_query(); // Restore global post data stomped by the_post(). ?> <?php // args $args = array( 'numberposts' => -1, 'post_type' => 'page', 'meta_key' => 'feature_on_front_page', 'meta_value' => 'featured' ); // query $the_query = new WP_Query( $args ); ?> <?php if( $the_query->have_posts() ): ?> <ul> <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?> <li> do some stuff </li> <?php endwhile; ?> </ul> <?php endif; ?> <?php wp_reset_query(); // Restore global post data stomped by the_post(). ?> ``` It brings back 0 results. I looked in database and the `"feature_on_front_page"` key has data value `"a:1:{i:0;s:8:"featured";}"` I have tried using array instead of string but I can't work out exactly what I am doing wrong I tried: ``` 'meta_value' => array('Featured' => 'featured') ``` and ``` 'meta_value' => array('featured') ``` and various other variations. I know this is simple but I can't see where I am going wrong. Here is what it looks like in database: ![enter image description here](https://i.stack.imgur.com/YDgcr.png)
UPDATE: Ok this should work, according to ACF's documentation: ``` $args = array( 'posts_per_page' => -1, 'post_type' => 'page', 'meta_query' => array( array( 'key' => 'feature_on_front_page', 'value' => 'featured', 'compare' => 'LIKE' ), ) ); ``` --- Your code works for me. Can you see the `feature_on_front_page` custom field when you view the page(s) in the WordPress admin area? Or perhaps the problem lies in the `do some stuff` section you've omitted?
185,511
<p>I am using the below in my wordpress for developing a oauth based application.</p> <p><strong>WP-API</strong> (api generating plugin)</p> <p><strong>WP API OAuth1</strong> (oauth server)and </p> <p><strong>WP API client-cli</strong> (oauth client library)</p> <p>at the below url is for the wp client-cli <a href="https://man-sudarshann-1.c9.io/api/" rel="nofollow">https://man-sudarshann-1.c9.io/api/</a></p> <p>I am getting this error <strong>OAuth signature does not match</strong> when I click the AUTH button for autherizing the request. I have tried all the fixed for this over the internet. but none helped</p> <p>signature generated and sent from api client is <strong>3ko8DUsUUEB4Hqaks68vGYnTjQM=</strong> </p> <p>signature generated in server side is <strong>5rPsul6zplhfNvb4o+Mz11O/OyI=</strong></p> <p>so the below code is failing</p> <pre><code>if ( ! hash_equals( $signature, $consumer_signature ) ) { return new WP_Error( 'json_oauth1_signature_mismatch', __( 'OAuth signature does not match' ), array( 'status' =&gt; 401 ) ); } </code></pre> <p>I guess the API console is generating wrong signature. Please help me in solving this issue.</p>
[ { "answer_id": 201885, "author": "bilalshahid10", "author_id": 79978, "author_profile": "https://wordpress.stackexchange.com/users/79978", "pm_score": 1, "selected": true, "text": "<p>I was facing a similar issue when trying to use Client-CLI with OAuth 1.0a plugin, however I found a solution <a href=\"https://github.com/WP-API/OAuth1/pull/32\" rel=\"nofollow\">here</a> on the official repository.</p>\n\n<p>In the file <code>lib/class-wp-json-authentication-oauth1.php</code> on line <code>524</code>, change the following code:</p>\n\n<pre><code>$base_request_uri = rawurlencode( get_home_url( null, parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), 'http' ) );\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>$home_url_path = parse_url(get_home_url (null,'','http'), PHP_URL_PATH );\n$request_uri_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );\nif (substr($request_uri_path, 0, strlen($home_url_path)) == $home_url_path) {\n $request_uri_path = substr($request_uri_path, strlen($home_url_path));\n}\n$base_request_uri = rawurlencode( get_home_url( null, $request_uri_path, 'http' ) );\n</code></pre>\n\n<p>This should solve the problem you are facing.</p>\n" }, { "answer_id": 232021, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>Make sure that signature request is handled correctly:\n<a href=\"http://oauth1.wp-api.org/docs/basics/Signing.html\" rel=\"nofollow noreferrer\">http://oauth1.wp-api.org/docs/basics/Signing.html</a></p>\n\n<p>If you're using POSTMAN you can set it to OAuth 1.0 under Authorization and then select the options</p>\n\n<ul>\n<li>Add empty params to signature</li>\n<li>Encode OAuth signature</li>\n<li>Save helper data to request</li>\n</ul>\n\n<p>Here's a detailed tutorial I wrote on using OAuth 1 and Postman with WordPress: <a href=\"https://wordpress.stackexchange.com/a/239873/51201\">https://wordpress.stackexchange.com/a/239873/51201</a></p>\n" }, { "answer_id": 255841, "author": "Master Ace", "author_id": 112953, "author_profile": "https://wordpress.stackexchange.com/users/112953", "pm_score": 2, "selected": false, "text": "<p>In Postman under <strong>Authorization</strong> try deselecting \"<strong>Add params to header</strong>\".</p>\n" }, { "answer_id": 270639, "author": "Thupten", "author_id": 122150, "author_profile": "https://wordpress.stackexchange.com/users/122150", "pm_score": 0, "selected": false, "text": "<p>check you baseurl forwarding. \nIn my case the non-www was being forwarded to www. After updating the baseurl to www.example.com format it worked for me.</p>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71251/" ]
I am using the below in my wordpress for developing a oauth based application. **WP-API** (api generating plugin) **WP API OAuth1** (oauth server)and **WP API client-cli** (oauth client library) at the below url is for the wp client-cli <https://man-sudarshann-1.c9.io/api/> I am getting this error **OAuth signature does not match** when I click the AUTH button for autherizing the request. I have tried all the fixed for this over the internet. but none helped signature generated and sent from api client is **3ko8DUsUUEB4Hqaks68vGYnTjQM=** signature generated in server side is **5rPsul6zplhfNvb4o+Mz11O/OyI=** so the below code is failing ``` if ( ! hash_equals( $signature, $consumer_signature ) ) { return new WP_Error( 'json_oauth1_signature_mismatch', __( 'OAuth signature does not match' ), array( 'status' => 401 ) ); } ``` I guess the API console is generating wrong signature. Please help me in solving this issue.
I was facing a similar issue when trying to use Client-CLI with OAuth 1.0a plugin, however I found a solution [here](https://github.com/WP-API/OAuth1/pull/32) on the official repository. In the file `lib/class-wp-json-authentication-oauth1.php` on line `524`, change the following code: ``` $base_request_uri = rawurlencode( get_home_url( null, parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), 'http' ) ); ``` to: ``` $home_url_path = parse_url(get_home_url (null,'','http'), PHP_URL_PATH ); $request_uri_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ); if (substr($request_uri_path, 0, strlen($home_url_path)) == $home_url_path) { $request_uri_path = substr($request_uri_path, strlen($home_url_path)); } $base_request_uri = rawurlencode( get_home_url( null, $request_uri_path, 'http' ) ); ``` This should solve the problem you are facing.
185,512
<p>Currently I'm working on a plugin that will display a grid based on post type with many settings to customize it. One of the settings will be to choose between different skins available to display inside the grid.</p> <p>I would like to offer the possibility to developers to include their own skins with a custom HOOK/Filter.</p> <p>What is the right way to add this functionality in a plugin?</p> <p>I was thinking about something like this but I'm not sure if it's the right way and if it will work:</p> <pre><code>// register skin class in plugin class skinclass { //existing skins function myclass() { } do_action('add_custom_skin'); } // developers register action to include it's own skins (in function.php) add_action('add_custom_skin','my_custom_skins') function my_custom_skins($post) { function skin1($post) { $skin1 = '&lt;article class="skin1-holder"&gt;'; $skin1 .= '&lt;h2 class="skin1-title"&gt;'. get_the_title() .'&lt;/h2&gt;'; $skin1 .= '&lt;div class="skin1-excerpt"&gt;'. get_the_excerpt() .'&lt;/div&gt;'; $skin1 .= '&lt;/article&gt;'; return $skin1; } function skin2($post) { $skin2 = '&lt;article class="skin2-holder"&gt;'; $skin2 .= '&lt;h2 class="skin2-title"&gt;'. get_the_title() .'&lt;/h2&gt;'; $skin2 .= '&lt;div class="skin2-excerpt"&gt;'. get_the_excerpt() .'&lt;/div&gt;'; $skin2 .= '&lt;/article&gt;'; return $skin2; } } // get skin function in plugin $skins = get_class_methods(new skinclass()); // to output skin in a drop down list foreach ($skins as $skin_name) { echo "$skin_name\n"; } // output skin in front end $func = 'skin1'; $func(); </code></pre> <p>The skin to output will be in a query_posts loop.</p>
[ { "answer_id": 201885, "author": "bilalshahid10", "author_id": 79978, "author_profile": "https://wordpress.stackexchange.com/users/79978", "pm_score": 1, "selected": true, "text": "<p>I was facing a similar issue when trying to use Client-CLI with OAuth 1.0a plugin, however I found a solution <a href=\"https://github.com/WP-API/OAuth1/pull/32\" rel=\"nofollow\">here</a> on the official repository.</p>\n\n<p>In the file <code>lib/class-wp-json-authentication-oauth1.php</code> on line <code>524</code>, change the following code:</p>\n\n<pre><code>$base_request_uri = rawurlencode( get_home_url( null, parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), 'http' ) );\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>$home_url_path = parse_url(get_home_url (null,'','http'), PHP_URL_PATH );\n$request_uri_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );\nif (substr($request_uri_path, 0, strlen($home_url_path)) == $home_url_path) {\n $request_uri_path = substr($request_uri_path, strlen($home_url_path));\n}\n$base_request_uri = rawurlencode( get_home_url( null, $request_uri_path, 'http' ) );\n</code></pre>\n\n<p>This should solve the problem you are facing.</p>\n" }, { "answer_id": 232021, "author": "sMyles", "author_id": 51201, "author_profile": "https://wordpress.stackexchange.com/users/51201", "pm_score": 2, "selected": false, "text": "<p>Make sure that signature request is handled correctly:\n<a href=\"http://oauth1.wp-api.org/docs/basics/Signing.html\" rel=\"nofollow noreferrer\">http://oauth1.wp-api.org/docs/basics/Signing.html</a></p>\n\n<p>If you're using POSTMAN you can set it to OAuth 1.0 under Authorization and then select the options</p>\n\n<ul>\n<li>Add empty params to signature</li>\n<li>Encode OAuth signature</li>\n<li>Save helper data to request</li>\n</ul>\n\n<p>Here's a detailed tutorial I wrote on using OAuth 1 and Postman with WordPress: <a href=\"https://wordpress.stackexchange.com/a/239873/51201\">https://wordpress.stackexchange.com/a/239873/51201</a></p>\n" }, { "answer_id": 255841, "author": "Master Ace", "author_id": 112953, "author_profile": "https://wordpress.stackexchange.com/users/112953", "pm_score": 2, "selected": false, "text": "<p>In Postman under <strong>Authorization</strong> try deselecting \"<strong>Add params to header</strong>\".</p>\n" }, { "answer_id": 270639, "author": "Thupten", "author_id": 122150, "author_profile": "https://wordpress.stackexchange.com/users/122150", "pm_score": 0, "selected": false, "text": "<p>check you baseurl forwarding. \nIn my case the non-www was being forwarded to www. After updating the baseurl to www.example.com format it worked for me.</p>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185512", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35097/" ]
Currently I'm working on a plugin that will display a grid based on post type with many settings to customize it. One of the settings will be to choose between different skins available to display inside the grid. I would like to offer the possibility to developers to include their own skins with a custom HOOK/Filter. What is the right way to add this functionality in a plugin? I was thinking about something like this but I'm not sure if it's the right way and if it will work: ``` // register skin class in plugin class skinclass { //existing skins function myclass() { } do_action('add_custom_skin'); } // developers register action to include it's own skins (in function.php) add_action('add_custom_skin','my_custom_skins') function my_custom_skins($post) { function skin1($post) { $skin1 = '<article class="skin1-holder">'; $skin1 .= '<h2 class="skin1-title">'. get_the_title() .'</h2>'; $skin1 .= '<div class="skin1-excerpt">'. get_the_excerpt() .'</div>'; $skin1 .= '</article>'; return $skin1; } function skin2($post) { $skin2 = '<article class="skin2-holder">'; $skin2 .= '<h2 class="skin2-title">'. get_the_title() .'</h2>'; $skin2 .= '<div class="skin2-excerpt">'. get_the_excerpt() .'</div>'; $skin2 .= '</article>'; return $skin2; } } // get skin function in plugin $skins = get_class_methods(new skinclass()); // to output skin in a drop down list foreach ($skins as $skin_name) { echo "$skin_name\n"; } // output skin in front end $func = 'skin1'; $func(); ``` The skin to output will be in a query\_posts loop.
I was facing a similar issue when trying to use Client-CLI with OAuth 1.0a plugin, however I found a solution [here](https://github.com/WP-API/OAuth1/pull/32) on the official repository. In the file `lib/class-wp-json-authentication-oauth1.php` on line `524`, change the following code: ``` $base_request_uri = rawurlencode( get_home_url( null, parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), 'http' ) ); ``` to: ``` $home_url_path = parse_url(get_home_url (null,'','http'), PHP_URL_PATH ); $request_uri_path = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ); if (substr($request_uri_path, 0, strlen($home_url_path)) == $home_url_path) { $request_uri_path = substr($request_uri_path, strlen($home_url_path)); } $base_request_uri = rawurlencode( get_home_url( null, $request_uri_path, 'http' ) ); ``` This should solve the problem you are facing.
185,519
<p>I need to get the current plugin name using a define like this</p> <pre><code>define(PLUGIN_NAME, plugin_basename(dirname(__FILE__))); </code></pre> <p>Regrettably, that code doesn't work because the php file is nested inside a subdirectory (includes) of my plugin directory and it returns</p> <pre><code>my-plugin/includes </code></pre> <p>Is there any function from Wordpress API to accomplish this task? Thanks in advance.</p>
[ { "answer_id": 239497, "author": "Mark Howells-Mead", "author_id": 83412, "author_profile": "https://wordpress.stackexchange.com/users/83412", "pm_score": 3, "selected": false, "text": "<p>Within the plugin's main PHP file:</p>\n\n<pre><code>$plugin_data = get_plugin_data( __FILE__ );\n$plugin_name = $plugin_data['Name'];\n</code></pre>\n" }, { "answer_id": 299511, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>you can get plugin name in a subdirectory of your plugin by this snippet code:</p>\n\n<pre><code>$plugin = basename( plugin_dir_path( dirname( __FILE__ , 2 ) ) );\n</code></pre>\n\n<p>only you should write level of subdirectory relative to plugin folder in second parameter of dirname() function.</p>\n" }, { "answer_id": 393454, "author": "Kerkness", "author_id": 190304, "author_profile": "https://wordpress.stackexchange.com/users/190304", "pm_score": 2, "selected": false, "text": "<p>This will give you the plugin folder name regardless of where the file is located and not having to know anything about the directory structure of the plugin.</p>\n<pre><code>$plugin_folder_name = reset(explode('/', str_replace(WP_PLUGIN_DIR . '/', '', __DIR__)));\n</code></pre>\n<p>For a break down of what is happening</p>\n<pre><code>// Get the relative path to current file from plugin root\n$file_path_from_plugin_root = str_replace(WP_PLUGIN_DIR . '/', '', __DIR__);\n\n// Explode the path into an array\n$path_array = explode('/', $file_path_from_plugin_root);\n\n// Plugin folder is the first element\n$plugin_folder_name = reset($path_array);\n</code></pre>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185519", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70174/" ]
I need to get the current plugin name using a define like this ``` define(PLUGIN_NAME, plugin_basename(dirname(__FILE__))); ``` Regrettably, that code doesn't work because the php file is nested inside a subdirectory (includes) of my plugin directory and it returns ``` my-plugin/includes ``` Is there any function from Wordpress API to accomplish this task? Thanks in advance.
Within the plugin's main PHP file: ``` $plugin_data = get_plugin_data( __FILE__ ); $plugin_name = $plugin_data['Name']; ```
185,524
<p>I have a regular business website that I built on Wordpress - www.example.com</p> <p>I have a blog page in my website under - www.example.com/blog </p> <p>When viewing a blog post it looks like this: www.exmaple.com/[category]/[posts-name] </p> <p>How can I add "/blog" to this URL before the category? like this: www.exmaple.com/blog/[category]/[posts-name] </p> <p>This is my current .htaccess: </p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre>
[ { "answer_id": 185525, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": true, "text": "<p>You can not do that viw .htaccess because .htacces rules can not control how the permalinks are generated by WordPress. Instead, go to WordPress settings->permalink. Select custom structure and enter:</p>\n\n<pre><code>blog/%category%/%postname%\n</code></pre>\n" }, { "answer_id": 185526, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 0, "selected": false, "text": "<p>Go to Settings -> Permalink and type in Custom structure.</p>\n\n<pre><code>/blog/%postname%\n</code></pre>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185524", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75062/" ]
I have a regular business website that I built on Wordpress - www.example.com I have a blog page in my website under - www.example.com/blog When viewing a blog post it looks like this: www.exmaple.com/[category]/[posts-name] How can I add "/blog" to this URL before the category? like this: www.exmaple.com/blog/[category]/[posts-name] This is my current .htaccess: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ```
You can not do that viw .htaccess because .htacces rules can not control how the permalinks are generated by WordPress. Instead, go to WordPress settings->permalink. Select custom structure and enter: ``` blog/%category%/%postname% ```
185,527
<p>I have such a wp query args:</p> <pre><code>$args = array( 'post_type'=&gt; 'myposttype', 'posts_per_page' =&gt; 10, 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array('key' =&gt; 'routeFrom','value' =&gt; 'rome','compare' =&gt; 'LIKE'), array('key' =&gt; 'routeTo','value' =&gt; 'paris','compare' =&gt; 'LIKE'), ) ); </code></pre> <p>Each my post has custom field routeFrom and routeTo. In this example if routeFrom equal to Rome and routeTo equal to Paris wp query displaying those posts. </p> <p>The problem is that sticky posts appear no matter what meta query i'm using. </p> <p>I want to display particular sticky posts if they only match meta query.</p> <p>Real life example would be: I have a route search page where i would like to display sticky post on top of all posts, but only if it ALSO meets meta query (in this case particular route).</p> <p>I'm using sticky posts plugin "Sticky Custom Post Types", but posts are stored in the global ‘sticky_posts’ option field, just like regular posts.</p> <p>Any help?</p> <p><strong>Updated code:</strong></p> <pre><code>$stickyargs = array( 'post_type'=&gt; 'trips', 'posts_per_page' =&gt; -1, 'post__in' =&gt; get_option( 'sticky_posts' ), 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array('key' =&gt; 'routeFrom','value' =&gt; $_GET['from'],'compare' =&gt; 'LIKE'), array('key' =&gt; 'routeTo','value' =&gt; $_GET['to'],'compare' =&gt; 'LIKE'), ) ); $args = array( 'post_type'=&gt; 'trips', 'paged' =&gt; $paged, 'posts_per_page' =&gt; 10, 'post__not_in' =&gt; get_option( 'sticky_posts' ), 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array('key' =&gt; 'routeFrom','value' =&gt; $_GET['from'],'compare' =&gt; 'LIKE'), array('key' =&gt; 'routeTo','value' =&gt; $_GET['to'],'compare' =&gt; 'LIKE'), ) ); $search = new WP_Query($args); $searchsticky = new WP_Query($stickyargs); ?&gt; &lt;?php if ( $searchsticky-&gt;have_posts() ) : ?&gt; &lt;?php while ( $searchsticky-&gt;have_posts() ) : $searchsticky-&gt;the_post(); ?&gt; &lt;div class="search_item"&gt; &lt;?php the_content(); ?&gt;&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; Not found &lt;?php endif; wp_reset_query(); ?&gt; &lt;?php if ( $search-&gt;have_posts() ) : ?&gt; &lt;?php while ( $search-&gt;have_posts() ) : $search-&gt;the_post(); ?&gt; &lt;div class="search_item"&gt; &lt;?php the_content(); ?&gt;&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; Not found &lt;?php endif; wp_reset_query(); ?&gt; </code></pre>
[ { "answer_id": 185528, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 2, "selected": false, "text": "<p>You can ignore sticky posts by adding</p>\n\n<pre><code>'ignore_sticky_posts' =&gt; true,\n</code></pre>\n\n<p>to your query. You can also set <code>ignore_sticky_posts</code> to 1.</p>\n\n<p>Please note that a post is still delivered if it is sticky, but matches the other criterias.</p>\n" }, { "answer_id": 185570, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>Custom queries and sticky posts are quite a curve ball to work with. I don't know how your setup looks and what exactly is your user case, but your best solution here would be to run two queries here, the first one to get your sticky posts and the other one to display normal posts</p>\n\n<p>Your first query's arguments will look something like </p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'myposttype',\n 'posts_per_page' =&gt; -1,\n 'post__in' =&gt; get_option( 'sticky_posts' ),\n 'ignore_sticky_posts' =&gt; 1,\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array('key' =&gt; 'routeFrom','value' =&gt; 'rome','compare' =&gt; 'LIKE'),\n array('key' =&gt; 'routeTo','value' =&gt; 'paris','compare' =&gt; 'LIKE'),\n ) \n);\n</code></pre>\n\n<p>Your second query arguments you will need to exclude these stickies</p>\n\n<pre><code>$args = array(\n 'post_type'=&gt; 'myposttype',\n 'posts_per_page' =&gt; 10,\n 'post__not_in' =&gt; get_option( 'sticky_posts' ),\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array('key' =&gt; 'routeFrom','value' =&gt; 'rome','compare' =&gt; 'LIKE'),\n array('key' =&gt; 'routeTo','value' =&gt; 'paris','compare' =&gt; 'LIKE'),\n ) \n);\n</code></pre>\n\n<p>Just make sure that you reset both queries.</p>\n\n<p>As I said before, I do not know your exact setup and user case, but if this is suppose to be the main query, you should look at <code>pre_get_posts</code> to alter the main query accordingly. If so, look at <a href=\"https://wordpress.stackexchange.com/a/183620/31545\">this post</a> I have recently done to include sticky posts outside the home page. </p>\n\n<h2>EDIT</h2>\n\n<p>I totally forgot to add <code>ignore_sticky_posts</code> to the first set of query arguments. It should work now. I have updated the code accordingly</p>\n\n<p>Just one or two notes on your code</p>\n\n<ul>\n<li><p>You should use <code>wp_reset_postdata()</code> to reset your queries, not <code>wp_reset_query()</code>. The latter is used with <code>query_posts</code> which you should never use. Also, <code>wp_reset_postdata()</code> should be used between <code>endwhile</code> and <code>endif</code></p></li>\n<li><p>To exclude the sticky post query from paged pages, simply warp the code in a <code>if ( !is_paged() ) { YOUR STICKY POST CODE }</code> condition</p></li>\n</ul>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56604/" ]
I have such a wp query args: ``` $args = array( 'post_type'=> 'myposttype', 'posts_per_page' => 10, 'meta_query' => array( 'relation' => 'AND', array('key' => 'routeFrom','value' => 'rome','compare' => 'LIKE'), array('key' => 'routeTo','value' => 'paris','compare' => 'LIKE'), ) ); ``` Each my post has custom field routeFrom and routeTo. In this example if routeFrom equal to Rome and routeTo equal to Paris wp query displaying those posts. The problem is that sticky posts appear no matter what meta query i'm using. I want to display particular sticky posts if they only match meta query. Real life example would be: I have a route search page where i would like to display sticky post on top of all posts, but only if it ALSO meets meta query (in this case particular route). I'm using sticky posts plugin "Sticky Custom Post Types", but posts are stored in the global ‘sticky\_posts’ option field, just like regular posts. Any help? **Updated code:** ``` $stickyargs = array( 'post_type'=> 'trips', 'posts_per_page' => -1, 'post__in' => get_option( 'sticky_posts' ), 'meta_query' => array( 'relation' => 'AND', array('key' => 'routeFrom','value' => $_GET['from'],'compare' => 'LIKE'), array('key' => 'routeTo','value' => $_GET['to'],'compare' => 'LIKE'), ) ); $args = array( 'post_type'=> 'trips', 'paged' => $paged, 'posts_per_page' => 10, 'post__not_in' => get_option( 'sticky_posts' ), 'meta_query' => array( 'relation' => 'AND', array('key' => 'routeFrom','value' => $_GET['from'],'compare' => 'LIKE'), array('key' => 'routeTo','value' => $_GET['to'],'compare' => 'LIKE'), ) ); $search = new WP_Query($args); $searchsticky = new WP_Query($stickyargs); ?> <?php if ( $searchsticky->have_posts() ) : ?> <?php while ( $searchsticky->have_posts() ) : $searchsticky->the_post(); ?> <div class="search_item"> <?php the_content(); ?>> </div> <?php endwhile; ?> <?php else : ?> Not found <?php endif; wp_reset_query(); ?> <?php if ( $search->have_posts() ) : ?> <?php while ( $search->have_posts() ) : $search->the_post(); ?> <div class="search_item"> <?php the_content(); ?>> </div> <?php endwhile; ?> <?php else : ?> Not found <?php endif; wp_reset_query(); ?> ```
Custom queries and sticky posts are quite a curve ball to work with. I don't know how your setup looks and what exactly is your user case, but your best solution here would be to run two queries here, the first one to get your sticky posts and the other one to display normal posts Your first query's arguments will look something like ``` $args = array( 'post_type' => 'myposttype', 'posts_per_page' => -1, 'post__in' => get_option( 'sticky_posts' ), 'ignore_sticky_posts' => 1, 'meta_query' => array( 'relation' => 'AND', array('key' => 'routeFrom','value' => 'rome','compare' => 'LIKE'), array('key' => 'routeTo','value' => 'paris','compare' => 'LIKE'), ) ); ``` Your second query arguments you will need to exclude these stickies ``` $args = array( 'post_type'=> 'myposttype', 'posts_per_page' => 10, 'post__not_in' => get_option( 'sticky_posts' ), 'meta_query' => array( 'relation' => 'AND', array('key' => 'routeFrom','value' => 'rome','compare' => 'LIKE'), array('key' => 'routeTo','value' => 'paris','compare' => 'LIKE'), ) ); ``` Just make sure that you reset both queries. As I said before, I do not know your exact setup and user case, but if this is suppose to be the main query, you should look at `pre_get_posts` to alter the main query accordingly. If so, look at [this post](https://wordpress.stackexchange.com/a/183620/31545) I have recently done to include sticky posts outside the home page. EDIT ---- I totally forgot to add `ignore_sticky_posts` to the first set of query arguments. It should work now. I have updated the code accordingly Just one or two notes on your code * You should use `wp_reset_postdata()` to reset your queries, not `wp_reset_query()`. The latter is used with `query_posts` which you should never use. Also, `wp_reset_postdata()` should be used between `endwhile` and `endif` * To exclude the sticky post query from paged pages, simply warp the code in a `if ( !is_paged() ) { YOUR STICKY POST CODE }` condition
185,530
<p>I want to remove WordPress logo from login and register page. I think I have to make some changes in .css file for this. So I want to know in which css file do I have to make the changes?</p>
[ { "answer_id": 185531, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 2, "selected": false, "text": "<p>You can add a filter to <code>login_head</code>. As explained in the <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/login_head\" rel=\"nofollow\">Codex</a>, add this to your code:</p>\n\n<pre><code>function my_custom_login_logo() {\n echo '&lt;style type=\"text/css\"&gt;\n h1 a {background-image:url(http://example.com/your-logo.png) !important; margin:0 auto;}\n &lt;/style&gt;';\n}\nadd_filter( 'login_head', 'my_custom_login_logo' );\n</code></pre>\n" }, { "answer_id": 185532, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 1, "selected": false, "text": "<p>To remove the WordPress logo, paste the below code in functions.php of the theme directory.</p>\n\n<pre><code>function remove_logo() { ?&gt;\n&lt;style type=\"text/css\"&gt;\n .login h1 a { display: none; }\n&lt;/style&gt;\n&lt;?php }\n\nadd_action( 'login_enqueue_scripts', 'remove_logo' );\n</code></pre>\n" }, { "answer_id": 185540, "author": "Ismail", "author_id": 70833, "author_profile": "https://wordpress.stackexchange.com/users/70833", "pm_score": 0, "selected": false, "text": "<p>You don't need to go through the coding, use <a href=\"https://wordpress.org/plugins/custom-login/\" rel=\"nofollow\">Custom Login</a> plug-in to do that</p>\n" }, { "answer_id": 296970, "author": "Roman Káčerek", "author_id": 138742, "author_profile": "https://wordpress.stackexchange.com/users/138742", "pm_score": 1, "selected": false, "text": "<p>Go to your website Editor using > <strong>Appearance > Editor > function.php</strong> and add this before the last line \"<strong>?></strong>\":</p>\n\n<pre><code>/* Remove WP logo from login page */\n\nfunction custom_login_logo() {\n echo '&lt;style type =\"text/css\"&gt;.login h1 a { display:none!important; }&lt;/style&gt;';\n}\n\nadd_action('login_head', 'custom_login_logo');\n</code></pre>\n" }, { "answer_id": 350927, "author": "Ashin", "author_id": 163307, "author_profile": "https://wordpress.stackexchange.com/users/163307", "pm_score": 1, "selected": false, "text": "<p>You can replace the logo using built-in theme editor as explained\n<a href=\"https://www.geekinsta.com/how-to-change-wordpress-logo-in-the-login-page/\" rel=\"nofollow noreferrer\">in this post</a>.</p>\n\n<p>Step 1:</p>\n\n<p>Login to your WordPress site as admin and go to <strong>Media</strong> -> <strong>Add New</strong> to upload a new image and copy the image url.</p>\n\n<p>You can also upload your new logo to the theme’s images directory or you can create a new directory to upload the logo. This can be done with the help of web hosting control panel or FTP.</p>\n\n<p>Step 2:</p>\n\n<p>Go to the Admin <strong>Dashboard</strong> -> <strong>Appearance</strong> -> <strong>Theme Editor</strong>.</p>\n\n<p>Step 3:</p>\n\n<p>When the editor opens, find and select functions.php from the right side of the page and add the following code to the end of the page.</p>\n\n<pre><code>function my_custom_logo() { ?&gt;\n &lt;style type=\"text/css\"&gt;\n #login h1 a, .login h1 a {\n background-image: url(&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/images/logo.png);\n height:100px;\n width:100px;\n background-size: 100px 100px;\n background-repeat: no-repeat;\n margin-bottom: 10px;\n }\n &lt;/style&gt;\n &lt;?php } \nadd_action( 'login_enqueue_scripts', 'my_custom_logo' );\n</code></pre>\n\n<p>Replace <em>logo.png</em> with the name of the file you have uploaded. If you have uploaded the new logo with WordPress, modify the background-image property as shown below.</p>\n\n<p><strong>background-image: url(url copied in step 1);</strong></p>\n" }, { "answer_id": 387035, "author": "revive", "author_id": 8645, "author_profile": "https://wordpress.stackexchange.com/users/8645", "pm_score": 0, "selected": false, "text": "<p>It's best to run this after login_enqueue_scripts as mentioned by @ashin <a href=\"https://wordpress.stackexchange.com/questions/185530/how-to-remove-the-wordpress-logo-from-login-and-register-page/350927#350927\">above</a></p>\n<p>I'll post this since it relates to changing the logo.</p>\n<p>To change the URL from wordpress.org to your own (along with the links title attr), use this:</p>\n<pre><code> function my_login_logo_url() {\n return home_url();\n }\n add_filter( 'login_headerurl', 'my_login_logo_url' );\n\n function my_login_logo_url_title() {\n return 'Your Site Name and Info';\n }\n add_filter( 'login_headertitle', 'my_login_logo_url_title' );\n</code></pre>\n<p>If you want to get crazy with styling, here is the css used to edit the entire login page:</p>\n<pre><code>body.login {}\nbody.login div#login {}\nbody.login div#login h1 {}\nbody.login div#login h1 a {}\nbody.login div#login form#loginform {}\nbody.login div#login form#loginform p {}\nbody.login div#login form#loginform p label {}\nbody.login div#login form#loginform input {}\nbody.login div#login form#loginform input#user_login {}\nbody.login div#login form#loginform input#user_pass {}\nbody.login div#login form#loginform p.forgetmenot {}\nbody.login div#login form#loginform p.forgetmenot input#rememberme {}\nbody.login div#login form#loginform p.submit {}\nbody.login div#login form#loginform p.submit input#wp-submit {}\nbody.login div#login p#nav {}\nbody.login div#login p#nav a {}\nbody.login div#login p#backtoblog {}\nbody.login div#login p#backtoblog a {}\n</code></pre>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185530", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71258/" ]
I want to remove WordPress logo from login and register page. I think I have to make some changes in .css file for this. So I want to know in which css file do I have to make the changes?
You can add a filter to `login_head`. As explained in the [Codex](http://codex.wordpress.org/Plugin_API/Filter_Reference/login_head), add this to your code: ``` function my_custom_login_logo() { echo '<style type="text/css"> h1 a {background-image:url(http://example.com/your-logo.png) !important; margin:0 auto;} </style>'; } add_filter( 'login_head', 'my_custom_login_logo' ); ```
185,545
<p>I am using this to localize strings in my theme </p> <pre><code>__('Background image', 'themename'); </code></pre> <p>there are plenty of strings that are localized but to make sure that the theme lang files and localization strings can be quickly changed, I would like to use something like this </p> <pre><code>$theme_name = 'themename';// this would be global var or var from a theme class __('Background image', $theme_name); // or $myClass-&gt;themename </code></pre> <p>and than use that variable everywhere it is needed. This way the owner of the theme can quickly change theme name and does not have to walk trough all locaizations. </p> <p>Do you see a problem with this ? </p>
[ { "answer_id": 185547, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>Yes this is problematic as <a href=\"https://developer.wordpress.org/themes/functionality/localization/#wordpress-i18n-tools\" rel=\"nofollow\">i18n tools</a> that parse your theme to generate a *.pot file for translation can't understand this as they do not run PHP code but just search your code as text.</p>\n\n<p>Here is <a href=\"http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/\" rel=\"nofollow\">a blogpost detailing on why this may cause trouble</a>:</p>\n\n<blockquote>\n <p>Bottom line: <em>Inside all translation functions, no PHP variables are allowed in the strings, for any reason, ever. Plain single-quoted strings only.</em></p>\n</blockquote>\n\n<p>But nevertheless the fact that you think about <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a> is great! Actually as I've already talked about the <a href=\"https://developer.wordpress.org/themes/functionality/internationalization/#add-text-domain-to-strings\" rel=\"nofollow\">i18n tools</a> they can help you with automatically adding a textdomain. There even is a <a href=\"https://github.com/cedaro/grunt-wp-i18n\" rel=\"nofollow\">Grunt plugin</a> to automate this plus the option to replace/rename textdomains which would solve your actual issue. Just comment if you need more help on that.</p>\n" }, { "answer_id": 185548, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 2, "selected": false, "text": "<p>A technique like this has one really big advantage, and one really big disadvantage.</p>\n\n<h2>Advantage</h2>\n\n<p>The good thing is, like you mentioned, that the owner can dynamically change the theme name, and therefor the source where the translations are pulled from. If you have a special use case, for example different versions of the translations, this could be really useful.</p>\n\n<p>I have one project where I use the first string as a variable. With this method I can dynamically translate strings that are returned from different functions, in my case from an API. In detail, I receive errors like <code>AdError.INVALID_INPUT</code>, and I can output an error description for each language.</p>\n\n<h2>Problem</h2>\n\n<p>The big disadvantage is however, there is no way for you to find all the strings in your theme/plugin. A lot of translation programs (or plugins like WPML) loop throug your files and search for <code>__()</code> and <code>_e()</code> functions (as well as all the other translation functions), and parse the strings to create the references for the translation.</p>\n\n<p>If you use variables in your calls, either the string for the textdomain or the string for the translationstring can not be found, as they are dynamic, and not hardcoded into the file.</p>\n\n<p>If you choose to take this path, you need an extra file somewhere, where all your translations are defined:</p>\n\n<pre><code>__( 'Your new String', 'yourtheme' );\n__( 'Your new String2', 'yourtheme' );\n</code></pre>\n\n<p>In case you use <code>.mo</code>-files, it gets a bit easier, as you just have to change the file, but as soon as you add another string, all the translation files must be updated as well.</p>\n\n<h2>Conclusion</h2>\n\n<p>Generally, I would discourage you from using this approach for textdomains. It would be a lot easier to just Search/Replace throughout your themefiles (most editors can do that in a few clicks).</p>\n\n<p>If you want translations for strings that you do not know or are dynamically generated, it can be a great simplification. Just be sure to add a filter to your <code>gettext</code> functions, to find out if the required translations are already recognized in your translation system/mo/po files.</p>\n\n<p>Something like that should do the trick (untested):</p>\n\n<pre><code>add_filter( 'gettext', 'f711_check_for_translations', 10, 3 );\n\nfunction f711_check_for_translations( $translated, $text, $domain ) {\n if ( $text == $translated ) {\n AddNewStringToTranslationStrings( $text ); // Function to add the string to your translation strings, however you are going to do that.\n }\n return $translated;\n}\n</code></pre>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67176/" ]
I am using this to localize strings in my theme ``` __('Background image', 'themename'); ``` there are plenty of strings that are localized but to make sure that the theme lang files and localization strings can be quickly changed, I would like to use something like this ``` $theme_name = 'themename';// this would be global var or var from a theme class __('Background image', $theme_name); // or $myClass->themename ``` and than use that variable everywhere it is needed. This way the owner of the theme can quickly change theme name and does not have to walk trough all locaizations. Do you see a problem with this ?
Yes this is problematic as [i18n tools](https://developer.wordpress.org/themes/functionality/localization/#wordpress-i18n-tools) that parse your theme to generate a \*.pot file for translation can't understand this as they do not run PHP code but just search your code as text. Here is [a blogpost detailing on why this may cause trouble](http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/): > > Bottom line: *Inside all translation functions, no PHP variables are allowed in the strings, for any reason, ever. Plain single-quoted strings only.* > > > But nevertheless the fact that you think about [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) is great! Actually as I've already talked about the [i18n tools](https://developer.wordpress.org/themes/functionality/internationalization/#add-text-domain-to-strings) they can help you with automatically adding a textdomain. There even is a [Grunt plugin](https://github.com/cedaro/grunt-wp-i18n) to automate this plus the option to replace/rename textdomains which would solve your actual issue. Just comment if you need more help on that.
185,558
<p>I was wondering if someone could help me out. I would like to create a dropdown search filter for my wordpress site. I would like the drop downs to be populated by meta_boxes values which i have for a custom post type. I know that <code>&lt;?php echo get_post_meta($post-&gt;ID, 'meta_field', true); ?&gt;</code> is the way to get them but i would like to create a variable and echo it out as a list for a drop down. </p> <pre><code>&lt;select&gt; $variable = get_post_meta($post-&gt;ID, 'meta_field', true); foreach( $variable as $key=&gt;$val) { echo '&lt;option&gt;'; echo '$variable'; echo '&lt;/option&gt;'; } &lt;/select&gt; </code></pre> <p>but it does not seem to work, does anyone know why? I would appreciate the help. </p>
[ { "answer_id": 185565, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>First, you have a very basic PHP mistake: <a href=\"https://php.net/manual/en/language.types.string.php#language.types.string.syntax.single\" rel=\"nofollow noreferrer\">single quotes mean \"string literal\"</a>. Variables won't be processed. You are literally putting \"$variable\" into the generated code. </p>\n\n<p>Second, look at the third parameter of <code>get_post_meta()</code></p>\n\n<blockquote>\n <p>$single (boolean) (optional)<br>\n If set to true then the function will\n return a single result, as a string. If false, or not set, then the\n function returns an array of the custom fields. This may not be\n intuitive in the context of serialized arrays. If you fetch a\n serialized array with this method you want $single to be true to\n actually get an unserialized array back. If you pass in false, or\n leave it out, you will have an array of one, and the value at index 0\n will be the serialized string.<br>\n Default: false</p>\n</blockquote>\n\n<p>You are asking for a single variable as a string, and are then trying to iterate over it as if it were an array. I am surprised you aren't getting errors. (see: <a href=\"https://wordpress.stackexchange.com/a/95983/21376\">https://wordpress.stackexchange.com/a/95983/21376</a>)</p>\n\n<p>It looks to me like you need to drop that third parameter or set it to <code>false</code> (the default), which will return an <code>array</code> that you can iterate over.</p>\n" }, { "answer_id": 185573, "author": "steamfunk", "author_id": 67512, "author_profile": "https://wordpress.stackexchange.com/users/67512", "pm_score": 1, "selected": false, "text": "<p>This outputs what I need incase anyone is wondering how they would create a drop down from you metakey values. </p>\n\n<pre><code>&lt;select&gt;\n &lt;?php while (have_posts()) : the_post();?&gt;\n\n &lt;option&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'Meta_key', true); ?&gt;&lt;/option&gt;\n\n &lt;?php\n endwhile;\n ?&gt;\n &lt;/select&gt;\n</code></pre>\n" }, { "answer_id": 241342, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>Please try with this one-</p>\n\n<pre><code>$variable = get_post_meta( $post-&gt;ID, 'meta_field', true ); // assuming this returns an array\n\n$dropdown = '';\n$dropdown .= '&lt;select&gt;';\n\n if( ! count( $variable ) ){\n $dropdown .= '&lt;option&gt;Not found!&lt;/option&gt;';\n }\n else{\n foreach( $variable as $option ) {\n $dropdown .= '&lt;option&gt;' . $option . '&lt;/option&gt;';\n }\n }\n\n$dropdown .= '&lt;/select&gt;';\n\necho $dropdown;\n</code></pre>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67512/" ]
I was wondering if someone could help me out. I would like to create a dropdown search filter for my wordpress site. I would like the drop downs to be populated by meta\_boxes values which i have for a custom post type. I know that `<?php echo get_post_meta($post->ID, 'meta_field', true); ?>` is the way to get them but i would like to create a variable and echo it out as a list for a drop down. ``` <select> $variable = get_post_meta($post->ID, 'meta_field', true); foreach( $variable as $key=>$val) { echo '<option>'; echo '$variable'; echo '</option>'; } </select> ``` but it does not seem to work, does anyone know why? I would appreciate the help.
First, you have a very basic PHP mistake: [single quotes mean "string literal"](https://php.net/manual/en/language.types.string.php#language.types.string.syntax.single). Variables won't be processed. You are literally putting "$variable" into the generated code. Second, look at the third parameter of `get_post_meta()` > > $single (boolean) (optional) > > If set to true then the function will > return a single result, as a string. If false, or not set, then the > function returns an array of the custom fields. This may not be > intuitive in the context of serialized arrays. If you fetch a > serialized array with this method you want $single to be true to > actually get an unserialized array back. If you pass in false, or > leave it out, you will have an array of one, and the value at index 0 > will be the serialized string. > > Default: false > > > You are asking for a single variable as a string, and are then trying to iterate over it as if it were an array. I am surprised you aren't getting errors. (see: <https://wordpress.stackexchange.com/a/95983/21376>) It looks to me like you need to drop that third parameter or set it to `false` (the default), which will return an `array` that you can iterate over.
185,577
<p>So WP 4.2 introduced emojis (smileys) that basically adds JS and other junk all over your pages. Something some people may find shocking. How does one completely erase all instances of this?</p>
[ { "answer_id": 185578, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 9, "selected": true, "text": "<p>We will hook into <code>init</code> and remove actions as followed:</p>\n\n<pre><code>function disable_wp_emojicons() {\n\n // all actions related to emojis\n remove_action( 'admin_print_styles', 'print_emoji_styles' );\n remove_action( 'wp_head', 'print_emoji_detection_script', 7 );\n remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );\n remove_action( 'wp_print_styles', 'print_emoji_styles' );\n remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );\n remove_filter( 'the_content_feed', 'wp_staticize_emoji' );\n remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );\n\n // filter to remove TinyMCE emojis\n add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' );\n}\nadd_action( 'init', 'disable_wp_emojicons' );\n</code></pre>\n\n<p>We will need the following filter function to disable TinyMCE emojicons:</p>\n\n<pre><code>function disable_emojicons_tinymce( $plugins ) {\n if ( is_array( $plugins ) ) {\n return array_diff( $plugins, array( 'wpemoji' ) );\n } else {\n return array();\n }\n}\n</code></pre>\n\n<p>Now we breathe and pretend this feature was never added to core... particularly while tons of <em>resolved</em> bugs are <a href=\"https://core.trac.wordpress.org/\">yet</a> to be implemented.</p>\n\n<p>This is available as a plugin, <a href=\"https://wordpress.org/plugins/disable-emojis/\">Disable Emojis</a>. </p>\n\n<p>Alternatively, you can replace the smilies with the original versions from previous versions of WordPress using <a href=\"https://wordpress.org/plugins/classic-smilies/\">Classic Smilies</a>.</p>\n\n<h1>Update</h1>\n\n<p>We can also remove the DNS prefetch by returning false on filter <code>emoji_svg_url</code> (thanks @yobddigi):</p>\n\n<pre><code>add_filter( 'emoji_svg_url', '__return_false' );\n</code></pre>\n" }, { "answer_id": 185733, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 5, "selected": false, "text": "<p>Better solution if you want to disable this: use a plugin.</p>\n\n<p>Same code as from Christine's comments:\n<a href=\"https://wordpress.org/plugins/disable-emojis/\">https://wordpress.org/plugins/disable-emojis/</a></p>\n\n<p>Same code that also fixes the smilies to be the older ones:\n<a href=\"https://wordpress.org/plugins/classic-smilies/\">https://wordpress.org/plugins/classic-smilies/</a></p>\n\n<p>Source: Me, since I wrote that code in the first place.\n<a href=\"https://plugins.trac.wordpress.org/changeset/1142480/classic-smilies\">https://plugins.trac.wordpress.org/changeset/1142480/classic-smilies</a></p>\n" }, { "answer_id": 192534, "author": "Exclutips", "author_id": 74748, "author_profile": "https://wordpress.stackexchange.com/users/74748", "pm_score": 4, "selected": false, "text": "<p>This is the simple way to remove emoji. Add bellow code to your <code>function.php</code></p>\n\n<pre><code>remove_action( 'wp_head', 'print_emoji_detection_script', 7 );\nremove_action( 'wp_print_styles', 'print_emoji_styles' ); \n</code></pre>\n" }, { "answer_id": 241897, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": -1, "selected": false, "text": "<p>Good news, I added a feature request:</p>\n\n<p><strong><em>Introduce a new option to WordPress WP_EMOICONS</em></strong>\nin here <a href=\"https://core.trac.wordpress.org/ticket/38252\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/38252</a></p>\n\n<p>and apparently this has been marked as duplicate\n<a href=\"https://core.trac.wordpress.org/ticket/32102\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/32102</a>\nso we may expect something like</p>\n\n<pre><code>define( 'WP_EMOICONS', false );\n</code></pre>\n\n<p>in the future WordPress releases.</p>\n" }, { "answer_id": 246266, "author": "Antony Agnel", "author_id": 107024, "author_profile": "https://wordpress.stackexchange.com/users/107024", "pm_score": -1, "selected": false, "text": "<p>Since WordPress emoji are served from s.w.org and they are not compressed, this impacts the SVG loading time depending on how many emoji you are using, and can even throw warnings on Google’s PageSpeed Insights tool.</p>\n\n<p>To fix this issue, you can serve the emoji directly from your WordPress site itself and not by making external calls through js. </p>\n\n<p>This can be achieved by installing the plugin <a href=\"https://wordpress.org/plugins/compressed-emoji/\" rel=\"nofollow noreferrer\">Compressed Emoji</a> which is available for free in the WordPress.org plugin repository.</p>\n\n<p>When the plugin is activated, the compression offers savings in the range of 3kb ~ 1.3kb (roughly %60) per emoji.</p>\n\n<p>Source: <a href=\"https://wptavern.com/new-wordpress-plugin-serves-pre-compressed-emoji\" rel=\"nofollow noreferrer\">WPTavern</a></p>\n" }, { "answer_id": 269983, "author": "Christallkeks", "author_id": 114734, "author_profile": "https://wordpress.stackexchange.com/users/114734", "pm_score": 2, "selected": false, "text": "<p>If you want to prevent Wordpress from automatically converting your old school ASCII smilies to Unicode emojis (like <code>;-)</code> to <code></code>) in your posts altogether, you might want to <code>remove_filter('the_content', 'convert_smilies')</code></p>\n\n<p>(Not 100% sure this is what the question's about, but this solved my problem and I hope it might be handy for someone.)</p>\n" }, { "answer_id": 272831, "author": "johnhgaspay", "author_id": 60964, "author_profile": "https://wordpress.stackexchange.com/users/60964", "pm_score": 0, "selected": false, "text": "<p>I've tried some codes above but the only codes works on my end is this one.</p>\n\n<p>Don't forget to back-up your functions.php before implementing these codes.</p>\n\n<pre><code>// REMOVE WP EMOJI\nremove_action('wp_head', 'print_emoji_detection_script', 7);\nremove_action('wp_print_styles', 'print_emoji_styles');\n\nremove_action( 'admin_print_scripts', 'print_emoji_detection_script' );\nremove_action( 'admin_print_styles', 'print_emoji_styles' );\n</code></pre>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185577", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24875/" ]
So WP 4.2 introduced emojis (smileys) that basically adds JS and other junk all over your pages. Something some people may find shocking. How does one completely erase all instances of this?
We will hook into `init` and remove actions as followed: ``` function disable_wp_emojicons() { // all actions related to emojis remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); // filter to remove TinyMCE emojis add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' ); } add_action( 'init', 'disable_wp_emojicons' ); ``` We will need the following filter function to disable TinyMCE emojicons: ``` function disable_emojicons_tinymce( $plugins ) { if ( is_array( $plugins ) ) { return array_diff( $plugins, array( 'wpemoji' ) ); } else { return array(); } } ``` Now we breathe and pretend this feature was never added to core... particularly while tons of *resolved* bugs are [yet](https://core.trac.wordpress.org/) to be implemented. This is available as a plugin, [Disable Emojis](https://wordpress.org/plugins/disable-emojis/). Alternatively, you can replace the smilies with the original versions from previous versions of WordPress using [Classic Smilies](https://wordpress.org/plugins/classic-smilies/). Update ====== We can also remove the DNS prefetch by returning false on filter `emoji_svg_url` (thanks @yobddigi): ``` add_filter( 'emoji_svg_url', '__return_false' ); ```
185,579
<p>I have a file in my theme's JS folder named cycle2.js.</p> <ol> <li><p>How do I include the Jquery from 'wordpress→includes' into my theme?</p></li> <li><p>How do I load this custom JavaScript file 'cycle2.js' into my theme?</p> <p>I have:</p> <pre><code>function watercolor_js_scripts(){ if (!is_admin()) { wp_register_script('cycle2', get_template_directory_uri() . '/js/cycle2.js', 'jquery', TRUE); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'cycle2' ); } add_action('init', 'watercolor_js_scripts'); } </code></pre></li> </ol> <p>I can't understand any of the many explanations of this. Can some please just provide a copy/paste solution to throw into functions.php that will include the basic Jquery library included with WordPress &amp; the cycle2.js file in my theme's js folder?</p>
[ { "answer_id": 185582, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>Your snippet seems mostly ok, except that dependency is a list and should be <code>array('jquery')</code>. Also <code>wp_enqueue_scripts</code> should be use as more appropriate.</p>\n\n<p>You can check out Codex documentation for a complete example, see <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script#Example_of_Automatic_Dependency_Loading\" rel=\"nofollow\">Example of Automatic Dependency Loading</a>.</p>\n" }, { "answer_id": 185596, "author": "coupon walrus", "author_id": 70369, "author_profile": "https://wordpress.stackexchange.com/users/70369", "pm_score": 0, "selected": false, "text": "<p>SOLVED: can't figure out the best way to update my question, sorry! Thank you Rarst the link you provided helped me figure this out:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'watercolor_js_scripts');\n\nfunction watercolor_js_scripts(){\n\n if (!is_admin()) {\n\n wp_register_script('cycle2', get_template_directory_uri() . '/js/cycle2.js', array('jquery'), TRUE);\n\n wp_enqueue_script( 'cycle2', get_stylesheet_directory_uri() . '/js/cycle2.js', array( 'jquery', 'my-script' ) );\n}\n</code></pre>\n\n<p>}</p>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70369/" ]
I have a file in my theme's JS folder named cycle2.js. 1. How do I include the Jquery from 'wordpress→includes' into my theme? 2. How do I load this custom JavaScript file 'cycle2.js' into my theme? I have: ``` function watercolor_js_scripts(){ if (!is_admin()) { wp_register_script('cycle2', get_template_directory_uri() . '/js/cycle2.js', 'jquery', TRUE); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'cycle2' ); } add_action('init', 'watercolor_js_scripts'); } ``` I can't understand any of the many explanations of this. Can some please just provide a copy/paste solution to throw into functions.php that will include the basic Jquery library included with WordPress & the cycle2.js file in my theme's js folder?
Your snippet seems mostly ok, except that dependency is a list and should be `array('jquery')`. Also `wp_enqueue_scripts` should be use as more appropriate. You can check out Codex documentation for a complete example, see [Example of Automatic Dependency Loading](https://codex.wordpress.org/Function_Reference/wp_register_script#Example_of_Automatic_Dependency_Loading).
185,587
<p>I've found that <code>wp_update_post()</code> escapes all ampersands provided in the post's <code>post_content</code>. I'm trying to update a post without converting ampersands to <code>&amp;amp;</code>. (I need to add plaintext URLs (<em>not</em> links) to the <code>post_content</code> field of posts). So, I'm trying to find a way to use <code>wp_update_post()</code> with escaping disabled, or perhaps another function in its place.</p> <p>One approach would be to exercise <code>$wpdb</code> directly, but I'd rather not as that seems like a last resort to me.</p> <p>One observation I've made is that if you use the "Text" view to edit a post via the admin interface, you can successfully add ampersands to the post_content without them being converted to <code>&amp;amp;</code>. However, it's taking me some time to trace through the code to find out how Wordpress accomplishes this. Does anyone know how WP accomplishes this?</p> <p>Ultimately, my question is, <strong>what's the best way to update a post with ampersand escaping "disabled"?</strong></p>
[ { "answer_id": 185593, "author": "rinogo", "author_id": 10388, "author_profile": "https://wordpress.stackexchange.com/users/10388", "pm_score": 1, "selected": false, "text": "<p>I'm not sure how WP's admin interface handles this (e.g. the scenario I referenced in the question), but I found a way to accomplish this:</p>\n\n<pre><code>//Disable KSES\nkses_remove_filters(); \n\n$update_rval = wp_update_post($updates);\n\n//Reenable KSES\nkses_init_filters();\n</code></pre>\n\n<p>Note that \"kses\" functions are part of Wordpress' defense against evil code. So, use this approach at your own risk. KSES does a <em>lot</em> more than just escape ampersands. If <code>$updates</code> contains trusted data (as in my case), you're probably safe using this approach.</p>\n\n<hr>\n\n<p>Update: I ran into another scenario in which Wordpress was happily running my JS but STILL escaping ampersands... I managed to get around this issue by substituting <code>String.fromCharCode(38)</code> in for every <code>&amp;</code> character I needed in the URL.</p>\n" }, { "answer_id": 299729, "author": "Bassel Banbouk", "author_id": 141064, "author_profile": "https://wordpress.stackexchange.com/users/141064", "pm_score": 2, "selected": false, "text": "<p>That is correct, the updating in the Admin section does not change the <code>&amp;</code> to <code>&amp;amp;</code> while the wp_update_post() function (which can be found under <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/post.php\" rel=\"nofollow noreferrer\">/wp-includes/post.php</a> on line 3772) does but only when the user does not have the capability <strong>unfiltered_html</strong>, let me explain how I found this out, and what I recommend.</p>\n\n<p>I did some tracing into this and found out that wp_update_post() calls wp_insert_post() internally as shown on line 3820</p>\n\n<pre><code>return wp_insert_post( $postarr, $wp_error );\n</code></pre>\n\n<p>wp_insert_post() calls sanitize_post() on line 3227</p>\n\n<pre><code>$postarr = sanitize_post( $postarr, 'db' );\n</code></pre>\n\n<p>Then on line 2176, this filter changes the <code>&amp;</code> to <code>&amp;amp;</code></p>\n\n<pre><code>$value = apply_filters( \"{$field_no_prefix}_save_pre\", $value );\n</code></pre>\n\n<p>In particular there is a filter called <code>content_save_pre</code> or in my case <code>title_save_pre</code> since I am facing the same issue with the title.</p>\n\n<p>Now, onto the Admin page which uses <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/post.php\" rel=\"nofollow noreferrer\">/wp-admin/post.php</a> </p>\n\n<p>You can see the actual save is on line 205</p>\n\n<pre><code>$post_id = edit_post();\n</code></pre>\n\n<p>And <code>edit_post()</code> function can be found under <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/post.php\" rel=\"nofollow noreferrer\">/wp-admin/includes/post.php</a> on line 208</p>\n\n<pre><code>function edit_post( $post_data = null ) {\n</code></pre>\n\n<p>The actual update is being done on line 382</p>\n\n<pre><code>$success = wp_update_post( $post_data );\n</code></pre>\n\n<p>Which shows that Wordpress uses the same wp_update_post() function internally.</p>\n\n<p>Turns out that there is a filter named 'wp_filter_kses' which is not being used by Wordpress Admin that is making all the difference. Although you can remove it by using:</p>\n\n<pre><code>remove_filter('content_save_pre', 'wp_filter_kses');\n</code></pre>\n\n<p>or in my case</p>\n\n<pre><code>remove_filter('title_save_pre', 'wp_filter_kses');\n</code></pre>\n\n<p>Or as @rinogo mentioned, you can use kses_remove_filters() to remove all kses filters.</p>\n\n<p>However, these filters are set by <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/kses.php\" rel=\"nofollow noreferrer\">/wp-includes/kses.php</a> on line 1934 after it checks if the user has the capability of \"unfiltered_html\"</p>\n\n<pre><code> if ( ! current_user_can( 'unfiltered_html' ) ) {\n kses_init_filters();\n }\n</code></pre>\n\n<p>If <code>kses_init_filters()</code> gets called, then the user who is trying to update the post is not trusted enough and does not have the proper capability.</p>\n\n<p>I would recommend that authentication gets handled properly rather than removing the filters.</p>\n" }, { "answer_id": 349524, "author": "ggedde", "author_id": 166772, "author_profile": "https://wordpress.stackexchange.com/users/166772", "pm_score": 0, "selected": false, "text": "<p>Thanks @Basil,\nYour answer helped me, but instead of altering filters all I needed to do was add the capability \"unfiltered_html\" to the User Roles that were having this issue.</p>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185587", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10388/" ]
I've found that `wp_update_post()` escapes all ampersands provided in the post's `post_content`. I'm trying to update a post without converting ampersands to `&amp;`. (I need to add plaintext URLs (*not* links) to the `post_content` field of posts). So, I'm trying to find a way to use `wp_update_post()` with escaping disabled, or perhaps another function in its place. One approach would be to exercise `$wpdb` directly, but I'd rather not as that seems like a last resort to me. One observation I've made is that if you use the "Text" view to edit a post via the admin interface, you can successfully add ampersands to the post\_content without them being converted to `&amp;`. However, it's taking me some time to trace through the code to find out how Wordpress accomplishes this. Does anyone know how WP accomplishes this? Ultimately, my question is, **what's the best way to update a post with ampersand escaping "disabled"?**
That is correct, the updating in the Admin section does not change the `&` to `&amp;` while the wp\_update\_post() function (which can be found under [/wp-includes/post.php](https://github.com/WordPress/WordPress/blob/master/wp-includes/post.php) on line 3772) does but only when the user does not have the capability **unfiltered\_html**, let me explain how I found this out, and what I recommend. I did some tracing into this and found out that wp\_update\_post() calls wp\_insert\_post() internally as shown on line 3820 ``` return wp_insert_post( $postarr, $wp_error ); ``` wp\_insert\_post() calls sanitize\_post() on line 3227 ``` $postarr = sanitize_post( $postarr, 'db' ); ``` Then on line 2176, this filter changes the `&` to `&amp;` ``` $value = apply_filters( "{$field_no_prefix}_save_pre", $value ); ``` In particular there is a filter called `content_save_pre` or in my case `title_save_pre` since I am facing the same issue with the title. Now, onto the Admin page which uses [/wp-admin/post.php](https://github.com/WordPress/WordPress/blob/master/wp-admin/post.php) You can see the actual save is on line 205 ``` $post_id = edit_post(); ``` And `edit_post()` function can be found under [/wp-admin/includes/post.php](https://github.com/WordPress/WordPress/blob/master/wp-admin/includes/post.php) on line 208 ``` function edit_post( $post_data = null ) { ``` The actual update is being done on line 382 ``` $success = wp_update_post( $post_data ); ``` Which shows that Wordpress uses the same wp\_update\_post() function internally. Turns out that there is a filter named 'wp\_filter\_kses' which is not being used by Wordpress Admin that is making all the difference. Although you can remove it by using: ``` remove_filter('content_save_pre', 'wp_filter_kses'); ``` or in my case ``` remove_filter('title_save_pre', 'wp_filter_kses'); ``` Or as @rinogo mentioned, you can use kses\_remove\_filters() to remove all kses filters. However, these filters are set by [/wp-includes/kses.php](https://github.com/WordPress/WordPress/blob/master/wp-includes/kses.php) on line 1934 after it checks if the user has the capability of "unfiltered\_html" ``` if ( ! current_user_can( 'unfiltered_html' ) ) { kses_init_filters(); } ``` If `kses_init_filters()` gets called, then the user who is trying to update the post is not trusted enough and does not have the proper capability. I would recommend that authentication gets handled properly rather than removing the filters.
185,600
<p>I have been using the same pagination query for the majority of the websites i have created. This time it is not working for some reason I have used the pagination trouble shooting links <a href="https://codex.wordpress.org/Pagination" rel="nofollow">Here</a> but nothing seems to be working. I have attached my code below. </p> <p>This time i am querying the post in a table so i think that must have something to do with it but i have queried it without a table and is still not working. Please see my code below. </p> <p>New query </p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'custom_post_type', 'posts_per_page' =&gt; 5, 'paged' =&gt; ( get_query_var('paged') ? get_query_var('paged') : 1), ); query_posts($args); ?&gt; </code></pre> <p>The table with my table data from my custom meta fields. </p> <pre><code>&lt;table&gt; &lt;thead &gt; &lt;tr&gt; &lt;th&gt;header&lt;/th&gt; &lt;th&gt;header&lt;/th&gt; &lt;th&gt;header&lt;/th&gt; &lt;th&gt;header&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php while (have_posts()) : the_post();?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endwhile; ?&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>My pagination links</p> <pre><code>&lt;?php global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' =&gt; '?paged=%#%', 'prev_text' =&gt; __(' Previous'), 'next_text' =&gt; __('Next '), 'current' =&gt; max( 1, get_query_var('paged') ), 'total' =&gt; $wp_query-&gt;max_num_pages ) ); ?&gt; </code></pre> <p>When I say its not working i mean that the pagination links are displayed the appropriate number of pages. but when i press on page two it isnt changing pages. the permalinks are right its says <code>domain/page/2</code> but the page is the same as page one. This is on a template page i created for <code>home-page.php</code> I appreciate the suggestions.</p>
[ { "answer_id": 185706, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As I already stated in comments, you should never use <code>query_posts</code>, only use <code>query_posts</code> if you are intended to break your page functionalities. Add <code>query_posts</code> to the very top of your <strong>EVIL LIST</strong>.</p>\n\n<p><code>query_posts</code> breaks the main query object, the very object that your pagination function relies on. Your pagination function relies on the <code>$max_num_pages</code> property from the main query. This is just <strong>one</strong> of the many things that <code>query_posts</code> break. </p>\n\n<p>To solve your issue, make use of <code>WP_Query</code> as it seems that you are using a custom page template here. Just one note here, if <code>home-page.php</code> is a static front page, which I suspect from the template name, then </p>\n\n<pre><code>'paged' =&gt; ( get_query_var('paged') ? get_query_var('paged') : 1),\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>'paged' =&gt; ( get_query_var('page') ? get_query_var('page') : 1),\n</code></pre>\n\n<p>as static front pages uses <code>page</code> and not <code>paged</code></p>\n\n<p>You can try something like this: (<em>Very important, this is untested and copied and pasted from OP, and <strong>always</strong> remember to reset postdata once you are done with your custom query</em>)</p>\n\n<pre><code>&lt;?php\n$args = array(\n 'post_type' =&gt; 'custom_post_type',\n 'posts_per_page' =&gt; 5,\n 'paged' =&gt; ( get_query_var('paged') ? get_query_var('paged') : 1),\n);\n$query = new WP_Query($args);\n?&gt;\n&lt;table&gt;\n &lt;thead &gt;\n &lt;tr&gt;\n\n &lt;th&gt;header&lt;/th&gt;\n &lt;th&gt;header&lt;/th&gt;\n &lt;th&gt;header&lt;/th&gt;\n &lt;th&gt;header&lt;/th&gt;\n\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n\n &lt;?php while ($query-&gt;have_posts()) : $query-&gt;the_post();?&gt;\n &lt;tr&gt;\n\n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; \n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; \n\n &lt;/tr&gt;\n &lt;?php\n endwhile;\n wp_reset_postdata();\n ?&gt;\n\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>You then just need to update your pagination function with the <code>$max_num_pages</code> property rom your custom query</p>\n\n<pre><code>&lt;?php\n$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'prev_text' =&gt; __(' Previous'),\n 'next_text' =&gt; __('Next '),\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; $query-&gt;max_num_pages\n) );\n?&gt;\n</code></pre>\n" }, { "answer_id": 390794, "author": "Lucas Bustamante", "author_id": 27278, "author_profile": "https://wordpress.stackexchange.com/users/27278", "pm_score": 0, "selected": false, "text": "<p>I was using a custom query and needed to paginate my query results. Since the original <code>paginate_links()</code> function is heavily tied to the global <code>$wp_query</code> and <code>$wp_rewrite</code> contexts, I have adapted it to be completely independent. usage:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function myPaginateLinks( WP_Query $wp_query, $args = '' ) {\n global $wp_rewrite;\n\n // Setting up default values based on the current URL.\n $pagenum_link = html_entity_decode( get_pagenum_link() );\n $url_parts = explode( '?', $pagenum_link );\n\n // Get max pages and current page out of the current query, if available.\n $total = isset( $wp_query-&gt;max_num_pages ) ? $wp_query-&gt;max_num_pages : 1;\n $current = !empty($_GET['pg']) ? absint($_GET['pg']) : 1;\n\n // Append the format placeholder to the base URL.\n $pagenum_link = trailingslashit( $url_parts[0] ) . '%_%';\n\n // URL base depends on permalink settings.\n $format = $wp_rewrite-&gt;using_index_permalinks() &amp;&amp; ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';\n $format .= '?pg=%#%';\n\n $defaults = array(\n 'base' =&gt; $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below).\n 'format' =&gt; $format, // ?page=%#% : %#% is replaced by the page number.\n 'total' =&gt; $total,\n 'current' =&gt; $current,\n 'aria_current' =&gt; 'page',\n 'show_all' =&gt; false,\n 'prev_next' =&gt; true,\n 'prev_text' =&gt; __( '&amp;laquo; Previous' ),\n 'next_text' =&gt; __( 'Next &amp;raquo;' ),\n 'end_size' =&gt; 1,\n 'mid_size' =&gt; 2,\n 'type' =&gt; 'plain',\n 'add_args' =&gt; array(), // Array of query args to add.\n 'add_fragment' =&gt; '',\n 'before_page_number' =&gt; '',\n 'after_page_number' =&gt; '',\n );\n\n $args = wp_parse_args( $args, $defaults );\n\n if ( ! is_array( $args['add_args'] ) ) {\n $args['add_args'] = array();\n }\n\n // Merge additional query vars found in the original URL into 'add_args' array.\n if ( isset( $url_parts[1] ) ) {\n // Find the format argument.\n $format = explode( '?', str_replace( '%_%', $args['format'], $args['base'] ) );\n $format_query = isset( $format[1] ) ? $format[1] : '';\n wp_parse_str( $format_query, $format_args );\n\n // Find the query args of the requested URL.\n wp_parse_str( $url_parts[1], $url_query_args );\n\n // Remove the format argument from the array of query arguments, to avoid overwriting custom format.\n foreach ( $format_args as $format_arg =&gt; $format_arg_value ) {\n unset( $url_query_args[ $format_arg ] );\n }\n\n $args['add_args'] = array_merge( $args['add_args'], urlencode_deep( $url_query_args ) );\n }\n\n // Who knows what else people pass in $args.\n $total = (int) $args['total'];\n if ( $total &lt; 2 ) {\n return;\n }\n $current = (int) $args['current'];\n $end_size = (int) $args['end_size']; // Out of bounds? Make it the default.\n if ( $end_size &lt; 1 ) {\n $end_size = 1;\n }\n $mid_size = (int) $args['mid_size'];\n if ( $mid_size &lt; 0 ) {\n $mid_size = 2;\n }\n\n $add_args = $args['add_args'];\n $r = '';\n $page_links = array();\n $dots = false;\n\n if ( $args['prev_next'] &amp;&amp; $current &amp;&amp; 1 &lt; $current ) :\n $link = str_replace( '%_%', 2 == $current ? '' : $args['format'], $args['base'] );\n $link = str_replace( '%#%', $current - 1, $link );\n if ( $add_args ) {\n $link = add_query_arg( $add_args, $link );\n }\n $link .= $args['add_fragment'];\n\n $page_links[] = sprintf(\n '&lt;a class=&quot;prev page-numbers&quot; href=&quot;%s&quot;&gt;%s&lt;/a&gt;',\n /**\n * Filters the paginated links for the given archive pages.\n *\n * @since 3.0.0\n *\n * @param string $link The paginated link URL.\n */\n esc_url( apply_filters( 'paginate_links', $link ) ),\n $args['prev_text']\n );\n endif;\n\n for ( $n = 1; $n &lt;= $total; $n++ ) :\n if ( $n == $current ) :\n $page_links[] = sprintf(\n '&lt;span aria-current=&quot;%s&quot; class=&quot;page-numbers current&quot;&gt;%s&lt;/span&gt;',\n esc_attr( $args['aria_current'] ),\n $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']\n );\n\n $dots = true;\n else :\n if ( $args['show_all'] || ( $n &lt;= $end_size || ( $current &amp;&amp; $n &gt;= $current - $mid_size &amp;&amp; $n &lt;= $current + $mid_size ) || $n &gt; $total - $end_size ) ) :\n $link = str_replace( '%_%', 1 == $n ? '' : $args['format'], $args['base'] );\n $link = str_replace( '%#%', $n, $link );\n if ( $add_args ) {\n $link = add_query_arg( $add_args, $link );\n }\n $link .= $args['add_fragment'];\n\n $page_links[] = sprintf(\n '&lt;a class=&quot;page-numbers&quot; href=&quot;%s&quot;&gt;%s&lt;/a&gt;',\n /** This filter is documented in wp-includes/general-template.php */\n esc_url( apply_filters( 'paginate_links', $link ) ),\n $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']\n );\n\n $dots = true;\n elseif ( $dots &amp;&amp; ! $args['show_all'] ) :\n $page_links[] = '&lt;span class=&quot;page-numbers dots&quot;&gt;' . __( '&amp;hellip;' ) . '&lt;/span&gt;';\n\n $dots = false;\n endif;\n endif;\n endfor;\n\n if ( $args['prev_next'] &amp;&amp; $current &amp;&amp; $current &lt; $total ) :\n $link = str_replace( '%_%', $args['format'], $args['base'] );\n $link = str_replace( '%#%', $current + 1, $link );\n if ( $add_args ) {\n $link = add_query_arg( $add_args, $link );\n }\n $link .= $args['add_fragment'];\n\n $page_links[] = sprintf(\n '&lt;a class=&quot;next page-numbers&quot; href=&quot;%s&quot;&gt;%s&lt;/a&gt;',\n /** This filter is documented in wp-includes/general-template.php */\n esc_url( apply_filters( 'paginate_links', $link ) ),\n $args['next_text']\n );\n endif;\n\n switch ( $args['type'] ) {\n case 'array':\n return $page_links;\n\n case 'list':\n $r .= &quot;&lt;ul class='page-numbers'&gt;\\n\\t&lt;li&gt;&quot;;\n $r .= implode( &quot;&lt;/li&gt;\\n\\t&lt;li&gt;&quot;, $page_links );\n $r .= &quot;&lt;/li&gt;\\n&lt;/ul&gt;\\n&quot;;\n break;\n\n default:\n $r = implode( &quot;\\n&quot;, $page_links );\n break;\n }\n\n /**\n * Filters the HTML output of paginated links for archives.\n *\n * @since 5.7.0\n *\n * @param string $r HTML output.\n * @param array $args An array of arguments. See paginate_links()\n * for information on accepted arguments.\n */\n $r = apply_filters( 'paginate_links_output', $r, $args );\n\n return $r;\n}\n</code></pre>\n<p>Usage example:</p>\n<pre><code>$myQuery = new WP_Query();\n\n$cars = $myQuery-&gt;query([\n 'post_type' =&gt; 'cars',\n 'paged' =&gt; !empty($_GET['pg']) ? absint($_GET['pg']) : 1,\n]);\n\nforeach ($cars as $car) {\n echo $car-&gt;post_title;\n}\n\necho myPaginateLinks($myQuery);\n</code></pre>\n<p>Which produces the exact same result as paginate_links, but without any ties to the global query or rewrite rules:</p>\n<p><a href=\"https://i.stack.imgur.com/e2O9a.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/e2O9a.png\" alt=\"wordpress pagination custom query custom post type cpt\" /></a></p>\n<p>Notice that I'm using <code>$_GET['pg']</code> instead of <code>?paged</code> for the pagination, as I didn't want any &quot;rewrite magic&quot; getting into the way of the pagination.</p>\n" } ]
2015/04/27
[ "https://wordpress.stackexchange.com/questions/185600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67512/" ]
I have been using the same pagination query for the majority of the websites i have created. This time it is not working for some reason I have used the pagination trouble shooting links [Here](https://codex.wordpress.org/Pagination) but nothing seems to be working. I have attached my code below. This time i am querying the post in a table so i think that must have something to do with it but i have queried it without a table and is still not working. Please see my code below. New query ``` <?php $args = array( 'post_type' => 'custom_post_type', 'posts_per_page' => 5, 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), ); query_posts($args); ?> ``` The table with my table data from my custom meta fields. ``` <table> <thead > <tr> <th>header</th> <th>header</th> <th>header</th> <th>header</th> </tr> </thead> <tbody> <?php while (have_posts()) : the_post();?> <tr> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> </tr> <?php endwhile; ?> </tbody> </table> ``` My pagination links ``` <?php global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'prev_text' => __(' Previous'), 'next_text' => __('Next '), 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages ) ); ?> ``` When I say its not working i mean that the pagination links are displayed the appropriate number of pages. but when i press on page two it isnt changing pages. the permalinks are right its says `domain/page/2` but the page is the same as page one. This is on a template page i created for `home-page.php` I appreciate the suggestions.
As I already stated in comments, you should never use `query_posts`, only use `query_posts` if you are intended to break your page functionalities. Add `query_posts` to the very top of your **EVIL LIST**. `query_posts` breaks the main query object, the very object that your pagination function relies on. Your pagination function relies on the `$max_num_pages` property from the main query. This is just **one** of the many things that `query_posts` break. To solve your issue, make use of `WP_Query` as it seems that you are using a custom page template here. Just one note here, if `home-page.php` is a static front page, which I suspect from the template name, then ``` 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), ``` should be ``` 'paged' => ( get_query_var('page') ? get_query_var('page') : 1), ``` as static front pages uses `page` and not `paged` You can try something like this: (*Very important, this is untested and copied and pasted from OP, and **always** remember to reset postdata once you are done with your custom query*) ``` <?php $args = array( 'post_type' => 'custom_post_type', 'posts_per_page' => 5, 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), ); $query = new WP_Query($args); ?> <table> <thead > <tr> <th>header</th> <th>header</th> <th>header</th> <th>header</th> </tr> </thead> <tbody> <?php while ($query->have_posts()) : $query->the_post();?> <tr> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> </tr> <?php endwhile; wp_reset_postdata(); ?> </tbody> </table> ``` You then just need to update your pagination function with the `$max_num_pages` property rom your custom query ``` <?php $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'prev_text' => __(' Previous'), 'next_text' => __('Next '), 'current' => max( 1, get_query_var('paged') ), 'total' => $query->max_num_pages ) ); ?> ```
185,609
<p>I'm trying to change the header menu, such that it looks different when it is logged in and logged out, without changing the main menu.</p> <pre><code>function my_wp_nav_menu_args( $args = '' ) { if( is_user_logged_in() ) { $args['widget_nav_menu'] = 'menu 4'; } else { $args['widget_nav_menu'] = 'menu 3'; } return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); </code></pre> <p>This does the job to change the header menu, but it also changes the main menu. How do I get it to not change the main menu?</p>
[ { "answer_id": 185706, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>As I already stated in comments, you should never use <code>query_posts</code>, only use <code>query_posts</code> if you are intended to break your page functionalities. Add <code>query_posts</code> to the very top of your <strong>EVIL LIST</strong>.</p>\n\n<p><code>query_posts</code> breaks the main query object, the very object that your pagination function relies on. Your pagination function relies on the <code>$max_num_pages</code> property from the main query. This is just <strong>one</strong> of the many things that <code>query_posts</code> break. </p>\n\n<p>To solve your issue, make use of <code>WP_Query</code> as it seems that you are using a custom page template here. Just one note here, if <code>home-page.php</code> is a static front page, which I suspect from the template name, then </p>\n\n<pre><code>'paged' =&gt; ( get_query_var('paged') ? get_query_var('paged') : 1),\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>'paged' =&gt; ( get_query_var('page') ? get_query_var('page') : 1),\n</code></pre>\n\n<p>as static front pages uses <code>page</code> and not <code>paged</code></p>\n\n<p>You can try something like this: (<em>Very important, this is untested and copied and pasted from OP, and <strong>always</strong> remember to reset postdata once you are done with your custom query</em>)</p>\n\n<pre><code>&lt;?php\n$args = array(\n 'post_type' =&gt; 'custom_post_type',\n 'posts_per_page' =&gt; 5,\n 'paged' =&gt; ( get_query_var('paged') ? get_query_var('paged') : 1),\n);\n$query = new WP_Query($args);\n?&gt;\n&lt;table&gt;\n &lt;thead &gt;\n &lt;tr&gt;\n\n &lt;th&gt;header&lt;/th&gt;\n &lt;th&gt;header&lt;/th&gt;\n &lt;th&gt;header&lt;/th&gt;\n &lt;th&gt;header&lt;/th&gt;\n\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n\n &lt;?php while ($query-&gt;have_posts()) : $query-&gt;the_post();?&gt;\n &lt;tr&gt;\n\n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; \n &lt;td&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'metakey', true); ?&gt;&lt;/td&gt; \n\n &lt;/tr&gt;\n &lt;?php\n endwhile;\n wp_reset_postdata();\n ?&gt;\n\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>You then just need to update your pagination function with the <code>$max_num_pages</code> property rom your custom query</p>\n\n<pre><code>&lt;?php\n$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; '?paged=%#%',\n 'prev_text' =&gt; __(' Previous'),\n 'next_text' =&gt; __('Next '),\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; $query-&gt;max_num_pages\n) );\n?&gt;\n</code></pre>\n" }, { "answer_id": 390794, "author": "Lucas Bustamante", "author_id": 27278, "author_profile": "https://wordpress.stackexchange.com/users/27278", "pm_score": 0, "selected": false, "text": "<p>I was using a custom query and needed to paginate my query results. Since the original <code>paginate_links()</code> function is heavily tied to the global <code>$wp_query</code> and <code>$wp_rewrite</code> contexts, I have adapted it to be completely independent. usage:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function myPaginateLinks( WP_Query $wp_query, $args = '' ) {\n global $wp_rewrite;\n\n // Setting up default values based on the current URL.\n $pagenum_link = html_entity_decode( get_pagenum_link() );\n $url_parts = explode( '?', $pagenum_link );\n\n // Get max pages and current page out of the current query, if available.\n $total = isset( $wp_query-&gt;max_num_pages ) ? $wp_query-&gt;max_num_pages : 1;\n $current = !empty($_GET['pg']) ? absint($_GET['pg']) : 1;\n\n // Append the format placeholder to the base URL.\n $pagenum_link = trailingslashit( $url_parts[0] ) . '%_%';\n\n // URL base depends on permalink settings.\n $format = $wp_rewrite-&gt;using_index_permalinks() &amp;&amp; ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';\n $format .= '?pg=%#%';\n\n $defaults = array(\n 'base' =&gt; $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below).\n 'format' =&gt; $format, // ?page=%#% : %#% is replaced by the page number.\n 'total' =&gt; $total,\n 'current' =&gt; $current,\n 'aria_current' =&gt; 'page',\n 'show_all' =&gt; false,\n 'prev_next' =&gt; true,\n 'prev_text' =&gt; __( '&amp;laquo; Previous' ),\n 'next_text' =&gt; __( 'Next &amp;raquo;' ),\n 'end_size' =&gt; 1,\n 'mid_size' =&gt; 2,\n 'type' =&gt; 'plain',\n 'add_args' =&gt; array(), // Array of query args to add.\n 'add_fragment' =&gt; '',\n 'before_page_number' =&gt; '',\n 'after_page_number' =&gt; '',\n );\n\n $args = wp_parse_args( $args, $defaults );\n\n if ( ! is_array( $args['add_args'] ) ) {\n $args['add_args'] = array();\n }\n\n // Merge additional query vars found in the original URL into 'add_args' array.\n if ( isset( $url_parts[1] ) ) {\n // Find the format argument.\n $format = explode( '?', str_replace( '%_%', $args['format'], $args['base'] ) );\n $format_query = isset( $format[1] ) ? $format[1] : '';\n wp_parse_str( $format_query, $format_args );\n\n // Find the query args of the requested URL.\n wp_parse_str( $url_parts[1], $url_query_args );\n\n // Remove the format argument from the array of query arguments, to avoid overwriting custom format.\n foreach ( $format_args as $format_arg =&gt; $format_arg_value ) {\n unset( $url_query_args[ $format_arg ] );\n }\n\n $args['add_args'] = array_merge( $args['add_args'], urlencode_deep( $url_query_args ) );\n }\n\n // Who knows what else people pass in $args.\n $total = (int) $args['total'];\n if ( $total &lt; 2 ) {\n return;\n }\n $current = (int) $args['current'];\n $end_size = (int) $args['end_size']; // Out of bounds? Make it the default.\n if ( $end_size &lt; 1 ) {\n $end_size = 1;\n }\n $mid_size = (int) $args['mid_size'];\n if ( $mid_size &lt; 0 ) {\n $mid_size = 2;\n }\n\n $add_args = $args['add_args'];\n $r = '';\n $page_links = array();\n $dots = false;\n\n if ( $args['prev_next'] &amp;&amp; $current &amp;&amp; 1 &lt; $current ) :\n $link = str_replace( '%_%', 2 == $current ? '' : $args['format'], $args['base'] );\n $link = str_replace( '%#%', $current - 1, $link );\n if ( $add_args ) {\n $link = add_query_arg( $add_args, $link );\n }\n $link .= $args['add_fragment'];\n\n $page_links[] = sprintf(\n '&lt;a class=&quot;prev page-numbers&quot; href=&quot;%s&quot;&gt;%s&lt;/a&gt;',\n /**\n * Filters the paginated links for the given archive pages.\n *\n * @since 3.0.0\n *\n * @param string $link The paginated link URL.\n */\n esc_url( apply_filters( 'paginate_links', $link ) ),\n $args['prev_text']\n );\n endif;\n\n for ( $n = 1; $n &lt;= $total; $n++ ) :\n if ( $n == $current ) :\n $page_links[] = sprintf(\n '&lt;span aria-current=&quot;%s&quot; class=&quot;page-numbers current&quot;&gt;%s&lt;/span&gt;',\n esc_attr( $args['aria_current'] ),\n $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']\n );\n\n $dots = true;\n else :\n if ( $args['show_all'] || ( $n &lt;= $end_size || ( $current &amp;&amp; $n &gt;= $current - $mid_size &amp;&amp; $n &lt;= $current + $mid_size ) || $n &gt; $total - $end_size ) ) :\n $link = str_replace( '%_%', 1 == $n ? '' : $args['format'], $args['base'] );\n $link = str_replace( '%#%', $n, $link );\n if ( $add_args ) {\n $link = add_query_arg( $add_args, $link );\n }\n $link .= $args['add_fragment'];\n\n $page_links[] = sprintf(\n '&lt;a class=&quot;page-numbers&quot; href=&quot;%s&quot;&gt;%s&lt;/a&gt;',\n /** This filter is documented in wp-includes/general-template.php */\n esc_url( apply_filters( 'paginate_links', $link ) ),\n $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']\n );\n\n $dots = true;\n elseif ( $dots &amp;&amp; ! $args['show_all'] ) :\n $page_links[] = '&lt;span class=&quot;page-numbers dots&quot;&gt;' . __( '&amp;hellip;' ) . '&lt;/span&gt;';\n\n $dots = false;\n endif;\n endif;\n endfor;\n\n if ( $args['prev_next'] &amp;&amp; $current &amp;&amp; $current &lt; $total ) :\n $link = str_replace( '%_%', $args['format'], $args['base'] );\n $link = str_replace( '%#%', $current + 1, $link );\n if ( $add_args ) {\n $link = add_query_arg( $add_args, $link );\n }\n $link .= $args['add_fragment'];\n\n $page_links[] = sprintf(\n '&lt;a class=&quot;next page-numbers&quot; href=&quot;%s&quot;&gt;%s&lt;/a&gt;',\n /** This filter is documented in wp-includes/general-template.php */\n esc_url( apply_filters( 'paginate_links', $link ) ),\n $args['next_text']\n );\n endif;\n\n switch ( $args['type'] ) {\n case 'array':\n return $page_links;\n\n case 'list':\n $r .= &quot;&lt;ul class='page-numbers'&gt;\\n\\t&lt;li&gt;&quot;;\n $r .= implode( &quot;&lt;/li&gt;\\n\\t&lt;li&gt;&quot;, $page_links );\n $r .= &quot;&lt;/li&gt;\\n&lt;/ul&gt;\\n&quot;;\n break;\n\n default:\n $r = implode( &quot;\\n&quot;, $page_links );\n break;\n }\n\n /**\n * Filters the HTML output of paginated links for archives.\n *\n * @since 5.7.0\n *\n * @param string $r HTML output.\n * @param array $args An array of arguments. See paginate_links()\n * for information on accepted arguments.\n */\n $r = apply_filters( 'paginate_links_output', $r, $args );\n\n return $r;\n}\n</code></pre>\n<p>Usage example:</p>\n<pre><code>$myQuery = new WP_Query();\n\n$cars = $myQuery-&gt;query([\n 'post_type' =&gt; 'cars',\n 'paged' =&gt; !empty($_GET['pg']) ? absint($_GET['pg']) : 1,\n]);\n\nforeach ($cars as $car) {\n echo $car-&gt;post_title;\n}\n\necho myPaginateLinks($myQuery);\n</code></pre>\n<p>Which produces the exact same result as paginate_links, but without any ties to the global query or rewrite rules:</p>\n<p><a href=\"https://i.stack.imgur.com/e2O9a.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/e2O9a.png\" alt=\"wordpress pagination custom query custom post type cpt\" /></a></p>\n<p>Notice that I'm using <code>$_GET['pg']</code> instead of <code>?paged</code> for the pagination, as I didn't want any &quot;rewrite magic&quot; getting into the way of the pagination.</p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185609", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71292/" ]
I'm trying to change the header menu, such that it looks different when it is logged in and logged out, without changing the main menu. ``` function my_wp_nav_menu_args( $args = '' ) { if( is_user_logged_in() ) { $args['widget_nav_menu'] = 'menu 4'; } else { $args['widget_nav_menu'] = 'menu 3'; } return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); ``` This does the job to change the header menu, but it also changes the main menu. How do I get it to not change the main menu?
As I already stated in comments, you should never use `query_posts`, only use `query_posts` if you are intended to break your page functionalities. Add `query_posts` to the very top of your **EVIL LIST**. `query_posts` breaks the main query object, the very object that your pagination function relies on. Your pagination function relies on the `$max_num_pages` property from the main query. This is just **one** of the many things that `query_posts` break. To solve your issue, make use of `WP_Query` as it seems that you are using a custom page template here. Just one note here, if `home-page.php` is a static front page, which I suspect from the template name, then ``` 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), ``` should be ``` 'paged' => ( get_query_var('page') ? get_query_var('page') : 1), ``` as static front pages uses `page` and not `paged` You can try something like this: (*Very important, this is untested and copied and pasted from OP, and **always** remember to reset postdata once you are done with your custom query*) ``` <?php $args = array( 'post_type' => 'custom_post_type', 'posts_per_page' => 5, 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1), ); $query = new WP_Query($args); ?> <table> <thead > <tr> <th>header</th> <th>header</th> <th>header</th> <th>header</th> </tr> </thead> <tbody> <?php while ($query->have_posts()) : $query->the_post();?> <tr> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> <td><?php echo get_post_meta($post->ID, 'metakey', true); ?></td> </tr> <?php endwhile; wp_reset_postdata(); ?> </tbody> </table> ``` You then just need to update your pagination function with the `$max_num_pages` property rom your custom query ``` <?php $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'prev_text' => __(' Previous'), 'next_text' => __('Next '), 'current' => max( 1, get_query_var('paged') ), 'total' => $query->max_num_pages ) ); ?> ```
185,617
<p>I am managing the WordPress website i don't have the document of the website my problem is the website has the registration page please see [this link]</p> <p>but when i check the registration page in WordPress admin the page is blank i don't have any idea how the previous developer linked the page can anyone help where to find the page.</p>
[ { "answer_id": 185618, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 0, "selected": false, "text": "<p>Probably under your theme folder. Maybe a custom page-template, something like <code>page-register.php</code> or similar.</p>\n\n<blockquote>\n <p>but when i check the registration page in WordPress admin the page is blank</p>\n</blockquote>\n\n<p>Check the right side, is there a \"template\" applied?</p>\n\n<p>edit: hearing this is a buddypress theme I'd look into <code>themes\\[yourtheme]\\buddypress\\members\\register.php</code> or similar paths</p>\n" }, { "answer_id": 185621, "author": "Bjarni", "author_id": 68130, "author_profile": "https://wordpress.stackexchange.com/users/68130", "pm_score": 0, "selected": false, "text": "<p>When I looked that that page source code there was a class name of page-template-default which would indicate that it is using a standard default file, eg index.php, page.php etc.</p>\n" }, { "answer_id": 185622, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 2, "selected": true, "text": "<p>This is a <code>buddypress</code> page, linked with the page ID 4275. The body class of your delivered HTML is:</p>\n\n<pre><code>&lt;body class=\"registration register buddypress page page-id-4275 page-template-default admin-bar no-customize-support no-js\"&gt;\n</code></pre>\n\n<p>To edit this page itself, go to <a href=\"http://hoteliersnetworkme.com/wp-admin/post.php?post=4275&amp;action=edit\" rel=\"nofollow\">http://hoteliersnetworkme.com/wp-admin/post.php?post=4275&amp;action=edit</a></p>\n\n<p>BuddyPress filters the content of this page and adds a registration form.</p>\n\n<p>To modify the registration form itself, please refer to the <a href=\"https://codex.buddypress.org/getting-started/guides/modifying-the-registration-form/\" rel=\"nofollow\">BuddyPress documentation</a>.</p>\n\n<p><em>BTW: Seems like you have got a lot of work to do, cleaning all this up. Just at glancing at it I found 36 stylesheets and 61 Javascript files, as well as inline scripts, from at least 22 plugins plus your theme and child theme..</em></p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31332/" ]
I am managing the WordPress website i don't have the document of the website my problem is the website has the registration page please see [this link] but when i check the registration page in WordPress admin the page is blank i don't have any idea how the previous developer linked the page can anyone help where to find the page.
This is a `buddypress` page, linked with the page ID 4275. The body class of your delivered HTML is: ``` <body class="registration register buddypress page page-id-4275 page-template-default admin-bar no-customize-support no-js"> ``` To edit this page itself, go to <http://hoteliersnetworkme.com/wp-admin/post.php?post=4275&action=edit> BuddyPress filters the content of this page and adds a registration form. To modify the registration form itself, please refer to the [BuddyPress documentation](https://codex.buddypress.org/getting-started/guides/modifying-the-registration-form/). *BTW: Seems like you have got a lot of work to do, cleaning all this up. Just at glancing at it I found 36 stylesheets and 61 Javascript files, as well as inline scripts, from at least 22 plugins plus your theme and child theme..*
185,631
<p>How to get the same post content for in (the default) <code>domain.com/year/month/post-slug</code> and <code>domain.com/custom/post-slug</code> (without redirect).</p> <p>Can I do this with some kind of rewrite or do I need a custom post type with it's own permalink structure?</p> <p>So the gist is that I want to show the same content a little differently in different urls. Is this even possible? Any other ideas how to implement something like this?</p>
[ { "answer_id": 185658, "author": "user2914563", "author_id": 68720, "author_profile": "https://wordpress.stackexchange.com/users/68720", "pm_score": -1, "selected": false, "text": "<p>I think you need to change your permalink structure for all your past posts and future posts?</p>\n\n<p>Just go to setting-> Permalink and type in custom permalink there,\nNow secondly I would recommend you to use Permalink Finder Plugin (Not Updated but is not having any compatibility issues), it will automatically redirect your posts to the changed permalink...I have been using it and it always 100% redirects correctly.</p>\n" }, { "answer_id": 186061, "author": "jimihenrik", "author_id": 64625, "author_profile": "https://wordpress.stackexchange.com/users/64625", "pm_score": 2, "selected": true, "text": "<p>I ended going the CPT route, as I couldn't figure out other way. Just added a bunch of logic to duplicate/modify/delete the normal posts when needed.</p>\n\n<pre><code>&lt;?php // function for the CPT\nfunction SU_kuuma_kysymys_type() { \n // creating (registering) the custom type \n register_post_type( 'kuuma_kysymys', /* (http://codex.wordpress.org/Function_Reference/register_post_type) */\n // let's now add all the options for this post type\n array( 'labels' =&gt; array(\n 'name' =&gt; ( 'Kuumat kysymykset' ), /* This is the Title of the Group */\n 'singular_name' =&gt; ( 'Kuuma kysymys' ), /* This is the individual type */\n 'all_items' =&gt; ( 'Kaikki kysymykset' ), /* the all items menu item */\n 'add_new' =&gt; ( 'Lisää uusi' ), /* The add new menu item */\n 'add_new_item' =&gt; ( 'Add New Custom Type' ), /* Add New Display Title */\n 'edit' =&gt; ( 'Edit' ), /* Edit Dialog */\n 'edit_item' =&gt; ( 'Muokkaa kysymystä' ), /* Edit Display Title */\n 'new_item' =&gt; ( 'Lisää kysymys' ), /* New Display Title */\n 'view_item' =&gt; ( 'Näytä kysymys' ), /* View Display Title */\n 'search_items' =&gt; ( 'Etsi kysymyksiä' ), /* Search Custom Type Title */ \n 'not_found' =&gt; ( 'Kysymyksiä ei löytynyt.' ), /* This displays if there are no entries yet */ \n 'not_found_in_trash' =&gt; ( 'Roskakori on tyhjä.' ), /* This displays if there is nothing in the trash */\n ), /* end of arrays */\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'exclude_from_search' =&gt; true,\n 'show_ui' =&gt; false,\n 'show_in_admin_bar' =&gt; false,\n 'query_var' =&gt; true,\n 'menu_position' =&gt; 8, /* this is what order you want it to appear in on the left hand side menu */ \n 'menu_icon' =&gt; get_stylesheet_directory_uri() . '/library/images/custom-post-icon.png', /* the icon for the custom post type menu */\n 'rewrite' =&gt; array( 'slug' =&gt; 'kuuma-kysymys', 'with_front' =&gt; false ), /* you can specify its url slug */\n 'has_archive' =&gt; 'kuuma-kysymys', /* you can rename the slug here */\n /* the next one is important, it tells what's enabled in the post editor */\n 'supports' =&gt; array( 'title', 'editor', 'author', 'comments')\n ) /* end of options */\n ); /* end of register post type */\n\n /* this adds your post categories to your custom post type */\n register_taxonomy_for_object_type( 'category', 'custom_type' );\n}\n// adding the function to the Wordpress init\nadd_action('init', 'SU_kuuma_kysymys_type');\n\n\n//first all the methods handling the question CPT posts\nfunction SU_add_kysymys_post($post) {\n $newpost = array(\n 'post_name' =&gt; $post-&gt;post_name,\n 'post_title' =&gt; $post-&gt;post_title,\n 'post_content' =&gt; $post-&gt;post_content,\n 'post_status' =&gt; $post-&gt;post_status,\n 'post_type' =&gt; 'kuuma_kysymys',\n 'post_author' =&gt; $post-&gt;post_status,\n 'post_category' =&gt; $post-&gt;post_category\n );\n\n $kysymys_post_id = wp_insert_post($newpost, true);\n\n // add the post ID's to their respective meta fields on both posts\n update_post_meta($post-&gt;ID, 'question_post_id', $kysymys_post_id);\n update_post_meta($kysymys_post_id, 'original_post_id', $post-&gt;ID);\n}\n\nfunction SU_update_kysymys_post($post, $q_post_id) {\n $updatedpost = array(\n 'ID' =&gt; $q_post_id,\n 'post_name' =&gt; $post-&gt;post_name,\n 'post_title' =&gt; $post-&gt;post_title,\n 'post_content' =&gt; $post-&gt;post_content,\n 'post_status' =&gt; $post-&gt;post_status,\n 'post_type' =&gt; 'kuuma_kysymys',\n 'post_author' =&gt; $post-&gt;post_status,\n 'post_category' =&gt; $post-&gt;post_category\n );\n wp_update_post($updatedpost, true);\n}\n\nfunction SU_delete_kysymys_post($post, $q_post_id = false) {\n // If we dont give $q_post_id check if we have the meta field\n if (!$q_post_id) { $q_post_id = get_post_meta($post_id, 'question_post_id', true); }\n // If we now have CPT post id -&gt; delete it\n if($q_post_id != \"\") {\n update_post_meta($post-&gt;ID, 'question_post_id', '');\n // Remove the deletion hook in case we're just removing the category\n remove_action('delete_post', 'SU_check_kysymys_deletion', 10);\n wp_delete_post($q_post_id, true);\n add_action('delete_post', 'SU_check_kysymys_deletion', 10);\n }\n}\n\n// and the logic on what to do and when\nfunction SU_check_kysymys($post_id, $post, $update) {\n //if new post or doing autosave/revision do nothing\n if(wp_is_post_revision($post_id) || wp_is_post_autosave($post_id) || get_post_status($post_id) == 'auto-draft') { return; }\n else {\n // We're saving/updating, go for it\n $q_post_id = get_post_meta($post_id, 'question_post_id', true);\n if (has_category('kuuma-kysymys', $post_id)) { // has the category \"kuuma kysymys\"\n if($q_post_id == \"\") {\n SU_add_kysymys_post($post);\n // wp_die('&lt;pre&gt;No q_post_id meta so new post?.&lt;br&gt;&lt;br&gt;$post = '.var_export($update, true).'&lt;/pre&gt;'); \n } else {\n SU_update_kysymys_post($post, (int)$q_post_id);\n // wp_die('&lt;pre&gt;We have q_post_id so just update existing CP I think.&lt;br&gt;&lt;br&gt;$post = '.var_export($post, true).'&lt;/pre&gt;'); \n }\n } else { // doesn't have the category (at least not anymore)\n\n if($q_post_id == \"\") { return; } // doesn't have the category or earlier remains of the meta field\n else { // doesn't have the category but has meta field -&gt; had the category before -&gt; delete the added CP\n SU_delete_kysymys_post($post, (int)$q_post_id);\n //wp_die('&lt;pre&gt;We have post meta but lack the category so delete CP&lt;br&gt;&lt;br&gt;$post = '.var_export($post, true).'&lt;/pre&gt;'); \n }\n }\n }\n}\nadd_action('save_post', 'SU_check_kysymys', 10, 3);\n\n// logic for deleting questions if the concurrent regular post is deleted for any reason\nfunction SU_check_kysymys_deletion($post) {\n if (has_category('kuuma-kysymys', $post-&gt;ID)) {\n SU_delete_kysymys_post($post);\n }\n}\nadd_action('delete_post', 'SU_check_kysymys_deletion', 10); ?&gt;\n</code></pre>\n\n<p>but this way I can access the \"same\" post from two different locations and have a custom template for each one.</p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185631", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64625/" ]
How to get the same post content for in (the default) `domain.com/year/month/post-slug` and `domain.com/custom/post-slug` (without redirect). Can I do this with some kind of rewrite or do I need a custom post type with it's own permalink structure? So the gist is that I want to show the same content a little differently in different urls. Is this even possible? Any other ideas how to implement something like this?
I ended going the CPT route, as I couldn't figure out other way. Just added a bunch of logic to duplicate/modify/delete the normal posts when needed. ``` <?php // function for the CPT function SU_kuuma_kysymys_type() { // creating (registering) the custom type register_post_type( 'kuuma_kysymys', /* (http://codex.wordpress.org/Function_Reference/register_post_type) */ // let's now add all the options for this post type array( 'labels' => array( 'name' => ( 'Kuumat kysymykset' ), /* This is the Title of the Group */ 'singular_name' => ( 'Kuuma kysymys' ), /* This is the individual type */ 'all_items' => ( 'Kaikki kysymykset' ), /* the all items menu item */ 'add_new' => ( 'Lisää uusi' ), /* The add new menu item */ 'add_new_item' => ( 'Add New Custom Type' ), /* Add New Display Title */ 'edit' => ( 'Edit' ), /* Edit Dialog */ 'edit_item' => ( 'Muokkaa kysymystä' ), /* Edit Display Title */ 'new_item' => ( 'Lisää kysymys' ), /* New Display Title */ 'view_item' => ( 'Näytä kysymys' ), /* View Display Title */ 'search_items' => ( 'Etsi kysymyksiä' ), /* Search Custom Type Title */ 'not_found' => ( 'Kysymyksiä ei löytynyt.' ), /* This displays if there are no entries yet */ 'not_found_in_trash' => ( 'Roskakori on tyhjä.' ), /* This displays if there is nothing in the trash */ ), /* end of arrays */ 'public' => true, 'publicly_queryable' => true, 'exclude_from_search' => true, 'show_ui' => false, 'show_in_admin_bar' => false, 'query_var' => true, 'menu_position' => 8, /* this is what order you want it to appear in on the left hand side menu */ 'menu_icon' => get_stylesheet_directory_uri() . '/library/images/custom-post-icon.png', /* the icon for the custom post type menu */ 'rewrite' => array( 'slug' => 'kuuma-kysymys', 'with_front' => false ), /* you can specify its url slug */ 'has_archive' => 'kuuma-kysymys', /* you can rename the slug here */ /* the next one is important, it tells what's enabled in the post editor */ 'supports' => array( 'title', 'editor', 'author', 'comments') ) /* end of options */ ); /* end of register post type */ /* this adds your post categories to your custom post type */ register_taxonomy_for_object_type( 'category', 'custom_type' ); } // adding the function to the Wordpress init add_action('init', 'SU_kuuma_kysymys_type'); //first all the methods handling the question CPT posts function SU_add_kysymys_post($post) { $newpost = array( 'post_name' => $post->post_name, 'post_title' => $post->post_title, 'post_content' => $post->post_content, 'post_status' => $post->post_status, 'post_type' => 'kuuma_kysymys', 'post_author' => $post->post_status, 'post_category' => $post->post_category ); $kysymys_post_id = wp_insert_post($newpost, true); // add the post ID's to their respective meta fields on both posts update_post_meta($post->ID, 'question_post_id', $kysymys_post_id); update_post_meta($kysymys_post_id, 'original_post_id', $post->ID); } function SU_update_kysymys_post($post, $q_post_id) { $updatedpost = array( 'ID' => $q_post_id, 'post_name' => $post->post_name, 'post_title' => $post->post_title, 'post_content' => $post->post_content, 'post_status' => $post->post_status, 'post_type' => 'kuuma_kysymys', 'post_author' => $post->post_status, 'post_category' => $post->post_category ); wp_update_post($updatedpost, true); } function SU_delete_kysymys_post($post, $q_post_id = false) { // If we dont give $q_post_id check if we have the meta field if (!$q_post_id) { $q_post_id = get_post_meta($post_id, 'question_post_id', true); } // If we now have CPT post id -> delete it if($q_post_id != "") { update_post_meta($post->ID, 'question_post_id', ''); // Remove the deletion hook in case we're just removing the category remove_action('delete_post', 'SU_check_kysymys_deletion', 10); wp_delete_post($q_post_id, true); add_action('delete_post', 'SU_check_kysymys_deletion', 10); } } // and the logic on what to do and when function SU_check_kysymys($post_id, $post, $update) { //if new post or doing autosave/revision do nothing if(wp_is_post_revision($post_id) || wp_is_post_autosave($post_id) || get_post_status($post_id) == 'auto-draft') { return; } else { // We're saving/updating, go for it $q_post_id = get_post_meta($post_id, 'question_post_id', true); if (has_category('kuuma-kysymys', $post_id)) { // has the category "kuuma kysymys" if($q_post_id == "") { SU_add_kysymys_post($post); // wp_die('<pre>No q_post_id meta so new post?.<br><br>$post = '.var_export($update, true).'</pre>'); } else { SU_update_kysymys_post($post, (int)$q_post_id); // wp_die('<pre>We have q_post_id so just update existing CP I think.<br><br>$post = '.var_export($post, true).'</pre>'); } } else { // doesn't have the category (at least not anymore) if($q_post_id == "") { return; } // doesn't have the category or earlier remains of the meta field else { // doesn't have the category but has meta field -> had the category before -> delete the added CP SU_delete_kysymys_post($post, (int)$q_post_id); //wp_die('<pre>We have post meta but lack the category so delete CP<br><br>$post = '.var_export($post, true).'</pre>'); } } } } add_action('save_post', 'SU_check_kysymys', 10, 3); // logic for deleting questions if the concurrent regular post is deleted for any reason function SU_check_kysymys_deletion($post) { if (has_category('kuuma-kysymys', $post->ID)) { SU_delete_kysymys_post($post); } } add_action('delete_post', 'SU_check_kysymys_deletion', 10); ?> ``` but this way I can access the "same" post from two different locations and have a custom template for each one.
185,639
<p>I've downloaded <a href="http://contactform7.com/" rel="nofollow">Contact Form 7</a> to add contact forms adding a simple snippet after every post, and I've added it in functions.php like this : </p> <pre><code>//if post type I add a form function is_post_type($type) { global $wp_query; if($type == get_post_type($wp_query-&gt;post-&gt;ID)) return true; return false; } function add_post_content($content){ if(!is_feed() &amp;&amp; !is_home()&amp;&amp; is_single() &amp;&amp; is_post_type('post')) { $content .= '[contact-form-7 id="2202" title="Formulario de contacto 1"]'; } return $content; } add_filter('the_content', 'add_post_content'); </code></pre> <p>What I would like to do now is to add a new field in the plugin to send the link of the entry were the user is sending the form, or even to concatenate this link or Id after the email content, or something like that, but I'm stuck in WordPress, and I don't know what file I need to edit and how to import the $post variables.</p>
[ { "answer_id": 185642, "author": "Sladix", "author_id": 27423, "author_profile": "https://wordpress.stackexchange.com/users/27423", "pm_score": 1, "selected": false, "text": "<p>You can try to add a get parameter to your url in the link to your contact form.</p>\n\n<p>If it's a lightbox style, you can also define a hidden field and fill it when wpcf7 loads up using global $post.</p>\n\n<p>Use this code for the url parameter solution and replace id_post by global $post->ID for the lightbow solution :</p>\n\n<pre><code>//Add the post id\nfunction add_post_id_origin ( $tag, $unused ) {\n //First we test if it's our hidden field\n if ( $tag['name'] != 'myhiddentag' ) \n return $tag; \n\n//This is for the url param version\nif(isset($_GET['id_post']) &amp;&amp; is_numeric($_GET['id_post']))\n{\n $post = get_post($_GET['id_post']);\n $tag['values'] = array($post-&gt;ID); \n $tag['options'] = array('readonly');\n}\n//this way for a regulare global $post usage\nglobal $post;\n$tag['values'] = array($post-&gt;ID); \n$tag['options'] = array('readonly');\n\nreturn $tag; \n} \n\n//Don't forget to hook the function\nadd_filter( 'wpcf7_form_tag', 'add_post_id_origin', 10, 2);\n</code></pre>\n" }, { "answer_id": 185643, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": true, "text": "<p>This is pretty easy out of the box:</p>\n\n<p>Just use the <code>[_url]</code> special mail tag.</p>\n\n<p>As long as you are on a post or page you can even add some more things like the title with <code>[_post_title]</code>.</p>\n\n<p>Just have a look at <a href=\"http://contactform7.com/special-mail-tags/\" rel=\"nofollow\">the documentation</a> for more options.</p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69187/" ]
I've downloaded [Contact Form 7](http://contactform7.com/) to add contact forms adding a simple snippet after every post, and I've added it in functions.php like this : ``` //if post type I add a form function is_post_type($type) { global $wp_query; if($type == get_post_type($wp_query->post->ID)) return true; return false; } function add_post_content($content){ if(!is_feed() && !is_home()&& is_single() && is_post_type('post')) { $content .= '[contact-form-7 id="2202" title="Formulario de contacto 1"]'; } return $content; } add_filter('the_content', 'add_post_content'); ``` What I would like to do now is to add a new field in the plugin to send the link of the entry were the user is sending the form, or even to concatenate this link or Id after the email content, or something like that, but I'm stuck in WordPress, and I don't know what file I need to edit and how to import the $post variables.
This is pretty easy out of the box: Just use the `[_url]` special mail tag. As long as you are on a post or page you can even add some more things like the title with `[_post_title]`. Just have a look at [the documentation](http://contactform7.com/special-mail-tags/) for more options.
185,650
<p>I found similar questions to it but none was an exact match to my question.</p> <p>I am using featured image in all my posts. I want to remove featured image on single post view from a single category (Say Video Interview) and not from multiple post view i.e. homepage.</p> <p>In other words, From Video category I want to show featured image in homepage but when someone clicks on continue reading and is redirected to single post view or full post view then featured image should disappear. I want to put videos in my post without any text. So it would look odd if featured image shows up in single post view.</p> <p>So, the code needs to be </p> <p>1.) Category wise</p> <p>2.) Only removing featured image at single post page</p>
[ { "answer_id": 185666, "author": "Guerrilla", "author_id": 70230, "author_profile": "https://wordpress.stackexchange.com/users/70230", "pm_score": 1, "selected": false, "text": "<p>You can update the way image is displayed in template. in the page loop it will have something like this:</p>\n\n<pre><code>&lt;?php the_post_thumbnail(); ?&gt;\n</code></pre>\n\n<p>This grabs the featured image. You can wrap that in a <a href=\"https://codex.wordpress.org/Conditional_Tags#A_Category_Page\" rel=\"nofollow\">conditional statement</a> to check for whatever you like.</p>\n\n<p>This would show it in every category apart from catgory 3.</p>\n\n<pre><code>&lt;?php if ( !in_category( '3' ) ) : ?&gt;\n\n&lt;?php the_post_thumbnail(); ?&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Further reading: <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow\">https://codex.wordpress.org/The_Loop</a></p>\n" }, { "answer_id": 185827, "author": "user2914563", "author_id": 68720, "author_profile": "https://wordpress.stackexchange.com/users/68720", "pm_score": 0, "selected": false, "text": "<p>I got an answer to it on some website... </p>\n\n<p>Just edit your css or add some css plugin (jetpack edit css, etc.)</p>\n\n<pre><code>.single .category-video .post-thumbnail img {\n display: none;\n}\n</code></pre>\n\n<p>Replace video with your category name...</p>\n\n<p>No need to change any theme functions...</p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68720/" ]
I found similar questions to it but none was an exact match to my question. I am using featured image in all my posts. I want to remove featured image on single post view from a single category (Say Video Interview) and not from multiple post view i.e. homepage. In other words, From Video category I want to show featured image in homepage but when someone clicks on continue reading and is redirected to single post view or full post view then featured image should disappear. I want to put videos in my post without any text. So it would look odd if featured image shows up in single post view. So, the code needs to be 1.) Category wise 2.) Only removing featured image at single post page
You can update the way image is displayed in template. in the page loop it will have something like this: ``` <?php the_post_thumbnail(); ?> ``` This grabs the featured image. You can wrap that in a [conditional statement](https://codex.wordpress.org/Conditional_Tags#A_Category_Page) to check for whatever you like. This would show it in every category apart from catgory 3. ``` <?php if ( !in_category( '3' ) ) : ?> <?php the_post_thumbnail(); ?> <?php endif; ?> ``` Further reading: <https://codex.wordpress.org/The_Loop>
185,659
<p>I am trying to investigate the correlation between the total number of posts published on a blog and the traffic it receive. I think it's not a huge task but my experience with coding with Wordpress is almost null. </p> <p>I guess it should be something like a foreach which loops all the posts and list the publishing date for each of them. Then sorts them by publishing date and then it counts the number of published post.</p> <p>Is my question clear enough?</p>
[ { "answer_id": 185660, "author": "jjarolim", "author_id": 56506, "author_profile": "https://wordpress.stackexchange.com/users/56506", "pm_score": 2, "selected": false, "text": "<p>the fastest way imho would be to create a custom sql statement:</p>\n\n<pre><code>global $wpdb;\n$rows = $wpdb-&gt;query('SELECT DATE(post_date) AS date, COUNT(*) AS count FROM ' . $wpdb-&gt;posts . ' GROUP BY DATE(post_date) ORDER BY DATE(post_date)');\nforeach ($rows as $row) {\n echo $row-&gt;date . ': ' . $row-&gt;count . '&lt;br&gt;';\n}\n</code></pre>\n" }, { "answer_id": 185665, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You'll want to use <code>WP_Query</code>, <a href=\"http://codex.wordpress.org/Function_Reference/WP_Query#Date_Parameters\" rel=\"nofollow\">along with the data parameters</a></p>\n\n<p>e.g. years:</p>\n\n<pre><code>$years = array( 2015,2014,2013,2012 );\necho '&lt;table&gt;';\nforeach ( $years as $year ) {\n $q = new WP_Query( array(\n 'year' =&gt; $year,\n 'fields' =&gt; 'ids'\n ) );\n echo '&lt;tr&gt;&lt;td&gt;'.$year.'&lt;/td&gt;&lt;td&gt;'. $q-&gt;found_posts.'&lt;/td&gt;&lt;/tr&gt;';\n}\necho '&lt;/table&gt;';\n</code></pre>\n\n<p>Note I specified only to grab the post IDs, this is to reduce the cost of the query. Doing it this way also means you can take better advantage of caching plugins</p>\n" }, { "answer_id": 187714, "author": "Revious", "author_id": 64590, "author_profile": "https://wordpress.stackexchange.com/users/64590", "pm_score": 0, "selected": false, "text": "<p>This answer is going to integrate the one from jjarolim</p>\n\n<p>The correct whole query is</p>\n\n<pre><code>SELECT DATE(post_date) AS date, concat(post_title) titles, COUNT(*) AS count\nFROM wp_posts \nWHERE post_status = 'publish'\nAND post_parent = 0\nAND post_type = 'post'\nGROUP BY DATE(post_date)\nORDER BY DATE(post_date)\n</code></pre>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185659", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64590/" ]
I am trying to investigate the correlation between the total number of posts published on a blog and the traffic it receive. I think it's not a huge task but my experience with coding with Wordpress is almost null. I guess it should be something like a foreach which loops all the posts and list the publishing date for each of them. Then sorts them by publishing date and then it counts the number of published post. Is my question clear enough?
the fastest way imho would be to create a custom sql statement: ``` global $wpdb; $rows = $wpdb->query('SELECT DATE(post_date) AS date, COUNT(*) AS count FROM ' . $wpdb->posts . ' GROUP BY DATE(post_date) ORDER BY DATE(post_date)'); foreach ($rows as $row) { echo $row->date . ': ' . $row->count . '<br>'; } ```
185,685
<p>i have this custom search-result page</p> <pre><code>global $query_string; $query_args = explode("&amp;", $query_string); $search_query = array( 'nopaging' =&gt; true, 'post_type' =&gt; 'page' ); foreach($query_args as $key =&gt; $string) { $query_split = explode("=", $string); $search_query[$query_split[0]] = urldecode($query_split[1]); } // foreach $search = new WP_Query($search_query); &lt;div class="page_title"&gt; &lt;div class="container"&gt; &lt;h1&gt;&lt;?php echo $search-&gt;found_posts; ?&gt; &lt;?php if ( is_rtl() ) { echo 'نتائج بحث عن'; } else { echo 'Search Results Found For'; } ?&gt; : "&lt;?php the_search_query(); ?&gt;"&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="content_fullwidth"&gt; &lt;div class="container"&gt; &lt;?php if ( $search-&gt;have_posts() ) : while ( $search-&gt;have_posts() ) : $search-&gt;the_post(); ?&gt; &lt;h1&gt;&lt;a href="&lt;?php echo get_permalink()?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;?php endwhile; else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>the search results i am expecting will have custom fields for image and description , with the fields having different IDs depending on which page this result is from, i am having a problem figure out the correct code to pull out values from those custom fields.</p> <pre><code>&lt;h1&gt;&lt;a href="&lt;?php echo get_permalink()?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; </code></pre> <p>working fine because it is more of a generic function that will work on all the results. so my problem is figuring out a dynamic code to pull out those custom fields values knowing that they have different IDs in terms of the page ID and the Custom field ID it self.</p> <p>note: i am using <a href="https://github.com/WebDevStudios/CMB2" rel="nofollow">CMB2</a> to display custom metaboxes , below is a sample of a metabox displayed on a specific page</p> <pre><code>function mobile_adv_metabox() { // Start with an underscore to hide fields from custom fields list $prefix = 'mobile_adv_'; /** * Metabox to be displayed on a single page ID */ $cmb_mobile_adv = new_cmb2_box( array( 'id' =&gt; $prefix . 'metabox', 'title' =&gt; __( 'Page Details', 'cmb2' ), 'object_types' =&gt; array( 'page', ), // Post type 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'show_names' =&gt; true, // Show field names on the left 'show_on' =&gt; array( 'id' =&gt; array( 10 ) ), // Specific post IDs to display this metabox ) ); $cmb_mobile_adv-&gt;add_field( array( 'name' =&gt; 'Service Image', 'desc' =&gt; 'Upload an image or add one from the library. ', 'id' =&gt; $prefix . 'service_image', 'type' =&gt; 'file', 'options' =&gt; array( 'url' =&gt; false, ), ) ); $cmb_mobile_adv-&gt;add_field( array( 'name' =&gt; 'Service Description', 'desc' =&gt; 'Add a description for the service.', 'id' =&gt; $prefix . 'service_desc', 'type' =&gt; 'textarea', ) ); </code></pre>
[ { "answer_id": 185803, "author": "efoula", "author_id": 42810, "author_profile": "https://wordpress.stackexchange.com/users/42810", "pm_score": -1, "selected": false, "text": "<p>Put this in your custom search page instead of your code, and don't forget to define your post types in the query arguments..</p>\n\n<pre><code>&lt;?php\n// Query arguments\nglobal $wpdb;\n// If you use a custom search form\n// $keyword = sanitize_text_field( $_POST['keyword'] );\n// If you use default WordPress search form\n$keyword = get_search_query();\n$keyword = '%' . like_escape( $keyword ) . '%'; // Thanks Manny Fleurmond\n// Search in all custom fields\n$post_ids_meta = $wpdb-&gt;get_col( $wpdb-&gt;prepare( \"\n SELECT DISTINCT post_id FROM {$wpdb-&gt;postmeta}\n WHERE meta_value LIKE '%s'\n\", $keyword ) );\n// Search in post_title and post_content\n$post_ids_post = $wpdb-&gt;get_col( $wpdb-&gt;prepare( \"\n SELECT DISTINCT ID FROM {$wpdb-&gt;posts}\n WHERE post_title LIKE '%s'\n OR post_content LIKE '%s'\n\", $keyword, $keyword ) );\n$post_ids = array_merge( $post_ids_meta, $post_ids_post );\n// Query arguments\n$args = array(\n 'post_type' =&gt; array('post'),\n 'post_status' =&gt; 'publish',\n 'post__in' =&gt; $post_ids,\n);\n$query = new WP_Query( $args );\nif ( $query-&gt;have_posts() ): while ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n// Do loop here\n echo '&lt;a href=\"'.get_permalink().'\"&gt;';\n echo the_title();\n echo '&lt;/a&gt;';\n echo '&lt;br&gt;';\n echo the_content();\n\n\n\n\nendwhile;\n\nelse :\n _e('Sorry, no posts matched your criteria.');\n\nendif;\n?&gt;\n</code></pre>\n\n<p>Thank you.\nBest,\nEF.</p>\n" }, { "answer_id": 185807, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 1, "selected": true, "text": "<p>You just need to get the data using <code>get_post_meta()</code>.</p>\n\n<pre><code>&lt;h1&gt;&lt;a href=\"&lt;?php echo get_permalink()?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;\n&lt;span class=\"description\"&gt;\n &lt;?php echo get_post_meta( get_the_ID(), 'mobile_adv_service_desc', true ); ?&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>This Plugin stores your values as WordPress metadata. So to retrieve the values in the frontend, you can use the built in WordPress functions for that.</p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185685", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62794/" ]
i have this custom search-result page ``` global $query_string; $query_args = explode("&", $query_string); $search_query = array( 'nopaging' => true, 'post_type' => 'page' ); foreach($query_args as $key => $string) { $query_split = explode("=", $string); $search_query[$query_split[0]] = urldecode($query_split[1]); } // foreach $search = new WP_Query($search_query); <div class="page_title"> <div class="container"> <h1><?php echo $search->found_posts; ?> <?php if ( is_rtl() ) { echo 'نتائج بحث عن'; } else { echo 'Search Results Found For'; } ?> : "<?php the_search_query(); ?>"</h1> </div> </div> <div class="content_fullwidth"> <div class="container"> <?php if ( $search->have_posts() ) : while ( $search->have_posts() ) : $search->the_post(); ?> <h1><a href="<?php echo get_permalink()?>"><?php the_title(); ?></a></h1> <?php endwhile; else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> </div> </div> ``` the search results i am expecting will have custom fields for image and description , with the fields having different IDs depending on which page this result is from, i am having a problem figure out the correct code to pull out values from those custom fields. ``` <h1><a href="<?php echo get_permalink()?>"><?php the_title(); ?></a></h1> ``` working fine because it is more of a generic function that will work on all the results. so my problem is figuring out a dynamic code to pull out those custom fields values knowing that they have different IDs in terms of the page ID and the Custom field ID it self. note: i am using [CMB2](https://github.com/WebDevStudios/CMB2) to display custom metaboxes , below is a sample of a metabox displayed on a specific page ``` function mobile_adv_metabox() { // Start with an underscore to hide fields from custom fields list $prefix = 'mobile_adv_'; /** * Metabox to be displayed on a single page ID */ $cmb_mobile_adv = new_cmb2_box( array( 'id' => $prefix . 'metabox', 'title' => __( 'Page Details', 'cmb2' ), 'object_types' => array( 'page', ), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'show_on' => array( 'id' => array( 10 ) ), // Specific post IDs to display this metabox ) ); $cmb_mobile_adv->add_field( array( 'name' => 'Service Image', 'desc' => 'Upload an image or add one from the library. ', 'id' => $prefix . 'service_image', 'type' => 'file', 'options' => array( 'url' => false, ), ) ); $cmb_mobile_adv->add_field( array( 'name' => 'Service Description', 'desc' => 'Add a description for the service.', 'id' => $prefix . 'service_desc', 'type' => 'textarea', ) ); ```
You just need to get the data using `get_post_meta()`. ``` <h1><a href="<?php echo get_permalink()?>"><?php the_title(); ?></a></h1> <span class="description"> <?php echo get_post_meta( get_the_ID(), 'mobile_adv_service_desc', true ); ?> </span> ``` This Plugin stores your values as WordPress metadata. So to retrieve the values in the frontend, you can use the built in WordPress functions for that.
185,693
<p>I am aware of the option to set <code>exclude_from_search =&gt; 'true'</code> when registering a custom post type. But what are the other options?</p>
[ { "answer_id": 185696, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> hook. Do note though, this hook filters the query on both the front-end and admin. For example, we could do something like this:</p>\n\n<pre><code>function search_post_types( $query ) {\n if( is_admin() ) {\n return $query;\n }\n\n if ( $query-&gt;is_search &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'post_type', array( 'post', 'page' ) );\n }\n}\nadd_action( 'pre_get_posts', 'search_post_types' );\n</code></pre>\n\n<p>I'm not sure there's a way to <em>exclude</em> it using <code>pre_get_posts</code> but more along the lines of include specific post types only, in the example above I'm only including Posts and Pages, nothing else.</p>\n\n<hr>\n\n<p>Another method is to get <em>all</em> post types and create an array of post types we actually want to exclude. First we use the function <a href=\"https://codex.wordpress.org/Function_Reference/get_post_types\" rel=\"nofollow\"><code>get_post_types()</code></a> which <strong>does</strong> have some arguments to exclude built-in post types but for this example we will get everything. Once we've gotten our post types we can create an exclude array and <a href=\"http://php.net/manual/en/function.array-diff.php\" rel=\"nofollow\"><code>array_diff()</code></a>, here's what it looks like:</p>\n\n<pre><code>function search_post_types( $query ) {\n if( is_admin() ) {\n return $query;\n }\n\n if ( $query-&gt;is_search &amp;&amp; $query-&gt;is_main_query() ) {\n $post_types = get_post_types( array(), 'names' ); // With no arguments, this should never be empty\n if( ! empty( $post_types ) ) { // But let's check just to be safe!\n $pt_exclude = array( 'attachment', 'revision', 'nav_menu_item' );\n $pt_include = array_diff( $post_types, $pt_exclude );\n\n $query-&gt;set( 'post_type', $pt_include );\n }\n }\n}\nadd_action( 'pre_get_posts', 'search_post_types' );\n</code></pre>\n" }, { "answer_id": 185697, "author": "codecowboy", "author_id": 500, "author_profile": "https://wordpress.stackexchange.com/users/500", "pm_score": 0, "selected": false, "text": "<p>One option is to use the pre_get_posts hook and check that the query is a search query:</p>\n\n<pre><code>function my_theme_pre_get_posts( WP_Query $query ) {\n if ( $query-&gt;is_search ) {\n ...\n }\n\n return $query;\n}\n\nadd_filter( 'pre_get_posts', 'my_theme_pre_get_posts' );\n</code></pre>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/500/" ]
I am aware of the option to set `exclude_from_search => 'true'` when registering a custom post type. But what are the other options?
You can use the [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) hook. Do note though, this hook filters the query on both the front-end and admin. For example, we could do something like this: ``` function search_post_types( $query ) { if( is_admin() ) { return $query; } if ( $query->is_search && $query->is_main_query() ) { $query->set( 'post_type', array( 'post', 'page' ) ); } } add_action( 'pre_get_posts', 'search_post_types' ); ``` I'm not sure there's a way to *exclude* it using `pre_get_posts` but more along the lines of include specific post types only, in the example above I'm only including Posts and Pages, nothing else. --- Another method is to get *all* post types and create an array of post types we actually want to exclude. First we use the function [`get_post_types()`](https://codex.wordpress.org/Function_Reference/get_post_types) which **does** have some arguments to exclude built-in post types but for this example we will get everything. Once we've gotten our post types we can create an exclude array and [`array_diff()`](http://php.net/manual/en/function.array-diff.php), here's what it looks like: ``` function search_post_types( $query ) { if( is_admin() ) { return $query; } if ( $query->is_search && $query->is_main_query() ) { $post_types = get_post_types( array(), 'names' ); // With no arguments, this should never be empty if( ! empty( $post_types ) ) { // But let's check just to be safe! $pt_exclude = array( 'attachment', 'revision', 'nav_menu_item' ); $pt_include = array_diff( $post_types, $pt_exclude ); $query->set( 'post_type', $pt_include ); } } } add_action( 'pre_get_posts', 'search_post_types' ); ```
185,699
<p>i have a field called bookname and based on the entry in that i am trying to check the <code>posttype = books</code> and pull out the logoid when the bookname matchs but for some reason <code>get_post_thumbnail_id</code> doesn't pull out the id of the image even when its present hence doesn't set the image.</p> <pre><code>$importbookname = get_field( 'bookname' ); $allbookposts = get_posts( array( 'post_type' =&gt; 'books', 'numberposts' =&gt; -1 ) ); if( ! empty( $allbookposts ) ) { foreach( $allbookposts as $importbookpost ) { $tempbookname = strip_tags( get_the_title( $importbookpost ) ); if( $tempbookname == $importbookname ) { $importbookcoverid = get_post_thumbnail_id( $importbookpost ); } } unset( $importbookpost ); set_post_thumbnail( $post_id, $importbookcoverid ); } </code></pre>
[ { "answer_id": 185700, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 3, "selected": true, "text": "<p>You need to call <code>get_post_thumbnail_id()</code> with the <code>ID</code> of the post, not the post object.</p>\n\n<pre><code>$importbookcoverid = get_post_thumbnail_id( $importbookpost-&gt;ID );\n</code></pre>\n\n<p>and you should be fine.</p>\n" }, { "answer_id": 185701, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>You are passing the complete post object to <a href=\"https://codex.wordpress.org/Function_Reference/get_post_thumbnail_id\" rel=\"nofollow\"><code>get_post_thumbnail_id()</code></a> where as you should use just the post ID. You should also setup post data before using template tags</p>\n\n<p>Please see <a href=\"https://codex.wordpress.org/Class_Reference/WP_Post\" rel=\"nofollow\"><code>WP_Post</code></a> to see all the available properties you can use in the post object</p>\n\n<pre><code>foreach( $allbookposts as $post ) {\n setup_postdata( $post );\n $tempbookname = strip_tags( get_the_title() );\n\n if( $tempbookname == $importbookname ) { \n $importbookcoverid = get_post_thumbnail_id( $post-&gt;ID ); \n }\n}\nwp_reset_postdata();\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Was a bit to fast, you don't need to pass the post ID to <code>get_the_title()</code></p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50113/" ]
i have a field called bookname and based on the entry in that i am trying to check the `posttype = books` and pull out the logoid when the bookname matchs but for some reason `get_post_thumbnail_id` doesn't pull out the id of the image even when its present hence doesn't set the image. ``` $importbookname = get_field( 'bookname' ); $allbookposts = get_posts( array( 'post_type' => 'books', 'numberposts' => -1 ) ); if( ! empty( $allbookposts ) ) { foreach( $allbookposts as $importbookpost ) { $tempbookname = strip_tags( get_the_title( $importbookpost ) ); if( $tempbookname == $importbookname ) { $importbookcoverid = get_post_thumbnail_id( $importbookpost ); } } unset( $importbookpost ); set_post_thumbnail( $post_id, $importbookcoverid ); } ```
You need to call `get_post_thumbnail_id()` with the `ID` of the post, not the post object. ``` $importbookcoverid = get_post_thumbnail_id( $importbookpost->ID ); ``` and you should be fine.
185,729
<p>So I have a page (ex. site.com/start) where I want to show a login page (ex. site.com/start/login) if not logged in, in order to view the page.</p> <p>Without using any plugin, what would be the condition logic which if user visits <code>/start</code> page, while they are not not logged in, then the user is redirected to <code>/start/login</code> page instead?</p> <p>Thanks.</p>
[ { "answer_id": 185730, "author": "jrothafer", "author_id": 71024, "author_profile": "https://wordpress.stackexchange.com/users/71024", "pm_score": 2, "selected": true, "text": "<p>In a template file, this should do it:</p>\n\n<pre><code>&lt;php\nIf (!is_user_logged_in())\n{\n wp_redirect( \"start/login\" );\n exit();\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 185738, "author": "Ben Cole", "author_id": 32532, "author_profile": "https://wordpress.stackexchange.com/users/32532", "pm_score": 0, "selected": false, "text": "<p>If the login page you want to send visitors to is the regular WordPress login page, then you can use the built in <code>auth_redirect</code> function. Put this code at the top of your template file:</p>\n\n<pre><code>&lt;?php auth_redirect(); ?&gt;\n</code></pre>\n\n<p>This code will do the following:</p>\n\n<p><strong>If user is logged out</strong></p>\n\n<ol>\n<li>Redirect the user to the default login page of WordPress.</li>\n<li>After login, redirects the user back to the current page. </li>\n</ol>\n\n<p><strong>If user is logged in</strong></p>\n\n<ul>\n<li>Page renders as normal, no login redirect. </li>\n</ul>\n\n<p>More documentation: <a href=\"https://codex.wordpress.org/Function_Reference/auth_redirect\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/auth_redirect</a></p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185729", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So I have a page (ex. site.com/start) where I want to show a login page (ex. site.com/start/login) if not logged in, in order to view the page. Without using any plugin, what would be the condition logic which if user visits `/start` page, while they are not not logged in, then the user is redirected to `/start/login` page instead? Thanks.
In a template file, this should do it: ``` <php If (!is_user_logged_in()) { wp_redirect( "start/login" ); exit(); } ?> ```
185,731
<p>What I am trying to achieve is the following: for every user on our website, I want to do an API request to a service (local REST API interacting with another database) once and then cache the result in the WP_User (sub)class until the user will logout and login again (as this value is used on every page in the application once so otherwise it would have to be retrieved once for every page load, which is very undesirable performance-wise).</p> <p>The most elegant way in terms of Separation of Concerns I have found up until now, is done by extending (subclassing) the WP_User class as per example featured in the O'Reilly book <em>Building Web Apps with WordPress By Brian Messenlehner &amp; Jason Coleman</em>.</p> <p>The example code can be seen here: <a href="https://github.com/bwawwp/bwawwp/blob/6d42186c39e629b8744bfd4f3a596f6fbf63cee8/chapter-06/example-24.php" rel="nofollow noreferrer">see this file on the author's GitHub</a>.</p> <p>The problem however is, that we still do not have this Student (extends WP_User, so subclass) available in our code, we still need to instantiate it in the following way to get one Student instance for the current user:</p> <pre><code>$student = new Student($current_user-&gt;ID); </code></pre> <p>If we do that on a page, the instance will always be created again (hence me referring to the lifecycle in the title) and the call to <code>$student-&gt;assignments</code> seems to never be cached inside the <code>WP_User</code> subclass itself after navigating to a new page and/or reloading the page, so for every page load we are hitting the API and database which will probably never perform in our high-traffic production environment.</p> <p>The <code>$current_user</code> global variable within WordPress itself however (which is an <code>WP_User</code> instance) seems to be created directly after logging in and is then available throughout the whole application as far as my understanding goes. What I really want, is the same availability throughout the application but then for my subclass (Student) instead of the <code>WP_User</code> class, but more importantly, I want to make sure that for every logged in user, the API hit is only done once (just like for <code>$current_user-&gt;user_login</code> which is in <code>WP_User</code> for example).</p> <p>I have also looked into adding <code>user_meta</code> to <code>WP_User</code>, and checked out this question related to it which seemed partially helpful: <a href="https://wordpress.stackexchange.com/questions/72264/does-wordpress-cache-get-user-meta-results">Does WordPress cache get_user_meta() results?</a></p> <p>However, this is retrieved through <code>wp_cache_get</code> which is WordPress Object Cache which clearly states:</p> <ol> <li>Non-persistent cache is available only during the loading of the current page; once the next page loads, it will be blank once again.</li> <li>The storage size is limited by the total available memory for PHP on the server. Do not store large data sets, or you might end up with an “Out of memory” message.</li> <li>Using this type of cache makes sense only for operations repeated more than once in the creation of a page.</li> </ol> <p>We are not using the values in the Student subclass more than once in the creation of the page, however, the value is used on every page in the application once so it would have to be retrieved once for every page load.</p> <p>Am I just thinking in the wrong direction here, or how would this be possible within WordPress? I really need a good long-term solution here which should perform in a high-traffic production environment. Thanks for all input and help in advance!</p>
[ { "answer_id": 240033, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>Your question is a bit broad, but the main issue seems to be that for every new student you want to approach an external API, <em>only once</em>.</p>\n\n<p>To do this you must hook into <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_user/\" rel=\"nofollow\"><code>wp_insert_user</code></a>, which is the core function that registers a new user. By definition this function is only called once for every new user. At the end of this function you see a hook <a href=\"https://developer.wordpress.org/reference/hooks/user_register/\" rel=\"nofollow\"><code>user_register</code></a>, which is where you can approach the API.</p>\n\n<pre><code>add_action ('user_register','wpse185731_approach_api');\nfunction wpse185731_approach_api ($user_id) {\n $userdata = get_userdata( $user_id );\n if ( some condition based on $userdata) {\n ... approach API with $userdata, then store with:\n add_user_meta( $user_id, $meta_key, $meta_value, $unique );\n }\n }\n</code></pre>\n\n<p>You would probably want to do this in a plugin, not in your theme.</p>\n" }, { "answer_id": 296710, "author": "JBoulhous", "author_id": 137648, "author_profile": "https://wordpress.stackexchange.com/users/137648", "pm_score": 1, "selected": false, "text": "<p>If I did understand well, we need to cache a value retrieved from another REST service, from the login to logout of the user on the wordpress installation, so we will hook into this <code>wp_login</code> to get the value and cache it using <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">Transient API</a>, <a href=\"https://codex.wordpress.org/Options_API\" rel=\"nofollow noreferrer\">Options API</a> or a <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache#Persistent_Caching\" rel=\"nofollow noreferrer\">persistent caching</a> plugin. </p>\n\n<pre><code>add_action('wp_login', 'my_get_and_cache_rest_value');\nfunction my_get_and_cache_rest_value ($user_login, $user) {\n // do your rest call\n // cache it using Transient API, Options API or a persistent caching plugin\n}\n</code></pre>\n\n<p>We can then extend the <code>WP_User</code> object and set a our magic calls to get the data we want from the cache.</p>\n\n<pre><code>class MY_User extends WP_User {\n // no constructor so WP_User's constructor is used\n\n // method to get cached data\n function getMyCachedData() {\n // get data via my cache solution\n if ( ! isset( $this-&gt;data-&gt;myData ) )\n $this-&gt;data-&gt;myData = my_get_cached_data( $this-&gt;ID );\n\n return $this-&gt;data-&gt;myData;\n }\n\n // magic method to detect $user-&gt;my_data\n function __get( $key ) {\n if ( $key == 'my_data' )\n {\n return $this-&gt;getMyCachedData();\n }\n else\n {\n // fallback to default WP_User magic method\n return parent::__get( $key );\n }\n } \n}\n</code></pre>\n\n<p>I hope this would help someone, and cheers to @Daniel.</p>\n" }, { "answer_id": 313167, "author": "Matthew Clark", "author_id": 97094, "author_profile": "https://wordpress.stackexchange.com/users/97094", "pm_score": 0, "selected": false, "text": "<p>What follows doesn't answer the entire question, but it does address this part:</p>\n\n<blockquote>\n <p>@Daniel: The <code>$current_user</code> global variable... is then available throughout the whole application as far as my understanding goes. What I really want, is the same availability throughout the application...</p>\n</blockquote>\n\n<p>I had a similar need, and this is what I came up with.</p>\n\n<p>There is a <code>set_current_user</code> hook (within the <a href=\"https://developer.wordpress.org/reference/functions/wp_set_current_user/\" rel=\"nofollow noreferrer\">wp_set_current_user()</a> function), and because the <code>$current_user</code> global variable is set to an instance of WP_User by the time the action is fired, you can use this hook to \"do stuff\" to it.</p>\n\n<p>Calls to <a href=\"https://developer.wordpress.org/reference/functions/_wp_get_current_user/\" rel=\"nofollow noreferrer\">wp_get_current_user()</a> basically return the value of the global <code>$current_user</code>, but could end up calling <code>wp_set_current_user()</code> under certain conditions, which will cause your custom action to fire.</p>\n\n<p>So, in a custom plugin (I don't think this would work in a theme function.php file), you can define an action:</p>\n\n<pre><code>add_action( 'set_current_user', 'extend_current_user', PHP_INT_MAX );\n</code></pre>\n\n<p>And then your action can overwrite the global <code>$current_user</code>:</p>\n\n<pre><code>public function extend_current_user()\n{\n global $current_user;\n\n if( $current_user-&gt;ID == 0 )\n return;\n\n $current_user = new Student( $current_user-&gt;ID );\n}\n</code></pre>\n\n<p>Your Student class could then implement the <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">Transient API</a> to cache the RESTful data and offer methods or properties that will expose that data. And because the global <code>$current_user</code> will stay as an instance of Student, those methods/properties will always be available from <code>wp_get_current_user()</code> anytime you need them.</p>\n\n<p>Of course, by doing this, a <a href=\"https://en.wikipedia.org/wiki/Defensive_programming\" rel=\"nofollow noreferrer\">defensive programmer</a> will want to verify that any call to <code>wp_get_current_user()</code> does return an instance of Student before calling any methods on it.</p>\n" } ]
2015/04/28
[ "https://wordpress.stackexchange.com/questions/185731", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71349/" ]
What I am trying to achieve is the following: for every user on our website, I want to do an API request to a service (local REST API interacting with another database) once and then cache the result in the WP\_User (sub)class until the user will logout and login again (as this value is used on every page in the application once so otherwise it would have to be retrieved once for every page load, which is very undesirable performance-wise). The most elegant way in terms of Separation of Concerns I have found up until now, is done by extending (subclassing) the WP\_User class as per example featured in the O'Reilly book *Building Web Apps with WordPress By Brian Messenlehner & Jason Coleman*. The example code can be seen here: [see this file on the author's GitHub](https://github.com/bwawwp/bwawwp/blob/6d42186c39e629b8744bfd4f3a596f6fbf63cee8/chapter-06/example-24.php). The problem however is, that we still do not have this Student (extends WP\_User, so subclass) available in our code, we still need to instantiate it in the following way to get one Student instance for the current user: ``` $student = new Student($current_user->ID); ``` If we do that on a page, the instance will always be created again (hence me referring to the lifecycle in the title) and the call to `$student->assignments` seems to never be cached inside the `WP_User` subclass itself after navigating to a new page and/or reloading the page, so for every page load we are hitting the API and database which will probably never perform in our high-traffic production environment. The `$current_user` global variable within WordPress itself however (which is an `WP_User` instance) seems to be created directly after logging in and is then available throughout the whole application as far as my understanding goes. What I really want, is the same availability throughout the application but then for my subclass (Student) instead of the `WP_User` class, but more importantly, I want to make sure that for every logged in user, the API hit is only done once (just like for `$current_user->user_login` which is in `WP_User` for example). I have also looked into adding `user_meta` to `WP_User`, and checked out this question related to it which seemed partially helpful: [Does WordPress cache get\_user\_meta() results?](https://wordpress.stackexchange.com/questions/72264/does-wordpress-cache-get-user-meta-results) However, this is retrieved through `wp_cache_get` which is WordPress Object Cache which clearly states: 1. Non-persistent cache is available only during the loading of the current page; once the next page loads, it will be blank once again. 2. The storage size is limited by the total available memory for PHP on the server. Do not store large data sets, or you might end up with an “Out of memory” message. 3. Using this type of cache makes sense only for operations repeated more than once in the creation of a page. We are not using the values in the Student subclass more than once in the creation of the page, however, the value is used on every page in the application once so it would have to be retrieved once for every page load. Am I just thinking in the wrong direction here, or how would this be possible within WordPress? I really need a good long-term solution here which should perform in a high-traffic production environment. Thanks for all input and help in advance!
If I did understand well, we need to cache a value retrieved from another REST service, from the login to logout of the user on the wordpress installation, so we will hook into this `wp_login` to get the value and cache it using [Transient API](https://codex.wordpress.org/Transients_API), [Options API](https://codex.wordpress.org/Options_API) or a [persistent caching](https://codex.wordpress.org/Class_Reference/WP_Object_Cache#Persistent_Caching) plugin. ``` add_action('wp_login', 'my_get_and_cache_rest_value'); function my_get_and_cache_rest_value ($user_login, $user) { // do your rest call // cache it using Transient API, Options API or a persistent caching plugin } ``` We can then extend the `WP_User` object and set a our magic calls to get the data we want from the cache. ``` class MY_User extends WP_User { // no constructor so WP_User's constructor is used // method to get cached data function getMyCachedData() { // get data via my cache solution if ( ! isset( $this->data->myData ) ) $this->data->myData = my_get_cached_data( $this->ID ); return $this->data->myData; } // magic method to detect $user->my_data function __get( $key ) { if ( $key == 'my_data' ) { return $this->getMyCachedData(); } else { // fallback to default WP_User magic method return parent::__get( $key ); } } } ``` I hope this would help someone, and cheers to @Daniel.
185,747
<p>I'm getting this error at the top of my wordpress site:</p> <blockquote> <p>Notice: Use of undefined constant SCRIPT_DEBUG - assumed 'SCRIPT_DEBUG' in /[wordpress path]/wp-includes/formatting.php on line 4144</p> </blockquote> <p>No idea where it came from, any ideas what started causing this?</p> <p>Using version 4.2.1</p>
[ { "answer_id": 185945, "author": "Frederik Spang", "author_id": 25242, "author_profile": "https://wordpress.stackexchange.com/users/25242", "pm_score": 4, "selected": true, "text": "<p>This is a <a href=\"https://core.trac.wordpress.org/ticket/32118?cversion=0&amp;cnum_hist=10\" rel=\"nofollow\">known bug</a></p>\n\n<p>As far as I'm concerned, you can easily fix it by replacing </p>\n\n<pre><code>if ( SCRIPT_DEBUG ) {\n</code></pre>\n\n<p>with </p>\n\n<pre><code>if ( defined('SCRIPT_DEBUG') &amp;&amp; SCRIPT_DEBUG ) {\n</code></pre>\n\n<p>That should suppress the error for now.</p>\n\n<p>When Wordpress is updated again, this error may be overwritten, but I believe it will be fixed in the next update.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Fixed at build 32482.</p>\n" }, { "answer_id": 186270, "author": "Eric Willis", "author_id": 71616, "author_profile": "https://wordpress.stackexchange.com/users/71616", "pm_score": 2, "selected": false, "text": "<p>If you don't wish to modify your core wordpress files to fix the issue, you can simply add the missing definition into your <code>wp.config.php</code> file.</p>\n\n<p>Something like: \n<code>\n define('SCRIPT_DEBUG', true);\n</code></p>\n\n<p>Would remove the error.</p>\n\n<p>There is already a <code>WP_DEBUG</code> definition in there already so I would suggest putting it close to that.</p>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185747", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71358/" ]
I'm getting this error at the top of my wordpress site: > > Notice: Use of undefined constant SCRIPT\_DEBUG - assumed 'SCRIPT\_DEBUG' in /[wordpress path]/wp-includes/formatting.php on line 4144 > > > No idea where it came from, any ideas what started causing this? Using version 4.2.1
This is a [known bug](https://core.trac.wordpress.org/ticket/32118?cversion=0&cnum_hist=10) As far as I'm concerned, you can easily fix it by replacing ``` if ( SCRIPT_DEBUG ) { ``` with ``` if ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) { ``` That should suppress the error for now. When Wordpress is updated again, this error may be overwritten, but I believe it will be fixed in the next update. **UPDATE** Fixed at build 32482.
185,753
<p>I have a curly problem I've been working on for some time. At first it appears as if the get_body_class() function was broken but after I removed it from the template the issue persists.</p> <pre><code>&lt;html class=&quot;js firefox&quot;&gt; &lt;head&gt; &lt;body&gt; &lt;body&gt; &lt;div class=&quot;top_div&quot;&gt; &lt;div id=&quot;page&quot; class=&quot;hfeed site logo&quot;&gt; &lt;div id=&quot;page&quot; class=&quot;hfeed site&quot;&gt; &lt;div class=&quot;footer_wrapper&quot;&gt; &lt;/body&gt; </code></pre> <p>Yet when I view the same via page source I see only one body tag.</p> <p>I am using the latest version of Wordpress and all plugins are up to date.</p> <p>Things I have tried to resolve the issue:</p> <ul> <li>Disabling all plugins</li> <li>Changing to default theme</li> <li>Replacing the wp-admin folder</li> <li>Forcing UTF-8 without BOM encoding on all PHP files</li> </ul> <p>Note that if I completely remove the body tag from the header.php file I only see a single body tag in Firebug and in page source I see the following:</p> <p><img src="https://i.stack.imgur.com/ypuBH.png" alt="pagesource screenshot" /></p>
[ { "answer_id": 185945, "author": "Frederik Spang", "author_id": 25242, "author_profile": "https://wordpress.stackexchange.com/users/25242", "pm_score": 4, "selected": true, "text": "<p>This is a <a href=\"https://core.trac.wordpress.org/ticket/32118?cversion=0&amp;cnum_hist=10\" rel=\"nofollow\">known bug</a></p>\n\n<p>As far as I'm concerned, you can easily fix it by replacing </p>\n\n<pre><code>if ( SCRIPT_DEBUG ) {\n</code></pre>\n\n<p>with </p>\n\n<pre><code>if ( defined('SCRIPT_DEBUG') &amp;&amp; SCRIPT_DEBUG ) {\n</code></pre>\n\n<p>That should suppress the error for now.</p>\n\n<p>When Wordpress is updated again, this error may be overwritten, but I believe it will be fixed in the next update.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Fixed at build 32482.</p>\n" }, { "answer_id": 186270, "author": "Eric Willis", "author_id": 71616, "author_profile": "https://wordpress.stackexchange.com/users/71616", "pm_score": 2, "selected": false, "text": "<p>If you don't wish to modify your core wordpress files to fix the issue, you can simply add the missing definition into your <code>wp.config.php</code> file.</p>\n\n<p>Something like: \n<code>\n define('SCRIPT_DEBUG', true);\n</code></p>\n\n<p>Would remove the error.</p>\n\n<p>There is already a <code>WP_DEBUG</code> definition in there already so I would suggest putting it close to that.</p>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185753", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20547/" ]
I have a curly problem I've been working on for some time. At first it appears as if the get\_body\_class() function was broken but after I removed it from the template the issue persists. ``` <html class="js firefox"> <head> <body> <body> <div class="top_div"> <div id="page" class="hfeed site logo"> <div id="page" class="hfeed site"> <div class="footer_wrapper"> </body> ``` Yet when I view the same via page source I see only one body tag. I am using the latest version of Wordpress and all plugins are up to date. Things I have tried to resolve the issue: * Disabling all plugins * Changing to default theme * Replacing the wp-admin folder * Forcing UTF-8 without BOM encoding on all PHP files Note that if I completely remove the body tag from the header.php file I only see a single body tag in Firebug and in page source I see the following: ![pagesource screenshot](https://i.stack.imgur.com/ypuBH.png)
This is a [known bug](https://core.trac.wordpress.org/ticket/32118?cversion=0&cnum_hist=10) As far as I'm concerned, you can easily fix it by replacing ``` if ( SCRIPT_DEBUG ) { ``` with ``` if ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) { ``` That should suppress the error for now. When Wordpress is updated again, this error may be overwritten, but I believe it will be fixed in the next update. **UPDATE** Fixed at build 32482.
185,755
<p>I'm trying to display a texts with functions on my page. Please find the code below. I'm not getting the output I want. </p> <pre><code>&lt;?php $content = the_content(); ?&gt; &lt;?php printf(__('Output : %1$s', 'theme'), $content); ?&gt; </code></pre> <p>Which Outputs : </p> <pre><code>Foo Output : </code></pre> <p>I need my output to be like this :</p> <pre><code>Output : Foo </code></pre> <hr> <p>Answer from Kim Christensen :</p> <pre><code>&lt;?php $content = get_the_content(); ?&gt; &lt;?php printf(__('Output : %1$s', 'theme'), $content); ?&gt; </code></pre> <p>Works perfectly :</p> <pre><code>Output : Foo </code></pre> <hr> <p>Answer from Pieter Goosen :</p> <pre><code>&lt;?php $content = apply_filters( 'the_content', get_the_content() ); ?&gt; &lt;?php printf(__('Output : %1$s', 'theme'), $content); ?&gt; </code></pre> <p>It pushes my content below :</p> <pre><code>Output : Foo </code></pre>
[ { "answer_id": 185761, "author": "Kim Christensen", "author_id": 71367, "author_profile": "https://wordpress.stackexchange.com/users/71367", "pm_score": 2, "selected": false, "text": "<p>You want to use <code>get_the_content()</code>, \n<code>the_content()</code> prints the content.</p>\n\n<p><code>get_the_content()</code> will be assigned to your variable.</p>\n" }, { "answer_id": 185762, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 1, "selected": false, "text": "<p>Kim is correct. </p>\n\n<p><code>get_the_content()</code> displays your intended result.</p>\n\n<pre><code>&lt;?php $content = get_the_content(); \nprintf(\"Output: %1$s\", $content); ?&gt;\n</code></pre>\n" }, { "answer_id": 185763, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p><code>the_content()</code> prints it output to screen. What you want is to return that output and assign a variable to it.</p>\n\n<p>You should note, although <code>get_the_content()</code> do exactly what you want, it only returns unfiltered content, and not filtered content like <code>the_content()</code>. You should manually add those filters, which is real easy. </p>\n\n<p>You can do the following</p>\n\n<pre><code>$content = apply_filters( 'the_content', get_the_content() );\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>It seems the above approach pushes the content part to the next line when the filters are applied to <code>get_the_content()</code>. </p>\n\n<p>A work around here would be to concatenate <code>Output :</code> to <code>get_the_content()</code> and then applying the content filters to that</p>\n\n<pre><code>&lt;?php $content = apply_filters( 'the_content', 'Output :' . get_the_content() ); ?&gt;\n&lt;?php printf(__( '%1$s', 'theme'), $content); ?&gt;\n</code></pre>\n\n<p>would give you what you need </p>\n" }, { "answer_id": 185769, "author": "Devendra Sharma", "author_id": 70571, "author_profile": "https://wordpress.stackexchange.com/users/70571", "pm_score": -1, "selected": false, "text": "<p>Another approach:</p>\n\n<pre><code>ob_start();\nthe_content();\n$content = ob_get_clean();\n</code></pre>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26988/" ]
I'm trying to display a texts with functions on my page. Please find the code below. I'm not getting the output I want. ``` <?php $content = the_content(); ?> <?php printf(__('Output : %1$s', 'theme'), $content); ?> ``` Which Outputs : ``` Foo Output : ``` I need my output to be like this : ``` Output : Foo ``` --- Answer from Kim Christensen : ``` <?php $content = get_the_content(); ?> <?php printf(__('Output : %1$s', 'theme'), $content); ?> ``` Works perfectly : ``` Output : Foo ``` --- Answer from Pieter Goosen : ``` <?php $content = apply_filters( 'the_content', get_the_content() ); ?> <?php printf(__('Output : %1$s', 'theme'), $content); ?> ``` It pushes my content below : ``` Output : Foo ```
`the_content()` prints it output to screen. What you want is to return that output and assign a variable to it. You should note, although `get_the_content()` do exactly what you want, it only returns unfiltered content, and not filtered content like `the_content()`. You should manually add those filters, which is real easy. You can do the following ``` $content = apply_filters( 'the_content', get_the_content() ); ``` EDIT ---- It seems the above approach pushes the content part to the next line when the filters are applied to `get_the_content()`. A work around here would be to concatenate `Output :` to `get_the_content()` and then applying the content filters to that ``` <?php $content = apply_filters( 'the_content', 'Output :' . get_the_content() ); ?> <?php printf(__( '%1$s', 'theme'), $content); ?> ``` would give you what you need
185,781
<p>I want to show related posts, with the same taxonomy (artists) as the current post. In the related post I don't want the current post to appear.</p> <p>I am also using a custom post type. (sculptures)</p> <p>This is the code I am using below, but it is showing the current post in the related post and all post not only those with the taxonomy (artists)</p> <p>Does anyone have a solution</p> <pre><code>&lt;div class="related-posts"&gt; &lt;h3 class="widget-title"&gt;Related Posts&lt;/h3&gt; &lt;ul&gt; &lt;?php $query = new WP_Query(array('post_type' =&gt; 'sculptures', 'artist' =&gt; get_the_term_list( $post-&gt;taxonomies, 'artist' ))); while ($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt; &lt;div class="related-thumb"&gt;&lt;a href="&lt;? the_permalink()?&gt;" rel="bookmark" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_post_thumbnail('medium'); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;?php endwhile; wp_reset_query(); ?&gt; </code></pre> <p></p> <p></p>
[ { "answer_id": 185764, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 2, "selected": true, "text": "<p>Yes, the categories are stored in <code>wp_terms</code> table which contains the term_id, name and slug. Deleting the category in admin panel removes the three values along with it.</p>\n" }, { "answer_id": 185768, "author": "Devendra Sharma", "author_id": 70571, "author_profile": "https://wordpress.stackexchange.com/users/70571", "pm_score": 0, "selected": false, "text": "<p>Sure, When you create categories,WordPress inserts detail in two tables <strong>WP_terms</strong> and <strong>WP_term_taxonomy</strong> .So when you delete category all entries does deleted. </p>\n\n<pre><code>if you assign any post of that category.all post are automatically assign **uncategory**\n</code></pre>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185781", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66373/" ]
I want to show related posts, with the same taxonomy (artists) as the current post. In the related post I don't want the current post to appear. I am also using a custom post type. (sculptures) This is the code I am using below, but it is showing the current post in the related post and all post not only those with the taxonomy (artists) Does anyone have a solution ``` <div class="related-posts"> <h3 class="widget-title">Related Posts</h3> <ul> <?php $query = new WP_Query(array('post_type' => 'sculptures', 'artist' => get_the_term_list( $post->taxonomies, 'artist' ))); while ($query->have_posts()) : $query->the_post(); ?> <div class="related-thumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail('medium'); ?></a></div> <?php endwhile; wp_reset_query(); ?> ```
Yes, the categories are stored in `wp_terms` table which contains the term\_id, name and slug. Deleting the category in admin panel removes the three values along with it.
185,800
<p>I'm trying to make WordPress theme with the materialize framework but I'm really confused by the navbar part. I've searched on the internet but found nothing, it seems nobody works with materialize.</p> <p>The only thing that I have found is to make it with nav_walker, like it is done in bootstrap but I don't know how to do it with materialize.</p> <p><strong>UPDATE:</strong></p> <p>Here is my navbar code;</p> <pre><code> &lt;div class="navbar"&gt; &lt;nav&gt; &lt;div class="nav-wrapper"&gt; &lt;a href="&lt;?php bloginfo('url'); ?&gt;" class="brand-logo"&gt;&lt;?php bloginfo('title'); ?&gt;&lt;/a&gt; &lt;a href="#" data-activates="mobile-demo" class="button-collapse"&gt;&lt;i class="mdi-navigation-menu"&gt;&lt;/i&gt;&lt;/a&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'top-menu', 'items_wrap' =&gt; '&lt;ul class="right hide-on-med-and-down"&gt;%3$s&lt;/ul&gt;' ) ); ?&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'top-menu', 'items_wrap' =&gt; '&lt;ul class="side-nav" id="mobile-demo"&gt;%3$s&lt;/ul&gt;' ) ); ?&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; </code></pre> <p>PS: now would show menu but has these issues:</p> <ol> <li>drop-down menu not works.</li> <li>menu items are not linked.</li> <li>when try to make drop-down menu in wp-admin after save again items jump's out of parent items!.</li> <li>after create menu all notes will be clear!</li> </ol>
[ { "answer_id": 185764, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 2, "selected": true, "text": "<p>Yes, the categories are stored in <code>wp_terms</code> table which contains the term_id, name and slug. Deleting the category in admin panel removes the three values along with it.</p>\n" }, { "answer_id": 185768, "author": "Devendra Sharma", "author_id": 70571, "author_profile": "https://wordpress.stackexchange.com/users/70571", "pm_score": 0, "selected": false, "text": "<p>Sure, When you create categories,WordPress inserts detail in two tables <strong>WP_terms</strong> and <strong>WP_term_taxonomy</strong> .So when you delete category all entries does deleted. </p>\n\n<pre><code>if you assign any post of that category.all post are automatically assign **uncategory**\n</code></pre>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71384/" ]
I'm trying to make WordPress theme with the materialize framework but I'm really confused by the navbar part. I've searched on the internet but found nothing, it seems nobody works with materialize. The only thing that I have found is to make it with nav\_walker, like it is done in bootstrap but I don't know how to do it with materialize. **UPDATE:** Here is my navbar code; ``` <div class="navbar"> <nav> <div class="nav-wrapper"> <a href="<?php bloginfo('url'); ?>" class="brand-logo"><?php bloginfo('title'); ?></a> <a href="#" data-activates="mobile-demo" class="button-collapse"><i class="mdi-navigation-menu"></i></a> <?php wp_nav_menu( array( 'theme_location' => 'top-menu', 'items_wrap' => '<ul class="right hide-on-med-and-down">%3$s</ul>' ) ); ?> <?php wp_nav_menu( array( 'theme_location' => 'top-menu', 'items_wrap' => '<ul class="side-nav" id="mobile-demo">%3$s</ul>' ) ); ?> </div> </nav> </div> ``` PS: now would show menu but has these issues: 1. drop-down menu not works. 2. menu items are not linked. 3. when try to make drop-down menu in wp-admin after save again items jump's out of parent items!. 4. after create menu all notes will be clear!
Yes, the categories are stored in `wp_terms` table which contains the term\_id, name and slug. Deleting the category in admin panel removes the three values along with it.
185,839
<p>I've tried this on a fresh install on the twentyfifteen theme. I'm adding a metabox to pages which allows uploads - Whenever I upload a file on a new Page it uploads the file but also adds another file to the media library with the <code>post_id</code> as the name. It then saves the phantom ID as post meta. If I publish the post <em>first</em> then upload the file everything works as expected.</p> <p>Here's my <code>save_post</code> hook, the code below is minimalistic with no validation just to replicate the issue.</p> <pre><code>/** * Save Metaboxes * @param int $post_id */ function save_custom_meta_boxes( $post_id ) { // If we're not in the right place, bailout if( ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) || ! isset( $post_id ) || ! isset( $_POST['post_type'] ) || ! current_user_can( 'edit_post', $post_id ) ) { return; } if( isset( $_FILES['_uploaded_file'] ) &amp;&amp; ! empty( $_FILES['_uploaded_file']['name'] ) ) { require_once( ABSPATH . 'wp-admin/includes/image.php' ); $uploadStatus = wp_handle_upload( $_FILES['_uploaded_file'], array( 'test_form' =&gt; false ) ); $fileID = wp_insert_attachment( array( 'post_mime_type' =&gt; $uploadStatus['type'], 'post_title' =&gt; preg_replace( '/\.[^.]+$/', '', basename( $uploadStatus['file'] ) ), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit' ), $uploadStatus['file'], $post_id ); $attachmentData = wp_generate_attachment_metadata( $fileID, $uploadStatus['file'] ); wp_update_attachment_metadata( $fileID, $attachmentData ); update_post_meta( $post_id, '_uploaded_file', $fileID ); } } add_action( 'save_post', 'save_custom_meta_boxes' ); </code></pre> <p><strong>Metabox</strong> - Here's the display of the metabox.</p> <pre><code>/** `page_meta` Callback Function **/ function page_meta_cb( $post ) { wp_nonce_field( 'page_meta_metabox', 'page_meta_nonce' ); $uploaded_file_id = get_post_meta( $post-&gt;ID, '_uploaded_file', true ); ?&gt; &lt;table style="width:100%;"&gt; &lt;tbody&gt; &lt;tr id="uploaded_file"&gt; &lt;td style="width:8%;min-width:105px;"&gt; &lt;label for="uploaded_file_input" style="font-weight:bold;"&gt;Uploaded File&lt;/label&gt;&lt;br /&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="file" style="width:100%;" name="_uploaded_file" value="" id="uploaded_file_input" /&gt; &lt;?php if( is_numeric( $uploaded_file_id ) ) : ?&gt; &lt;div class="fileLink"&gt; &lt;a href="post.php?post=&lt;?php echo $uploaded_file_id; ?&gt;&amp;action=edit" target="_blank"&gt;Edit File - &lt;?php echo get_the_title( $uploaded_file_id ); ?&gt;&lt;/a&gt; &lt;br /&gt; &lt;br /&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;?php } // END Metabox </code></pre> <p>The media library looks like:</p> <p><img src="https://i.stack.imgur.com/9QlRe.jpg" alt="Phantom Upload in Media Library"></p> <p>Again, the issue is only when uploading to new posts - published posts have no problem with the upload. What can the issue be?</p>
[ { "answer_id": 185852, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>Part of your problem might be that while you create a nonce you don't really use it.</p>\n\n<p>You don't really need it to be a nonce, an hidden text input will be as good (yes, codex is wrong again ;) ). You use the hidden input as an indicator to when the save happened from the post edit screen, or technically when the meta box was displayed as part of the form. This should protect you when a user does a bulk edit and I assume that since revisions do not save meta values it should protect you for your specific problem.</p>\n" }, { "answer_id": 185859, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": true, "text": "<p>I've modified your code a little to check that the post type is a page, that the current user can edit that page, verify the nonce and verify the inserting attachment functions. The resulting code is working. It seems that don't checking the post type could be the reason of the issue. Also, you don't need to manually include 'wp-admin/includes/image.php':</p>\n\n<pre><code>add_filter('post_edit_form_tag', function() {\n echo ' enctype=\"multipart/form-data\"';\n});\n\nadd_action( 'save_post', 'save_custom_meta_boxes', 10, 2 );\nfunction save_custom_meta_boxes( $post_id, $post ) {\n\n // If we're not in the right place, bailout\n if( ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) || ! isset( $post_id ) || $post-&gt;post_type !== 'page' || ! current_user_can( 'edit_page', $post_id ) ) {\n return;\n }\n\n if ( !isset( $_POST['page_meta_nonce'] ) || ! wp_verify_nonce( $_POST['page_meta_nonce'], 'page_meta_metabox' ) ) {\n return;\n }\n\n if( ! empty( $_FILES['_uploaded_file']['name'] ) ) { \n $uploadStatus = wp_handle_upload( $_FILES['_uploaded_file'], array( 'test_form' =&gt; false ) );\n if ( $uploadStatus &amp;&amp; ! isset( $uploadStatus['error'] ) ) {\n $fileID = wp_insert_attachment( array(\n 'post_mime_type' =&gt; $uploadStatus['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $uploadStatus['file'] ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit'\n ),\n $uploadStatus['file'],\n $post_id\n );\n\n if( $fileID ) {\n $attachmentData = wp_generate_attachment_metadata( $fileID, $uploadStatus['file'] );\n wp_update_attachment_metadata( $fileID, $attachmentData );\n update_post_meta( $post_id, '_uploaded_file', $fileID );\n }\n }\n }\n}\n\nadd_action( 'add_meta_boxes_page', 'page_meta' );\nfunction page_meta() {\n add_meta_box(\"page_upload_image\", 'Upload image', 'page_meta_cb');\n}\n/** `page_meta` Callback Function **/\nfunction page_meta_cb( $post ) { \n wp_nonce_field( 'page_meta_metabox', 'page_meta_nonce' );\n $uploaded_file_id = get_post_meta( $post-&gt;ID, '_uploaded_file', true );\n ?&gt;\n\n &lt;div&gt;\n\n &lt;table style=\"width:100%;\"&gt;\n &lt;tbody&gt;\n &lt;tr id=\"uploaded_file\"&gt;\n &lt;td style=\"width:8%;min-width:105px;\"&gt;\n &lt;label for=\"uploaded_file_input\" style=\"font-weight:bold;\"&gt;Uploaded File&lt;/label&gt;&lt;br /&gt;\n &lt;/td&gt;\n &lt;td&gt;\n &lt;input type=\"file\" style=\"width:100%;\" name=\"_uploaded_file\" value=\"\" id=\"uploaded_file_input\" /&gt;\n\n &lt;?php if( is_numeric( $uploaded_file_id ) ) : ?&gt;\n\n &lt;div class=\"fileLink\"&gt;\n &lt;a href=\"post.php?post=&lt;?php echo $uploaded_file_id; ?&gt;&amp;action=edit\" target=\"_blank\"&gt;Edit File - &lt;?php echo get_the_title( $uploaded_file_id ); ?&gt;&lt;/a&gt;\n &lt;br /&gt;\n &lt;br /&gt;\n &lt;/div&gt;\n\n &lt;?php endif; ?&gt;\n\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n\n &lt;/div&gt;\n\n &lt;?php\n} // END Metabox\n</code></pre>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185839", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7355/" ]
I've tried this on a fresh install on the twentyfifteen theme. I'm adding a metabox to pages which allows uploads - Whenever I upload a file on a new Page it uploads the file but also adds another file to the media library with the `post_id` as the name. It then saves the phantom ID as post meta. If I publish the post *first* then upload the file everything works as expected. Here's my `save_post` hook, the code below is minimalistic with no validation just to replicate the issue. ``` /** * Save Metaboxes * @param int $post_id */ function save_custom_meta_boxes( $post_id ) { // If we're not in the right place, bailout if( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ! isset( $post_id ) || ! isset( $_POST['post_type'] ) || ! current_user_can( 'edit_post', $post_id ) ) { return; } if( isset( $_FILES['_uploaded_file'] ) && ! empty( $_FILES['_uploaded_file']['name'] ) ) { require_once( ABSPATH . 'wp-admin/includes/image.php' ); $uploadStatus = wp_handle_upload( $_FILES['_uploaded_file'], array( 'test_form' => false ) ); $fileID = wp_insert_attachment( array( 'post_mime_type' => $uploadStatus['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $uploadStatus['file'] ) ), 'post_content' => '', 'post_status' => 'inherit' ), $uploadStatus['file'], $post_id ); $attachmentData = wp_generate_attachment_metadata( $fileID, $uploadStatus['file'] ); wp_update_attachment_metadata( $fileID, $attachmentData ); update_post_meta( $post_id, '_uploaded_file', $fileID ); } } add_action( 'save_post', 'save_custom_meta_boxes' ); ``` **Metabox** - Here's the display of the metabox. ``` /** `page_meta` Callback Function **/ function page_meta_cb( $post ) { wp_nonce_field( 'page_meta_metabox', 'page_meta_nonce' ); $uploaded_file_id = get_post_meta( $post->ID, '_uploaded_file', true ); ?> <table style="width:100%;"> <tbody> <tr id="uploaded_file"> <td style="width:8%;min-width:105px;"> <label for="uploaded_file_input" style="font-weight:bold;">Uploaded File</label><br /> </td> <td> <input type="file" style="width:100%;" name="_uploaded_file" value="" id="uploaded_file_input" /> <?php if( is_numeric( $uploaded_file_id ) ) : ?> <div class="fileLink"> <a href="post.php?post=<?php echo $uploaded_file_id; ?>&action=edit" target="_blank">Edit File - <?php echo get_the_title( $uploaded_file_id ); ?></a> <br /> <br /> </div> <?php endif; ?> </td> </tr> </tbody> </table> <?php } // END Metabox ``` The media library looks like: ![Phantom Upload in Media Library](https://i.stack.imgur.com/9QlRe.jpg) Again, the issue is only when uploading to new posts - published posts have no problem with the upload. What can the issue be?
I've modified your code a little to check that the post type is a page, that the current user can edit that page, verify the nonce and verify the inserting attachment functions. The resulting code is working. It seems that don't checking the post type could be the reason of the issue. Also, you don't need to manually include 'wp-admin/includes/image.php': ``` add_filter('post_edit_form_tag', function() { echo ' enctype="multipart/form-data"'; }); add_action( 'save_post', 'save_custom_meta_boxes', 10, 2 ); function save_custom_meta_boxes( $post_id, $post ) { // If we're not in the right place, bailout if( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ! isset( $post_id ) || $post->post_type !== 'page' || ! current_user_can( 'edit_page', $post_id ) ) { return; } if ( !isset( $_POST['page_meta_nonce'] ) || ! wp_verify_nonce( $_POST['page_meta_nonce'], 'page_meta_metabox' ) ) { return; } if( ! empty( $_FILES['_uploaded_file']['name'] ) ) { $uploadStatus = wp_handle_upload( $_FILES['_uploaded_file'], array( 'test_form' => false ) ); if ( $uploadStatus && ! isset( $uploadStatus['error'] ) ) { $fileID = wp_insert_attachment( array( 'post_mime_type' => $uploadStatus['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $uploadStatus['file'] ) ), 'post_content' => '', 'post_status' => 'inherit' ), $uploadStatus['file'], $post_id ); if( $fileID ) { $attachmentData = wp_generate_attachment_metadata( $fileID, $uploadStatus['file'] ); wp_update_attachment_metadata( $fileID, $attachmentData ); update_post_meta( $post_id, '_uploaded_file', $fileID ); } } } } add_action( 'add_meta_boxes_page', 'page_meta' ); function page_meta() { add_meta_box("page_upload_image", 'Upload image', 'page_meta_cb'); } /** `page_meta` Callback Function **/ function page_meta_cb( $post ) { wp_nonce_field( 'page_meta_metabox', 'page_meta_nonce' ); $uploaded_file_id = get_post_meta( $post->ID, '_uploaded_file', true ); ?> <div> <table style="width:100%;"> <tbody> <tr id="uploaded_file"> <td style="width:8%;min-width:105px;"> <label for="uploaded_file_input" style="font-weight:bold;">Uploaded File</label><br /> </td> <td> <input type="file" style="width:100%;" name="_uploaded_file" value="" id="uploaded_file_input" /> <?php if( is_numeric( $uploaded_file_id ) ) : ?> <div class="fileLink"> <a href="post.php?post=<?php echo $uploaded_file_id; ?>&action=edit" target="_blank">Edit File - <?php echo get_the_title( $uploaded_file_id ); ?></a> <br /> <br /> </div> <?php endif; ?> </td> </tr> </tbody> </table> </div> <?php } // END Metabox ```
185,864
<p>I have event listings that look like this</p> <pre><code>PAPA ROACH AT THE PARAMOUNT IN HUNTINGTON ON APR 28, 2015 </code></pre> <p>Im trying to remove everything after the last "ON"</p> <pre><code>$s = the_title(); echo substr($s, 0, strrpos($s, 'ON') - 1); </code></pre> <p>The code above works if '$s' is a regular string but if it is 'the_title()' it does not work. Is there a way to convert the_title() in to a static string?</p>
[ { "answer_id": 185866, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 2, "selected": true, "text": "<p>Try using the <code>post</code> variable to access the <code>post_title</code></p>\n\n<pre><code>global $post;\n$s = $post-&gt;post_title;\necho substr($s, 0, strrpos($s, 'on') - 1);\n</code></pre>\n" }, { "answer_id": 185867, "author": "Ben Wainwright", "author_id": 44235, "author_profile": "https://wordpress.stackexchange.com/users/44235", "pm_score": -1, "selected": false, "text": "<p>The function you need to use is</p>\n\n<pre><code>get_the_title()\n</code></pre>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63922/" ]
I have event listings that look like this ``` PAPA ROACH AT THE PARAMOUNT IN HUNTINGTON ON APR 28, 2015 ``` Im trying to remove everything after the last "ON" ``` $s = the_title(); echo substr($s, 0, strrpos($s, 'ON') - 1); ``` The code above works if '$s' is a regular string but if it is 'the\_title()' it does not work. Is there a way to convert the\_title() in to a static string?
Try using the `post` variable to access the `post_title` ``` global $post; $s = $post->post_title; echo substr($s, 0, strrpos($s, 'on') - 1); ```
185,872
<p>I am trying to do a pretty basic AJAX request at the moment, just to test functionality, routing my calls through admin-ajax.php. However, every time I try to fire the AJAX request, I get a 404 error that says "Uncaught syntaxerror: Unexpected token &lt;". Wtf? It appears to be doing this because of the carot in my DTD... I've been through my code but can't figure out what I'm doing wrong here...I'm fairly new to working with AJAX so any help would be appreciated.</p> <p>The php in functions.php is nothing...</p> <pre><code>function shows_callback(){ echo '&lt;h1&gt;Test&lt;/h1&gt;'; } </code></pre> <p>The ajax call...</p> <pre><code> $(".tabs .btn").click(function(e) { e.preventDefault(); $.ajax({ url:"/wp-admin/admin-ajax.php", type: "GET", dataType: "html", cache: false, data: { action: "shows" }, success: function(resp) { $(".ajax-show").append(resp); }, error: function(xhr, status, error){ var err = JSON.parse(xhr.responseText); console.log(err); } }); }); </code></pre> <p>What could I be doing wrong here?</p> <p>EDIT: The full error:</p> <pre><code>Uncaught SyntaxError: Unexpected token &lt; </code></pre> <p>Which I figure is related to the dataType, but I've declared html, so I don't understand...</p>
[ { "answer_id": 227346, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 0, "selected": false, "text": "<p>Make sure you set your</p>\n\n<pre><code>define( 'WP_DEBUG', false );\n</code></pre>\n\n<p>Else the notices and possible errors may cause 404.</p>\n" }, { "answer_id": 233319, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 1, "selected": false, "text": "<p><code>success</code> and <code>error</code> are <strong>functions</strong>, not <strong>properties</strong> of AJAX function. Working code:</p>\n\n<pre><code>$(\".tabs .btn\").click(function(e) {\n e.preventDefault();\n $.ajax({\n url:\"/wp-admin/admin-ajax.php\",\n type: \"GET\",\n dataType: \"html\",\n cache: false,\n data: {\n action: \"shows\"\n }\n })\n .success(function(resp) {\n $(\".ajax-show\").append(resp);\n })\n .error(function(xhr, status, error) {\n var err = JSON.parse(xhr.responseText);\n console.log(err);\n });\n}); \n</code></pre>\n\n<p>Also that should be noted:</p>\n\n<blockquote>\n <p><strong>Deprecation Notice</strong>: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.</p>\n</blockquote>\n" } ]
2015/04/29
[ "https://wordpress.stackexchange.com/questions/185872", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55073/" ]
I am trying to do a pretty basic AJAX request at the moment, just to test functionality, routing my calls through admin-ajax.php. However, every time I try to fire the AJAX request, I get a 404 error that says "Uncaught syntaxerror: Unexpected token <". Wtf? It appears to be doing this because of the carot in my DTD... I've been through my code but can't figure out what I'm doing wrong here...I'm fairly new to working with AJAX so any help would be appreciated. The php in functions.php is nothing... ``` function shows_callback(){ echo '<h1>Test</h1>'; } ``` The ajax call... ``` $(".tabs .btn").click(function(e) { e.preventDefault(); $.ajax({ url:"/wp-admin/admin-ajax.php", type: "GET", dataType: "html", cache: false, data: { action: "shows" }, success: function(resp) { $(".ajax-show").append(resp); }, error: function(xhr, status, error){ var err = JSON.parse(xhr.responseText); console.log(err); } }); }); ``` What could I be doing wrong here? EDIT: The full error: ``` Uncaught SyntaxError: Unexpected token < ``` Which I figure is related to the dataType, but I've declared html, so I don't understand...
`success` and `error` are **functions**, not **properties** of AJAX function. Working code: ``` $(".tabs .btn").click(function(e) { e.preventDefault(); $.ajax({ url:"/wp-admin/admin-ajax.php", type: "GET", dataType: "html", cache: false, data: { action: "shows" } }) .success(function(resp) { $(".ajax-show").append(resp); }) .error(function(xhr, status, error) { var err = JSON.parse(xhr.responseText); console.log(err); }); }); ``` Also that should be noted: > > **Deprecation Notice**: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. > > >
185,916
<p>im using the <strong>wp_list_table</strong> class on my backend theme, to show some informations that i have saved on database, but there is a lot of informations and i want to make it responsive, show/hide some elements according to screen size.</p> <p>I thought it would happen automatically as in the table that displays posts but that's not the case.</p> <p>here is the example of all posts in small screen <img src="https://i.stack.imgur.com/OHqwP.png" alt="posts on small screen"></p> <p>and here is my wp_list_table on small screen <img src="https://i.stack.imgur.com/pGCSj.png" alt="wp_list_table on small screen"></p> <p>how can i remedy that bug without hacks, does it have any solution with wordpress core? like posts </p> <p>thanks</p>
[ { "answer_id": 186020, "author": "Latz", "author_id": 13811, "author_profile": "https://wordpress.stackexchange.com/users/13811", "pm_score": 0, "selected": false, "text": "<p>Responsive list tables are a development goal of WordPress v4.3: <a href=\"https://make.wordpress.org/core/2015/04/30/dev-chat-summary-april-29th/\" rel=\"nofollow\">https://make.wordpress.org/core/2015/04/30/dev-chat-summary-april-29th/</a></p>\n\n<blockquote>\n <p>Better responsive list tables - this involves some PHP-side API changes as well as UI work. The base thought here is that a narrow screened device is also often a mobile device, which may have limited bandwidth. That’s exactly the situation in which you don’t want to have to load more pages to see important information, and our current strategy of truncation is in direct conflict with that.</p>\n</blockquote>\n\n<p>Contact @helen if you want to be involved in the development.</p>\n" }, { "answer_id": 203512, "author": "Dunimas", "author_id": 80863, "author_profile": "https://wordpress.stackexchange.com/users/80863", "pm_score": 0, "selected": false, "text": "<p>This is because you need to set the primary column. If you tell WP what the primary column is, it will format like the default WordPress tables you pictured above. Like so:</p>\n\n<p>Within method <code>prepare_items()</code>:</p>\n\n<pre><code>$this-&gt;_column_headers = array( $columns, $hidden, $sortable, $primary );\n</code></pre>\n\n<p><strong>Definitions</strong></p>\n\n<p>The columns to display:</p>\n\n<pre><code>$columns = array()\n</code></pre>\n\n<p>Columns to hide:</p>\n\n<pre><code>$hidden = array()\n</code></pre>\n\n<p>Columns you can sort:</p>\n\n<pre><code>$sortable = array()\n</code></pre>\n\n<p>The name (provided in the columns array) of the primary column:</p>\n\n<pre><code>$primary = string\n</code></pre>\n" }, { "answer_id": 290467, "author": "roest", "author_id": 134463, "author_profile": "https://wordpress.stackexchange.com/users/134463", "pm_score": 2, "selected": true, "text": "<p>i'm using wp-list-table without the (php) class but html only and wanna share my research. There is some stuff to watch if you need a responsive table when building a wp-list-table yourself:</p>\n\n<ul>\n<li>add class <code>column-primary</code> to header <code>th</code> and body <code>td</code>. If this class is missing the table gets messy in mobile view </li>\n<li>add button with <code>toggle-row</code> class into <code>column-primary</code> to expand the row</li>\n<li>add <code>data-colname</code> to body <code>td</code>- content in mobile get displayed in the middle. Without <code>data-colname</code> the label is missing (which normally displayed in the table header)</li>\n</ul>\n\n<hr>\n\n<p><a href=\"https://i.stack.imgur.com/HomKQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HomKQ.png\" alt=\"responsive wp-list-table on mobile view\"></a></p>\n\n<h2>Final HTML Code should look like this:</h2>\n\n<pre><code>&lt;table class=\"wp-list-table widefat striped\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th class=\"column-primary\"&gt;primary Field Name&lt;/th&gt;\n &lt;th&gt;Label 2&lt;/th&gt;\n &lt;th&gt;Label 3&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr class=\"is-expanded\"&gt;\n &lt;td class=\"column-primary\" data-colname=\"Name\"&gt;primary field content\n &lt;button type=\"button\" class=\"toggle-row\"&gt;\n &lt;span class=\"screen-reader-text\"&gt;show details&lt;/span&gt;\n &lt;/button&gt;\n &lt;/td&gt;\n &lt;td data-colname=\"Label 2\"&gt;Content 2&lt;/td&gt;\n &lt;td data-colname=\"Label 3\"&gt;Content 3&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td class=\"column-primary\" data-colname=\"Name\"&gt;unexpanded row\n &lt;button type=\"button\" class=\"toggle-row\"&gt;\n &lt;span class=\"screen-reader-text\"&gt;show details&lt;/span&gt;\n &lt;/button&gt;\n &lt;/td&gt;\n &lt;td data-colname=\"Label 2\"&gt;Content 2&lt;/td&gt;\n &lt;td data-colname=\"Label 3\"&gt;Content 3&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n" } ]
2015/04/30
[ "https://wordpress.stackexchange.com/questions/185916", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71441/" ]
im using the **wp\_list\_table** class on my backend theme, to show some informations that i have saved on database, but there is a lot of informations and i want to make it responsive, show/hide some elements according to screen size. I thought it would happen automatically as in the table that displays posts but that's not the case. here is the example of all posts in small screen ![posts on small screen](https://i.stack.imgur.com/OHqwP.png) and here is my wp\_list\_table on small screen ![wp_list_table on small screen](https://i.stack.imgur.com/pGCSj.png) how can i remedy that bug without hacks, does it have any solution with wordpress core? like posts thanks
i'm using wp-list-table without the (php) class but html only and wanna share my research. There is some stuff to watch if you need a responsive table when building a wp-list-table yourself: * add class `column-primary` to header `th` and body `td`. If this class is missing the table gets messy in mobile view * add button with `toggle-row` class into `column-primary` to expand the row * add `data-colname` to body `td`- content in mobile get displayed in the middle. Without `data-colname` the label is missing (which normally displayed in the table header) --- [![responsive wp-list-table on mobile view](https://i.stack.imgur.com/HomKQ.png)](https://i.stack.imgur.com/HomKQ.png) Final HTML Code should look like this: -------------------------------------- ``` <table class="wp-list-table widefat striped"> <thead> <tr> <th class="column-primary">primary Field Name</th> <th>Label 2</th> <th>Label 3</th> </tr> </thead> <tbody> <tr class="is-expanded"> <td class="column-primary" data-colname="Name">primary field content <button type="button" class="toggle-row"> <span class="screen-reader-text">show details</span> </button> </td> <td data-colname="Label 2">Content 2</td> <td data-colname="Label 3">Content 3</td> </tr> <tr> <td class="column-primary" data-colname="Name">unexpanded row <button type="button" class="toggle-row"> <span class="screen-reader-text">show details</span> </button> </td> <td data-colname="Label 2">Content 2</td> <td data-colname="Label 3">Content 3</td> </tr> </tbody> </table> ```
185,931
<p>Recently I updated my wordpress to 4.2.1 and now I have a problem with editing people's comments. After editing them, the avatar picture of who edited the comment is shown instead of the avatar of the real man who wrote the comment. What should I do?</p>
[ { "answer_id": 186020, "author": "Latz", "author_id": 13811, "author_profile": "https://wordpress.stackexchange.com/users/13811", "pm_score": 0, "selected": false, "text": "<p>Responsive list tables are a development goal of WordPress v4.3: <a href=\"https://make.wordpress.org/core/2015/04/30/dev-chat-summary-april-29th/\" rel=\"nofollow\">https://make.wordpress.org/core/2015/04/30/dev-chat-summary-april-29th/</a></p>\n\n<blockquote>\n <p>Better responsive list tables - this involves some PHP-side API changes as well as UI work. The base thought here is that a narrow screened device is also often a mobile device, which may have limited bandwidth. That’s exactly the situation in which you don’t want to have to load more pages to see important information, and our current strategy of truncation is in direct conflict with that.</p>\n</blockquote>\n\n<p>Contact @helen if you want to be involved in the development.</p>\n" }, { "answer_id": 203512, "author": "Dunimas", "author_id": 80863, "author_profile": "https://wordpress.stackexchange.com/users/80863", "pm_score": 0, "selected": false, "text": "<p>This is because you need to set the primary column. If you tell WP what the primary column is, it will format like the default WordPress tables you pictured above. Like so:</p>\n\n<p>Within method <code>prepare_items()</code>:</p>\n\n<pre><code>$this-&gt;_column_headers = array( $columns, $hidden, $sortable, $primary );\n</code></pre>\n\n<p><strong>Definitions</strong></p>\n\n<p>The columns to display:</p>\n\n<pre><code>$columns = array()\n</code></pre>\n\n<p>Columns to hide:</p>\n\n<pre><code>$hidden = array()\n</code></pre>\n\n<p>Columns you can sort:</p>\n\n<pre><code>$sortable = array()\n</code></pre>\n\n<p>The name (provided in the columns array) of the primary column:</p>\n\n<pre><code>$primary = string\n</code></pre>\n" }, { "answer_id": 290467, "author": "roest", "author_id": 134463, "author_profile": "https://wordpress.stackexchange.com/users/134463", "pm_score": 2, "selected": true, "text": "<p>i'm using wp-list-table without the (php) class but html only and wanna share my research. There is some stuff to watch if you need a responsive table when building a wp-list-table yourself:</p>\n\n<ul>\n<li>add class <code>column-primary</code> to header <code>th</code> and body <code>td</code>. If this class is missing the table gets messy in mobile view </li>\n<li>add button with <code>toggle-row</code> class into <code>column-primary</code> to expand the row</li>\n<li>add <code>data-colname</code> to body <code>td</code>- content in mobile get displayed in the middle. Without <code>data-colname</code> the label is missing (which normally displayed in the table header)</li>\n</ul>\n\n<hr>\n\n<p><a href=\"https://i.stack.imgur.com/HomKQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HomKQ.png\" alt=\"responsive wp-list-table on mobile view\"></a></p>\n\n<h2>Final HTML Code should look like this:</h2>\n\n<pre><code>&lt;table class=\"wp-list-table widefat striped\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th class=\"column-primary\"&gt;primary Field Name&lt;/th&gt;\n &lt;th&gt;Label 2&lt;/th&gt;\n &lt;th&gt;Label 3&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr class=\"is-expanded\"&gt;\n &lt;td class=\"column-primary\" data-colname=\"Name\"&gt;primary field content\n &lt;button type=\"button\" class=\"toggle-row\"&gt;\n &lt;span class=\"screen-reader-text\"&gt;show details&lt;/span&gt;\n &lt;/button&gt;\n &lt;/td&gt;\n &lt;td data-colname=\"Label 2\"&gt;Content 2&lt;/td&gt;\n &lt;td data-colname=\"Label 3\"&gt;Content 3&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td class=\"column-primary\" data-colname=\"Name\"&gt;unexpanded row\n &lt;button type=\"button\" class=\"toggle-row\"&gt;\n &lt;span class=\"screen-reader-text\"&gt;show details&lt;/span&gt;\n &lt;/button&gt;\n &lt;/td&gt;\n &lt;td data-colname=\"Label 2\"&gt;Content 2&lt;/td&gt;\n &lt;td data-colname=\"Label 3\"&gt;Content 3&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n" } ]
2015/04/30
[ "https://wordpress.stackexchange.com/questions/185931", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36838/" ]
Recently I updated my wordpress to 4.2.1 and now I have a problem with editing people's comments. After editing them, the avatar picture of who edited the comment is shown instead of the avatar of the real man who wrote the comment. What should I do?
i'm using wp-list-table without the (php) class but html only and wanna share my research. There is some stuff to watch if you need a responsive table when building a wp-list-table yourself: * add class `column-primary` to header `th` and body `td`. If this class is missing the table gets messy in mobile view * add button with `toggle-row` class into `column-primary` to expand the row * add `data-colname` to body `td`- content in mobile get displayed in the middle. Without `data-colname` the label is missing (which normally displayed in the table header) --- [![responsive wp-list-table on mobile view](https://i.stack.imgur.com/HomKQ.png)](https://i.stack.imgur.com/HomKQ.png) Final HTML Code should look like this: -------------------------------------- ``` <table class="wp-list-table widefat striped"> <thead> <tr> <th class="column-primary">primary Field Name</th> <th>Label 2</th> <th>Label 3</th> </tr> </thead> <tbody> <tr class="is-expanded"> <td class="column-primary" data-colname="Name">primary field content <button type="button" class="toggle-row"> <span class="screen-reader-text">show details</span> </button> </td> <td data-colname="Label 2">Content 2</td> <td data-colname="Label 3">Content 3</td> </tr> <tr> <td class="column-primary" data-colname="Name">unexpanded row <button type="button" class="toggle-row"> <span class="screen-reader-text">show details</span> </button> </td> <td data-colname="Label 2">Content 2</td> <td data-colname="Label 3">Content 3</td> </tr> </tbody> </table> ```
185,960
<p>I'm trying to build a function to display the current chapter (page) within the single.php file ONLY if there's more than one chapter (page break).</p> <p>This function will output the chapter # within the page header under the title. Then I will customize and use the wp_link_pages at the bottom for the chapter pagination.</p> <p>Currently, my function doesn't work, it return nothing and if I remove the the IF statement if ( $multipage ) {} it return "Chapter 0".</p> <p>I need advice on this one.</p> <pre><code>/** * Get current chapter number */ if ( ! function_exists( 'sbwp_get_current_chapter' ) ) { function sbwp_get_current_chapter() { global $page, $numpages, $multipage, $more; if ( $multipage ) { echo '&lt;p class="page-link accent"&gt;'; echo esc_html(( '' . __( "Chapter ", "sbwp" ) . '' . $page )); echo '&lt;/p&gt;'; } } } </code></pre>
[ { "answer_id": 185967, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p><code>$multipage</code> is an <a href=\"https://codex.wordpress.org/Global_Variables#Inside_the_Loop_variables\" rel=\"nofollow\">\"inside the Loop\" variable</a>. I did not track down exactly where and how it is set but given that information alone the obvious solution is to <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow\">put your code inside a Loop</a>, which is good practice anyway as a number of things depend upon that Loop. Something like:</p>\n\n<pre><code>if (have_posts()) {\n while (have_posts() {\n the_post();\n $sbwp_story_thumbnail = \"\";\n // ....\n }\n}\n</code></pre>\n" }, { "answer_id": 185968, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>The <code>$multipage</code> is constructed inside the <code>setup_postdata()</code> method of <code>WP_Query</code>.\nIt's called when you run <code>the_post()</code>. So just as @s_ha_dum explained, you have to make a loop around it:</p>\n\n<p>You can try this:</p>\n\n<pre><code>if( have_posts() )\n{ \n the_post(); // Make a call to setup_postdata().\n echo sbwp_get_current_chapter(); // Display the current chapter.\n rewind_posts(); // Rewind back.\n}\n</code></pre>\n\n<p>before your main loop, where you must remember to rewind back.</p>\n" } ]
2015/04/30
[ "https://wordpress.stackexchange.com/questions/185960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71466/" ]
I'm trying to build a function to display the current chapter (page) within the single.php file ONLY if there's more than one chapter (page break). This function will output the chapter # within the page header under the title. Then I will customize and use the wp\_link\_pages at the bottom for the chapter pagination. Currently, my function doesn't work, it return nothing and if I remove the the IF statement if ( $multipage ) {} it return "Chapter 0". I need advice on this one. ``` /** * Get current chapter number */ if ( ! function_exists( 'sbwp_get_current_chapter' ) ) { function sbwp_get_current_chapter() { global $page, $numpages, $multipage, $more; if ( $multipage ) { echo '<p class="page-link accent">'; echo esc_html(( '' . __( "Chapter ", "sbwp" ) . '' . $page )); echo '</p>'; } } } ```
The `$multipage` is constructed inside the `setup_postdata()` method of `WP_Query`. It's called when you run `the_post()`. So just as @s\_ha\_dum explained, you have to make a loop around it: You can try this: ``` if( have_posts() ) { the_post(); // Make a call to setup_postdata(). echo sbwp_get_current_chapter(); // Display the current chapter. rewind_posts(); // Rewind back. } ``` before your main loop, where you must remember to rewind back.
185,971
<p>I have a custom function written in PHP for a Wordspress theme. When I initially wrote it, it worked exactly as expected (it returns the parents and grandparents etc of a term from its ID).</p> <p>However, after a couple of hours, it started throwing up 503 errors. Why would this only happen after a while? Is there some sort of memory leak that builds up over time?</p> <pre><code>$ancestors = $terms[0]-&gt;term_id.GetAncestors($terms[0]-&gt;term_id,$include); function GetAncestors($term_id,&amp;$include) { $child_term = get_term( $term_id, 'category' ); $parent_term = get_term( $child_term-&gt;parent, 'category' ); $include.=','.$parent_term-&gt;term_id; if($parent_term-&gt;parent!=11) {GetAncestors($parent_term-&gt;term_id,$include);} return $include; } </code></pre> <p>Is it the function itself that's causing the issue, or some way I'm using it, e.g. using a reference from an object as one of the variables?</p>
[ { "answer_id": 185972, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>If I had to guess, I'd say you're running into a memory leak like you suggested, infinite recursive loop. You need to run checks for when the term either hits the top of the ancestry tree or errors out:</p>\n\n<pre><code>$ancestors = $terms[0]-&gt;term_id.GetAncestors( $terms[0]-&gt;term_id, $include );\n\nfunction GetAncestors( $term_id, &amp;$include ) {\n $child_term = get_term( $term_id, 'category' );\n $parent_term = get_term( $child_term-&gt;parent, 'category' );\n $include .= ',' . $parent_term-&gt;term_id;\n\n if( ! empty( $parent_term ) &amp;&amp; $parent_term-&gt;parent != 11 ) { // We've reached the top - parent term_id is 0\n GetAncestors( $parent_term-&gt;term_id, $include );\n }\n\n return $include;\n}\n</code></pre>\n\n<p>Eventually, <code>$parent-&gt;term_id</code> is going to equal <code>0</code> and we can't go up any further. We need to test for that and drop out once we hit it. I imagine if you turned on debugging you would see a ton of non-object errors regarding this function. The PHP function <a href=\"http://php.net/manual/en/function.empty.php\" rel=\"nofollow\"><code>empty()</code></a> checks for <code>null</code> and <code>0</code> so this should suffice. </p>\n" }, { "answer_id": 185979, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 3, "selected": true, "text": "<p>What about using the WordPress function <a href=\"https://codex.wordpress.org/Function_Reference/get_ancestors\" rel=\"nofollow\"><code>get_ancestors()</code></a>, which</p>\n\n<blockquote>\n <p>Returns an array containing the parents of the given object. </p>\n</blockquote>\n\n<p>To be exact an</p>\n\n<blockquote>\n <p>Array of ancestors from lowest to highest in the hierarchy </p>\n</blockquote>\n\n<p>We can easily create a function to return a list by using <code>implode</code> to do so:</p>\n\n<pre><code>function wpse185971_get_ancestors_list(\n $object_id,\n $object_type = 'category',\n $separator = ','\n) {\n $ancestors_array = get_ancestors( $object_id, $object_type );\n $ancestors_list = implode( $separator, $ancestors_array );\n return $ancestors_list;\n}\n</code></pre>\n" } ]
2015/04/30
[ "https://wordpress.stackexchange.com/questions/185971", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63673/" ]
I have a custom function written in PHP for a Wordspress theme. When I initially wrote it, it worked exactly as expected (it returns the parents and grandparents etc of a term from its ID). However, after a couple of hours, it started throwing up 503 errors. Why would this only happen after a while? Is there some sort of memory leak that builds up over time? ``` $ancestors = $terms[0]->term_id.GetAncestors($terms[0]->term_id,$include); function GetAncestors($term_id,&$include) { $child_term = get_term( $term_id, 'category' ); $parent_term = get_term( $child_term->parent, 'category' ); $include.=','.$parent_term->term_id; if($parent_term->parent!=11) {GetAncestors($parent_term->term_id,$include);} return $include; } ``` Is it the function itself that's causing the issue, or some way I'm using it, e.g. using a reference from an object as one of the variables?
What about using the WordPress function [`get_ancestors()`](https://codex.wordpress.org/Function_Reference/get_ancestors), which > > Returns an array containing the parents of the given object. > > > To be exact an > > Array of ancestors from lowest to highest in the hierarchy > > > We can easily create a function to return a list by using `implode` to do so: ``` function wpse185971_get_ancestors_list( $object_id, $object_type = 'category', $separator = ',' ) { $ancestors_array = get_ancestors( $object_id, $object_type ); $ancestors_list = implode( $separator, $ancestors_array ); return $ancestors_list; } ```
185,997
<p>I'm searching the web on the last 3 hours without success.</p> <p>I have a website where authors can publish posts, and posts views are tracking using postmeta "post_views_count".</p> <p>I'm using this code and works, but show me the count only for the first 5 posts and not for all author posts. This is the code?</p> <pre><code>global $wp_query; $author_id = get_current_user_id(); $author_posts = get_posts( array('author' =&gt; $author_id) ); $counter = 0; // needed to collect the total sum of views foreach ( $author_posts as $post ) { $views = absint( get_post_meta( $post-&gt;ID, 'post_views_count', true ) ); var_dump($views); $counter += $views; } echo "{$counter}"; </code></pre> <hr> <p>What is wrong? Why show me the count of only 5 posts? Thanks a lot</p>
[ { "answer_id": 185998, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>It's showing you the first 5 posts because that's how many posts are on page 1, and you never told it how many posts per page to load, so it used the default posts per page you set under settings.</p>\n\n<p>You'll want to modify the <code>get_posts</code> call to have the <code>posts_per_page</code> parameter.</p>\n\n<p>However, I will note the following problems:</p>\n\n<ul>\n<li><code>get_posts</code> doesn't cache the way <code>WP_Query</code> does, switching to directly using <code>WP_Query</code> would be more efficient</li>\n<li>Storing view counts inside post meta is incredibly innefficient, and slows down page loads</li>\n<li>Your statistics are unreliable, as you now have race conditions whenever more than one person visits a page, which can lead to deflated values ( your page view updates aren't atomic operation )</li>\n<li>It's no longer possible to cache your pages, and any attempt to cache pages will ruin your stats</li>\n<li>Instead of <code>echo \"{$counter}\";</code> you should just use <code>echo $counter;</code></li>\n<li>You'll almost certainly want to save the view count and cache it, WordPress already maintains post counts for terms categories and post types, page views in post meta is even more expensive</li>\n<li>Don't declare stuff you're never going to use, I'm looking at <code>global $wp_query;</code></li>\n</ul>\n\n<p>Instead, consider using an existing stats package, such as the Google Analytics API, Jetpack stats, or a metric such as comment counts, twitter retweets or fb shares</p>\n" }, { "answer_id": 294046, "author": "ahmet", "author_id": 136023, "author_profile": "https://wordpress.stackexchange.com/users/136023", "pm_score": 0, "selected": false, "text": "<p>Thanks to Tom J Nowell's answer, I figured out.</p>\n\n<p>Here is the missing part:</p>\n\n<pre><code>$author_posts = get_posts( array('author' =&gt; $author_id, 'numberposts' =&gt; -1 ));\n</code></pre>\n\n<p>Try this</p>\n\n<pre><code>&lt;?php\n global $wp_query;\n\n $author_id = $wp_query-&gt;queried_object_id;\n $author_posts = get_posts( array('author' =&gt; $author_id, 'numberposts' =&gt; -1 ));\n $counter = 0; // needed to collect the total sum of views\n\n foreach ( $author_posts as $post ) {\n\n $views = absint( get_post_meta( $post-&gt;ID, 'post_views_count', true ) );\n\n $counter += $views;\n\n }\n echo $counter;\n\n ?&gt; \n</code></pre>\n" } ]
2015/04/30
[ "https://wordpress.stackexchange.com/questions/185997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71488/" ]
I'm searching the web on the last 3 hours without success. I have a website where authors can publish posts, and posts views are tracking using postmeta "post\_views\_count". I'm using this code and works, but show me the count only for the first 5 posts and not for all author posts. This is the code? ``` global $wp_query; $author_id = get_current_user_id(); $author_posts = get_posts( array('author' => $author_id) ); $counter = 0; // needed to collect the total sum of views foreach ( $author_posts as $post ) { $views = absint( get_post_meta( $post->ID, 'post_views_count', true ) ); var_dump($views); $counter += $views; } echo "{$counter}"; ``` --- What is wrong? Why show me the count of only 5 posts? Thanks a lot
It's showing you the first 5 posts because that's how many posts are on page 1, and you never told it how many posts per page to load, so it used the default posts per page you set under settings. You'll want to modify the `get_posts` call to have the `posts_per_page` parameter. However, I will note the following problems: * `get_posts` doesn't cache the way `WP_Query` does, switching to directly using `WP_Query` would be more efficient * Storing view counts inside post meta is incredibly innefficient, and slows down page loads * Your statistics are unreliable, as you now have race conditions whenever more than one person visits a page, which can lead to deflated values ( your page view updates aren't atomic operation ) * It's no longer possible to cache your pages, and any attempt to cache pages will ruin your stats * Instead of `echo "{$counter}";` you should just use `echo $counter;` * You'll almost certainly want to save the view count and cache it, WordPress already maintains post counts for terms categories and post types, page views in post meta is even more expensive * Don't declare stuff you're never going to use, I'm looking at `global $wp_query;` Instead, consider using an existing stats package, such as the Google Analytics API, Jetpack stats, or a metric such as comment counts, twitter retweets or fb shares
185,999
<p>I have a parent theme that uses correctly <code>load_theme_textdomain()</code> to load all the translated strings in many languages.</p> <p>Then I created a child theme that uses <code>load_child_theme_textdomain()</code> to achieve the same thing for its strings.</p> <p>There are certain translated strings for a particular language on the parent theme that I'd like to replace/override in the child theme.</p> <p>I know if they were on a template file I could replace the file and simply change the textdomain for those strings, but unfortunately the ones I'm talking about are used in many places and also in the dashboard (so inside some filter/action functions).</p> <p>So my question is: <strong>is there a way to replace those translated strings inside the child theme without having to replace parent template files or functions?</strong></p> <p>I don't know, maybe adding a <em>parent-theme.mo</em> file inside the languages folder of the child theme with only those strings translated, or something like that.</p>
[ { "answer_id": 188424, "author": "redelschaap", "author_id": 69725, "author_profile": "https://wordpress.stackexchange.com/users/69725", "pm_score": 2, "selected": false, "text": "<p>You can use language files that are in your child theme folder. First you have to know which text domain the parent theme is using. Then create the .po and .mo files with only your language as the file name (e.g. de_DE.po/de_DE.mo or nl_NL.po/nl_NL.mo) and put them into a folder within your child theme directory, \"languages\" for example.</p>\n\n<p>You can then initialize the text domain with <code>load_child_theme_textdomain()</code>:</p>\n\n<pre><code>load_child_theme_textdomain( 'the_text_domain', get_stylesheet_directory() . '/languages/' );\n</code></pre>\n\n<p>Note that you can find the text domain by looking for function calls like <code>__()</code> or <code>_e()</code> within the parent theme PHP files. The second parameter is the text domain: <code>__( 'Translated text string', 'text_domain' );</code></p>\n" }, { "answer_id": 188820, "author": "d79", "author_id": 69071, "author_profile": "https://wordpress.stackexchange.com/users/69071", "pm_score": 5, "selected": true, "text": "<p>I think I found a solution, but before a little</p>\n<h2>Premise</h2>\n<p><code>load_theme_textdomain()</code> and <code>load_child_theme_textdomain()</code> are basically equal, the only difference is the default path they use:</p>\n<ul>\n<li>they get the current language (using <code>get_locale()</code>) and add the relative <strong>.mo</strong> file to the path passed as argument;</li>\n<li>then they call <code>load_textdomain()</code> passing as argument both the textdomain and the resulting path to the .mo file.</li>\n</ul>\n<p>Then <code>load_textdomain</code> loads the .mo file into the global textdomain variable, but as we can read from the <a href=\"https://core.trac.wordpress.org/browser/tags/3.3.2/wp-includes/l10n.php#L306\" rel=\"noreferrer\">source</a>:</p>\n<blockquote>\n<p>If the domain already exists, the translations will be merged.</p>\n<p>If both sets have the same string, the translation from the original value will be taken.</p>\n</blockquote>\n<p>So, in order to override/replace just the strings of the theme parent we want, we need to load a custom .mo file for the parent textdomain, containing just those strings translated, <strong>before</strong> the parent theme load its .mo file.</p>\n<hr />\n<h2>Solution</h2>\n<p>In the end, I simply created a folder with the name of the parent theme (just for convenience) into the child theme languages folder, and put inside it my custom .mo files for the parent textdomain (one for language, in the <code>xx_XX.mo</code> form, where <code>xx_XX</code> is the language code).</p>\n<p>And then I added a line in my child theme <code>functions.php</code> file during the <code>after_setup_theme</code> action, near the one that loads the .mo file for my child theme textdomain:</p>\n<pre><code>add_action( 'after_setup_theme', function () {\n // load custom translation file for the parent theme\n load_theme_textdomain( 'parent-textdomain', get_stylesheet_directory() . '/languages/parent-theme' );\n // load translation file for the child theme\n load_child_theme_textdomain( 'my-child-theme', get_stylesheet_directory() . '/languages' );\n} );\n</code></pre>\n<p>Because the <code>functions.php</code> file of the child theme is loaded before the parent's one, this set of strings will have precedence over the parent theme translation (or I could've just set the priority using the third parameter of the <code>add_action</code> function).</p>\n<hr />\n<p><em>Note:</em> I could have use <code>load_child_theme_textdomain</code> instead of <code>load_theme_textdomain</code>, as said in the premise it would've been the same.</p>\n" }, { "answer_id": 333489, "author": "Cesar", "author_id": 152450, "author_profile": "https://wordpress.stackexchange.com/users/152450", "pm_score": 2, "selected": false, "text": "<p>A 2019 update for Wordpress 5.0.1.</p>\n\n<ol>\n<li>The files shall NOT have the parent or child slug in them. For example, providing spanish Mexican translation should have files child-theme-name/languages/es_MX.po and /child-theme-name/languages/es_MX.mo</li>\n<li>The child theme functions.php should have the following code. Notice that the function load_child_theme_textdomain() first parameter is the PARENT theme slug, not the child's:</li>\n</ol>\n\n<pre><code>function child_theme_slug_setup() {\n load_child_theme_textdomain( 'parent-theme-slug', get_stylesheet_directory() . '/languages' );\n}\nadd_action( 'after_setup_theme', 'child_theme_slug_setup' );\n</code></pre>\n" } ]
2015/05/01
[ "https://wordpress.stackexchange.com/questions/185999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69071/" ]
I have a parent theme that uses correctly `load_theme_textdomain()` to load all the translated strings in many languages. Then I created a child theme that uses `load_child_theme_textdomain()` to achieve the same thing for its strings. There are certain translated strings for a particular language on the parent theme that I'd like to replace/override in the child theme. I know if they were on a template file I could replace the file and simply change the textdomain for those strings, but unfortunately the ones I'm talking about are used in many places and also in the dashboard (so inside some filter/action functions). So my question is: **is there a way to replace those translated strings inside the child theme without having to replace parent template files or functions?** I don't know, maybe adding a *parent-theme.mo* file inside the languages folder of the child theme with only those strings translated, or something like that.
I think I found a solution, but before a little Premise ------- `load_theme_textdomain()` and `load_child_theme_textdomain()` are basically equal, the only difference is the default path they use: * they get the current language (using `get_locale()`) and add the relative **.mo** file to the path passed as argument; * then they call `load_textdomain()` passing as argument both the textdomain and the resulting path to the .mo file. Then `load_textdomain` loads the .mo file into the global textdomain variable, but as we can read from the [source](https://core.trac.wordpress.org/browser/tags/3.3.2/wp-includes/l10n.php#L306): > > If the domain already exists, the translations will be merged. > > > If both sets have the same string, the translation from the original value will be taken. > > > So, in order to override/replace just the strings of the theme parent we want, we need to load a custom .mo file for the parent textdomain, containing just those strings translated, **before** the parent theme load its .mo file. --- Solution -------- In the end, I simply created a folder with the name of the parent theme (just for convenience) into the child theme languages folder, and put inside it my custom .mo files for the parent textdomain (one for language, in the `xx_XX.mo` form, where `xx_XX` is the language code). And then I added a line in my child theme `functions.php` file during the `after_setup_theme` action, near the one that loads the .mo file for my child theme textdomain: ``` add_action( 'after_setup_theme', function () { // load custom translation file for the parent theme load_theme_textdomain( 'parent-textdomain', get_stylesheet_directory() . '/languages/parent-theme' ); // load translation file for the child theme load_child_theme_textdomain( 'my-child-theme', get_stylesheet_directory() . '/languages' ); } ); ``` Because the `functions.php` file of the child theme is loaded before the parent's one, this set of strings will have precedence over the parent theme translation (or I could've just set the priority using the third parameter of the `add_action` function). --- *Note:* I could have use `load_child_theme_textdomain` instead of `load_theme_textdomain`, as said in the premise it would've been the same.
186,034
<p>The essence of the question is, I'm looking for a solution like this: </p> <pre><code>$blog_upload_dir_info = wp_upload_dir( $date, $blog_ID ); $blog_upload_url = $blog_upload_dir_info[ 'baseurl' ]; </code></pre> <p>Where <code>$blog_ID</code> is different of the current blog ID. The most »WP-obvious« solution fails:</p> <pre><code>switch_to_blog( $blog_ID ); $blog_upload_dir_info = wp_upload_dir(); restore_current_blog(); </code></pre> <p>as <a href="https://github.com/WordPress/WordPress/blob/cb1ad98015ea8e75474e22c39d77e4aaf3d008ab/wp-includes/functions.php#L1722">wp_upload_dir()</a> relies on the constant <code>WP_CONTENT_URL</code> which is dynamically set the URL of the current blog unless the option <code>upload_url_path</code> is set.</p> <p>Of course, I could set this option, but this would couple my code to concrete system settings which includes much »WTF?«-potential.</p> <p>So I decided to add this option virtually:</p> <pre><code>/** * Apply a value to the option blog_upload_url * if there's not already one * * @wp-hook option_upload_url_path * @param string $upload_url * @return string */ function get_real_blog_upload_url( $upload_url ) { if ( '' !== trim( $upload_url ) ) return $upload_url; $upload_path = trim( get_option( 'upload_path' ) ); $siteurl = get_option( 'siteurl' ); $wp_content_dir = $siteurl . '/wp-content'; if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) { $dir = $wp_content_dir . '/uploads'; } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) { // $dir is absolute, $upload_path is (maybe) relative to ABSPATH $dir = path_join( ABSPATH, $upload_path ); } else { $dir = $upload_path; } if ( empty( $upload_path ) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) ) $upload_path = $wp_content_dir . '/uploads'; else $upload_path = trailingslashit( $siteurl ) . $upload_path; return $upload_path; } </code></pre> <p>which is in fact a partly fork of <code>wp_upload_dir()</code> and as such relies on constants which <a href="http://wpkrauts.com/2015/the-guide-to-wordpress-path-and-urls/">isn't a good practice at all</a>. Moreover a fork is always coupled to the original implementation and if the original changes, one also have to fix the fork. </p> <p>So as this solution is far away from being perfect, I wonder if there's a better way to get upload URLs by blog IDs.</p>
[ { "answer_id": 218845, "author": "Megan Rose", "author_id": 84643, "author_profile": "https://wordpress.stackexchange.com/users/84643", "pm_score": 1, "selected": false, "text": "<p>Why not just use <code>get_option('upload_path')</code> after your <code>switch_to_blog( $blog_ID );</code>?\nDoes that do it?</p>\n" }, { "answer_id": 242656, "author": "Arbelzapf", "author_id": 104911, "author_profile": "https://wordpress.stackexchange.com/users/104911", "pm_score": -1, "selected": false, "text": "<p>For completeness' sake, <a href=\"https://core.trac.wordpress.org/ticket/25650#comment:6\" rel=\"nofollow\">this</a> solution seems to work until the issue is fixed in core:</p>\n\n<pre><code>add_action('switch_blog', function($new_blog, $prev_blog_id) {\n update_option( 'upload_url_path', get_option('siteurl') . '/wp-content/uploads');\n}, 10, 2);\n</code></pre>\n" } ]
2015/05/01
[ "https://wordpress.stackexchange.com/questions/186034", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31323/" ]
The essence of the question is, I'm looking for a solution like this: ``` $blog_upload_dir_info = wp_upload_dir( $date, $blog_ID ); $blog_upload_url = $blog_upload_dir_info[ 'baseurl' ]; ``` Where `$blog_ID` is different of the current blog ID. The most »WP-obvious« solution fails: ``` switch_to_blog( $blog_ID ); $blog_upload_dir_info = wp_upload_dir(); restore_current_blog(); ``` as [wp\_upload\_dir()](https://github.com/WordPress/WordPress/blob/cb1ad98015ea8e75474e22c39d77e4aaf3d008ab/wp-includes/functions.php#L1722) relies on the constant `WP_CONTENT_URL` which is dynamically set the URL of the current blog unless the option `upload_url_path` is set. Of course, I could set this option, but this would couple my code to concrete system settings which includes much »WTF?«-potential. So I decided to add this option virtually: ``` /** * Apply a value to the option blog_upload_url * if there's not already one * * @wp-hook option_upload_url_path * @param string $upload_url * @return string */ function get_real_blog_upload_url( $upload_url ) { if ( '' !== trim( $upload_url ) ) return $upload_url; $upload_path = trim( get_option( 'upload_path' ) ); $siteurl = get_option( 'siteurl' ); $wp_content_dir = $siteurl . '/wp-content'; if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) { $dir = $wp_content_dir . '/uploads'; } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) { // $dir is absolute, $upload_path is (maybe) relative to ABSPATH $dir = path_join( ABSPATH, $upload_path ); } else { $dir = $upload_path; } if ( empty( $upload_path ) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) ) $upload_path = $wp_content_dir . '/uploads'; else $upload_path = trailingslashit( $siteurl ) . $upload_path; return $upload_path; } ``` which is in fact a partly fork of `wp_upload_dir()` and as such relies on constants which [isn't a good practice at all](http://wpkrauts.com/2015/the-guide-to-wordpress-path-and-urls/). Moreover a fork is always coupled to the original implementation and if the original changes, one also have to fix the fork. So as this solution is far away from being perfect, I wonder if there's a better way to get upload URLs by blog IDs.
Why not just use `get_option('upload_path')` after your `switch_to_blog( $blog_ID );`? Does that do it?
186,048
<p>Can you please help me on how can I display a list <code>&lt;li&gt;</code> of newly published child pages. I've been looking on google how to use display it using the <code>wp_list_pages();</code> but can't find out there. I want to display it like in the "Latest Trainings" or something like that.</p>
[ { "answer_id": 186053, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>If you're really just looking to get a list of children with <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_pages\" rel=\"nofollow noreferrer\"><code>wp_list_pages()</code></a>, then you should use the <code>child_of</code> parameter to do so. But I'm assuming you're actually want to restrict that list to a certain time frame, for this <code>wp_list_pages()</code>, which uses <a href=\"https://codex.wordpress.org/Function_Reference/get_pages\" rel=\"nofollow noreferrer\"><code>get_pages()</code></a>, isn't really good equipped. </p>\n\n<p>So I'm thinking you should use <a href=\"https://codex.wordpress.org/Function_Reference/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> - or even <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> directly -, where you can make use of »<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow noreferrer\">WP_Query: Date Parameters</a>«. <del>The drawback here - as a generic function<code>wp_list_posts()</code> does not exist - is that you have to write the code to generate your list yourself.</del> @s_ha_dum's <a href=\"https://wordpress.stackexchange.com/a/186055/22534\">answer</a> shows how you can combine this, making the drawback almost disappear - just a little bit more code is needed.</p>\n" }, { "answer_id": 186054, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 0, "selected": false, "text": "<p>Try using the following code to generate the child pages. </p>\n\n<pre><code>&lt;?php\n// Set up the objects needed\n$my_wp_query = new WP_Query();\n\n// Query all pages\n$all_wp_pages = $my_wp_query-&gt;query(array('post_type' =&gt; 'page'));\n\n$page_ids = get_all_page_ids();\n\n$page_children = get_page_children( $page_ids, $all_wp_pages );\n\necho '&lt;li&gt;' . print_r( $page_children, true ) . '&lt;/li&gt;';\n?&gt;\n</code></pre>\n" }, { "answer_id": 186055, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": true, "text": "<p>This will get you the post data for all child pages:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'page',\n 'post_parent__not_in' =&gt; array(0), \n 'no_found_rows' =&gt; true,\n);\n$child = new WP_Query($args);\nvar_dump(wp_list_pluck($child-&gt;posts,'post_title')); // debugging only\n</code></pre>\n\n<p>Then pass the IDs to <code>wp_list_pages()</code>:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'page',\n 'post_parent__not_in' =&gt; array(0), \n 'no_found_rows' =&gt; true,\n);\n$child = new WP_Query($args);\n$ids = wp_list_pluck($child-&gt;posts,'ID');\n$ids = implode($ids,',');\n$args = array(\n 'include' =&gt; $ids,\n);\nwp_list_pages($args);\n</code></pre>\n\n<p>Or, even cleaner:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'page',\n 'post_parent__not_in' =&gt; array(0), \n 'no_found_rows' =&gt; true,\n 'fields' =&gt; 'ids'\n);\n$child = new WP_Query($args);\n$args = array(\n 'include' =&gt; $child-&gt;posts,\n);\nwp_list_pages($args);\n</code></pre>\n\n<p>Please note that there is no error checking to that code. </p>\n\n<p>I'll see if I can spot a clean way to do this with filters. Check back later.</p>\n" } ]
2015/05/01
[ "https://wordpress.stackexchange.com/questions/186048", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50871/" ]
Can you please help me on how can I display a list `<li>` of newly published child pages. I've been looking on google how to use display it using the `wp_list_pages();` but can't find out there. I want to display it like in the "Latest Trainings" or something like that.
This will get you the post data for all child pages: ``` $args = array( 'post_type' => 'page', 'post_parent__not_in' => array(0), 'no_found_rows' => true, ); $child = new WP_Query($args); var_dump(wp_list_pluck($child->posts,'post_title')); // debugging only ``` Then pass the IDs to `wp_list_pages()`: ``` $args = array( 'post_type' => 'page', 'post_parent__not_in' => array(0), 'no_found_rows' => true, ); $child = new WP_Query($args); $ids = wp_list_pluck($child->posts,'ID'); $ids = implode($ids,','); $args = array( 'include' => $ids, ); wp_list_pages($args); ``` Or, even cleaner: ``` $args = array( 'post_type' => 'page', 'post_parent__not_in' => array(0), 'no_found_rows' => true, 'fields' => 'ids' ); $child = new WP_Query($args); $args = array( 'include' => $child->posts, ); wp_list_pages($args); ``` Please note that there is no error checking to that code. I'll see if I can spot a clean way to do this with filters. Check back later.
186,062
<p>Original post: <a href="https://wordpress.stackexchange.com/questions/149076/query-between-dates-using-date-picker-fields">Query between dates using Date Picker fields</a></p> <p>I originally made a post last year on this same subject, but seems the update to WP v4.2.1 has broken my filter. In summary, I am using ACF and date picker plugin in an Events custom post type. I am trying to query events between a start and end date. I also have events that can span multiple months. For example, an event may start in april but end in june. I want that event to display in april, may, and june.</p> <p>I had this working using a filter when on v3.9 of wordpress. I'm trying to get wordpress updated on all of my websites, but this filter breaks after updating to v4.2.1. This broke after updating WP 4.2.1 and also after updating ACF to latest version of 4. I have since updated to ACF PRO v5.2.3</p> <p>Does anyone know of a fix?</p> <p>Here is the code that worked great when on WP v3.9.</p> <p>My Event Widge Template:</p> <pre><code>&lt;?php /* Template Name: Events Widget */ $today = date('Ymd'); if (isset($_GET['_m'])) { $current_month = str_pad($_GET['_m'], 2, '0', STR_PAD_LEFT); $current_day = "01"; // day one $current_year = $_GET['_y']; $get_last_day = $current_year.$current_month.$current_day; $lastday = date("t", strtotime($get_last_day)); $tempstartday = $current_year.$current_month.$current_day; $tempendday = $current_year.$current_month.$lastday; $startday = date('Ymd', strtotime($tempstartday)); $endday = date('Ymd', strtotime($tempendday)); } else { $current_month = str_pad(date('m'), 2, '0', STR_PAD_LEFT); $current_day = "01"; // day one $current_year = date('Y'); $get_last_day = $current_year.$current_month.$current_day; $lastday = date("t", strtotime($get_last_day)); $tempstartday = $current_year.$current_month.$current_day; $tempendday = $current_year.$current_month.$lastday; $startday = date('Ymd', strtotime($tempstartday)); $endday = date('Ymd', strtotime($tempendday)); } add_filter( 'get_meta_sql', 'get_meta_sql_date', 10, 2 ); $qryevents = array( 'post_type' =&gt; 'events', 'posts_per_page' =&gt; 50, 'status' =&gt; 'published', 'meta_key' =&gt; 'event_start_date', 'orderby' =&gt; 'meta_value', 'order' =&gt; 'ASC', // produces meta join and where clauses for the query // which will be filtered in functions.php 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'event_start_date', 'compare' =&gt; '&gt;=', 'value' =&gt; $startday, 'type' =&gt; 'DATE' ), array( 'key' =&gt; 'event_end_date', 'compare' =&gt; '&lt;=', 'value' =&gt; $endday, 'type' =&gt; 'DATE' ) ) ); $loop = new WP_Query( $qryevents ); remove_filter( 'get_meta_sql', 'get_meta_sql_date', 10, 2 ); if ( $loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); // Let's format the dates $get_start_date = get_field('event_start_date'); $get_end_date = get_field('event_end_date'); $event_start_date = DateTime::createFromFormat('Ymd', $get_start_date); $event_end_date = DateTime::createFromFormat('Ymd', $get_end_date); // End of date definitions // Let's get the event start and end times $get_start_time = get_field('event_start_time'); $get_end_time = get_field('event_end_time'); // end of times // Let's get the times of the events now $specify_event_time = ""; $show_event_times = get_field('specify_event_times'); if($show_event_times){ foreach($show_event_times as $specify_event_time){ // Do nothing; this puts the yes value into the varible for us to later on the page. // echo $specify_event_time; } } // End of the specify times $event_month_spans = get_field('event_month_span'); ?&gt; &lt;div class="&lt;?php echo (++$j % 2 == 0) ? 'full row' : 'full row alt'; ?&gt;"&gt; &lt;p&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php if($specify_event_time == "yes"): ?&gt; &lt;p class="event-date"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php echo $event_start_date-&gt;format('M d, Y'); ?&gt; &lt;?php echo $get_start_time; ?&gt; - &lt;?php echo $event_end_date-&gt;format('M d, Y'); ?&gt; &lt;?php echo $get_end_time; ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php else: ?&gt; &lt;p class="event-date"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php echo $event_start_date-&gt;format('M d, Y'); ?&gt; - &lt;?php echo $event_end_date-&gt;format('M d, Y'); ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;No scheduled events.&lt;/p&gt; &lt;?php endif; wp_reset_query(); ?&gt; </code></pre> <p>In my functions.php file I have this function:</p> <pre><code>function get_meta_sql_date( $pieces, $queries ) { global $wpdb; // get start and end date from query foreach ( $queries as $q ) { if ( !isset( $q['key'] ) ) { return $pieces; } if ( 'event_start_date' === $q['key'] ) { $start_date = isset( $q['value'] ) ? $q['value'] : ''; } if ( 'event_end_date' === $q['key'] ) { $end_date = isset( $q['value'] ) ? $q['value'] : ''; } } if ( ( '' === $start_date ) || ( '' === $end_date ) ) { return $pieces; } $query = ""; // after start date AND before end date $_query = " AND ( ( $wpdb-&gt;postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb-&gt;postmeta.meta_value AS DATE) &gt;= %s) ) AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) &lt;= %s) ) )"; $query .= $wpdb-&gt;prepare( $_query, $start_date, $end_date ); // OR before start date AND after end date $_query = " OR ( ( $wpdb-&gt;postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb-&gt;postmeta.meta_value AS DATE) &lt;= %s) ) AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) &gt;= %s) ) )"; $query .= $wpdb-&gt;prepare( $_query, $start_date, $end_date ); // OR before start date AND (before end date AND end date after start date) $_query = " OR ( ( $wpdb-&gt;postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb-&gt;postmeta.meta_value AS DATE) &lt;= %s) ) AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) &lt;= %s ) AND ( CAST(mt1.meta_value AS DATE) &gt;= %s ) ) )"; $query .= $wpdb-&gt;prepare( $_query, $start_date, $end_date, $start_date ); // OR after end date AND (after start date AND start date before end date) ) $_query = "OR ( ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) &gt;= %s ) ) AND ( $wpdb-&gt;postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb-&gt;postmeta.meta_value AS DATE) &gt;= %s ) AND ( CAST($wpdb-&gt;postmeta.meta_value AS DATE) &lt;= %s ) ) )"; $query .= $wpdb-&gt;prepare( $_query, $end_date, $start_date, $end_date ); $pieces['where'] = $query; return $pieces; } </code></pre>
[ { "answer_id": 186130, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": false, "text": "<p>There's no need for the custom meta SQL filter - the beauty of storing dates in the format <code>Ymd</code> is that you can treat them numerically, and MySQL will still be able to find events in a given \"range\" and sort them ascending/descending.</p>\n\n<p>I've done this recently on another site using ACF for start/end date:</p>\n\n<pre><code>if ( ! empty( $_GET['_y'] ) )\n $year = absint( $_GET['_y'] );\nelse\n $year = date( 'Y ');\n\nif ( ! empty( $_GET['_m'] ) &amp;&amp; in_array( $month = absint( $_GET['_m'] ), range( 1, 12 ) ) )\n $month = zeroise( $month, 2 );\nelse\n $month = date( 'm' );\n\n$qryevents = array(\n 'post_type' =&gt; 'events',\n 'posts_per_page' =&gt; 50,\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'meta_value_num', // Ensure order is numerically based\n 'order' =&gt; 'ASC',\n\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'key' =&gt; 'event_start_date',\n 'compare' =&gt; '&gt;=',\n 'value' =&gt; \"{$year}{$month}01\",\n 'type' =&gt; 'NUMERIC',\n ),\n array(\n 'key' =&gt; 'event_end_date',\n 'compare' =&gt; '&lt;=',\n 'value' =&gt; \"{$year}{$month}31\", // Doesn't matter if there aren't 31 days in this month, will still work,\n 'type' =&gt; 'NUMERIC',\n )\n )\n);\n</code></pre>\n\n<p>No need for the overly complex date string calculations, and no need for the filter.</p>\n" }, { "answer_id": 193622, "author": "Swati Sharma", "author_id": 74588, "author_profile": "https://wordpress.stackexchange.com/users/74588", "pm_score": 0, "selected": false, "text": "<p>The Date &amp; time utilities utilize a detachment of date &amp; time patterns. The <code>date ()</code> utility revisits the date in this pattern: ‘YYYY-MM-DD’.</p>\n\n<p><a href=\"http://www.inoracle.com/sql-date-functions-oracle/\" rel=\"nofollow\">SQL Date functions oracle</a></p>\n" } ]
2015/05/01
[ "https://wordpress.stackexchange.com/questions/186062", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18119/" ]
Original post: [Query between dates using Date Picker fields](https://wordpress.stackexchange.com/questions/149076/query-between-dates-using-date-picker-fields) I originally made a post last year on this same subject, but seems the update to WP v4.2.1 has broken my filter. In summary, I am using ACF and date picker plugin in an Events custom post type. I am trying to query events between a start and end date. I also have events that can span multiple months. For example, an event may start in april but end in june. I want that event to display in april, may, and june. I had this working using a filter when on v3.9 of wordpress. I'm trying to get wordpress updated on all of my websites, but this filter breaks after updating to v4.2.1. This broke after updating WP 4.2.1 and also after updating ACF to latest version of 4. I have since updated to ACF PRO v5.2.3 Does anyone know of a fix? Here is the code that worked great when on WP v3.9. My Event Widge Template: ``` <?php /* Template Name: Events Widget */ $today = date('Ymd'); if (isset($_GET['_m'])) { $current_month = str_pad($_GET['_m'], 2, '0', STR_PAD_LEFT); $current_day = "01"; // day one $current_year = $_GET['_y']; $get_last_day = $current_year.$current_month.$current_day; $lastday = date("t", strtotime($get_last_day)); $tempstartday = $current_year.$current_month.$current_day; $tempendday = $current_year.$current_month.$lastday; $startday = date('Ymd', strtotime($tempstartday)); $endday = date('Ymd', strtotime($tempendday)); } else { $current_month = str_pad(date('m'), 2, '0', STR_PAD_LEFT); $current_day = "01"; // day one $current_year = date('Y'); $get_last_day = $current_year.$current_month.$current_day; $lastday = date("t", strtotime($get_last_day)); $tempstartday = $current_year.$current_month.$current_day; $tempendday = $current_year.$current_month.$lastday; $startday = date('Ymd', strtotime($tempstartday)); $endday = date('Ymd', strtotime($tempendday)); } add_filter( 'get_meta_sql', 'get_meta_sql_date', 10, 2 ); $qryevents = array( 'post_type' => 'events', 'posts_per_page' => 50, 'status' => 'published', 'meta_key' => 'event_start_date', 'orderby' => 'meta_value', 'order' => 'ASC', // produces meta join and where clauses for the query // which will be filtered in functions.php 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'event_start_date', 'compare' => '>=', 'value' => $startday, 'type' => 'DATE' ), array( 'key' => 'event_end_date', 'compare' => '<=', 'value' => $endday, 'type' => 'DATE' ) ) ); $loop = new WP_Query( $qryevents ); remove_filter( 'get_meta_sql', 'get_meta_sql_date', 10, 2 ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); // Let's format the dates $get_start_date = get_field('event_start_date'); $get_end_date = get_field('event_end_date'); $event_start_date = DateTime::createFromFormat('Ymd', $get_start_date); $event_end_date = DateTime::createFromFormat('Ymd', $get_end_date); // End of date definitions // Let's get the event start and end times $get_start_time = get_field('event_start_time'); $get_end_time = get_field('event_end_time'); // end of times // Let's get the times of the events now $specify_event_time = ""; $show_event_times = get_field('specify_event_times'); if($show_event_times){ foreach($show_event_times as $specify_event_time){ // Do nothing; this puts the yes value into the varible for us to later on the page. // echo $specify_event_time; } } // End of the specify times $event_month_spans = get_field('event_month_span'); ?> <div class="<?php echo (++$j % 2 == 0) ? 'full row' : 'full row alt'; ?>"> <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p> <?php if($specify_event_time == "yes"): ?> <p class="event-date"><a href="<?php the_permalink(); ?>"><?php echo $event_start_date->format('M d, Y'); ?> <?php echo $get_start_time; ?> - <?php echo $event_end_date->format('M d, Y'); ?> <?php echo $get_end_time; ?></a></p> <?php else: ?> <p class="event-date"><a href="<?php the_permalink(); ?>"><?php echo $event_start_date->format('M d, Y'); ?> - <?php echo $event_end_date->format('M d, Y'); ?></a></p> <?php endif; ?> </div> <?php endwhile; else: ?> <p>No scheduled events.</p> <?php endif; wp_reset_query(); ?> ``` In my functions.php file I have this function: ``` function get_meta_sql_date( $pieces, $queries ) { global $wpdb; // get start and end date from query foreach ( $queries as $q ) { if ( !isset( $q['key'] ) ) { return $pieces; } if ( 'event_start_date' === $q['key'] ) { $start_date = isset( $q['value'] ) ? $q['value'] : ''; } if ( 'event_end_date' === $q['key'] ) { $end_date = isset( $q['value'] ) ? $q['value'] : ''; } } if ( ( '' === $start_date ) || ( '' === $end_date ) ) { return $pieces; } $query = ""; // after start date AND before end date $_query = " AND ( ( $wpdb->postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb->postmeta.meta_value AS DATE) >= %s) ) AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) <= %s) ) )"; $query .= $wpdb->prepare( $_query, $start_date, $end_date ); // OR before start date AND after end date $_query = " OR ( ( $wpdb->postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb->postmeta.meta_value AS DATE) <= %s) ) AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) >= %s) ) )"; $query .= $wpdb->prepare( $_query, $start_date, $end_date ); // OR before start date AND (before end date AND end date after start date) $_query = " OR ( ( $wpdb->postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb->postmeta.meta_value AS DATE) <= %s) ) AND ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) <= %s ) AND ( CAST(mt1.meta_value AS DATE) >= %s ) ) )"; $query .= $wpdb->prepare( $_query, $start_date, $end_date, $start_date ); // OR after end date AND (after start date AND start date before end date) ) $_query = "OR ( ( mt1.meta_key = 'event_end_date' AND ( CAST(mt1.meta_value AS DATE) >= %s ) ) AND ( $wpdb->postmeta.meta_key = 'event_start_date' AND ( CAST($wpdb->postmeta.meta_value AS DATE) >= %s ) AND ( CAST($wpdb->postmeta.meta_value AS DATE) <= %s ) ) )"; $query .= $wpdb->prepare( $_query, $end_date, $start_date, $end_date ); $pieces['where'] = $query; return $pieces; } ```
There's no need for the custom meta SQL filter - the beauty of storing dates in the format `Ymd` is that you can treat them numerically, and MySQL will still be able to find events in a given "range" and sort them ascending/descending. I've done this recently on another site using ACF for start/end date: ``` if ( ! empty( $_GET['_y'] ) ) $year = absint( $_GET['_y'] ); else $year = date( 'Y '); if ( ! empty( $_GET['_m'] ) && in_array( $month = absint( $_GET['_m'] ), range( 1, 12 ) ) ) $month = zeroise( $month, 2 ); else $month = date( 'm' ); $qryevents = array( 'post_type' => 'events', 'posts_per_page' => 50, 'post_status' => 'publish', 'orderby' => 'meta_value_num', // Ensure order is numerically based 'order' => 'ASC', 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'event_start_date', 'compare' => '>=', 'value' => "{$year}{$month}01", 'type' => 'NUMERIC', ), array( 'key' => 'event_end_date', 'compare' => '<=', 'value' => "{$year}{$month}31", // Doesn't matter if there aren't 31 days in this month, will still work, 'type' => 'NUMERIC', ) ) ); ``` No need for the overly complex date string calculations, and no need for the filter.
186,069
<p>I can get <code>wp_logout</code> to work, but not without generating lots of warnings ('PHP warning: Cannot modify header information - headers already sent'). </p> <p><code>wp_logout</code> calls <code>wp_clear_auth_cookie</code>, which calls <code>setcookie</code>, and the cookies have to go with the HTTP headers. I'm calling <code>wp_logout</code> inside the page (in the header or footer), hence the problem.</p> <p>So, how exactly am I meant to programmatically log a user out? I could do this in response to an ajax request, but that seems way over the top. Thanks.</p> <p><em>EDIT</em></p> <p>Current code as follows:</p> <pre><code>add_action('wp_footer', 'fp_onload_php2'); function fp_onload_php2() { $slug = basename(get_permalink()); if($slug != 'club-login') return; $jsmsg = ''; $loggedin = false; if(is_user_logged_in()) { $current_user = wp_get_current_user(); $loggedin = $current_user-&gt;has_cap('customer'); } if($loggedin &amp;&amp; isset($_GET['logout'])) { wp_logout(); $jsmsg = 'You have been logged out.'; $loggedin = false; } else if(!$loggedin &amp;&amp; isset($_GET['logout'])) $jsmsg = "You are not logged in."; if(!$loggedin) echo "&lt;script type='text/javascript'&gt; fp_onload_js2(0, '" . $jsmsg . "'); &lt;/script&gt;\n"; else echo "&lt;script type='text/javascript'&gt; fp_onload_js2(1, '" . $jsmsg . "'); &lt;/script&gt;\n"; } // fp_onload_php2() </code></pre>
[ { "answer_id": 186345, "author": "EML", "author_id": 69329, "author_profile": "https://wordpress.stackexchange.com/users/69329", "pm_score": 0, "selected": false, "text": "<p>This isn't great, but seems to work. It's not as simple as calling <code>wp_logout</code> before any content is sent, because the user may or may not be logged out before the rest of the page loads (I don't understand this). In my case, the page contents depend on whether or not the user is actually logged in (the menus change, and some JS code is called to display content differently).</p>\n\n<p>for this code, a logout request redirects to the login page, with a GET parameter of <code>logout=1</code>. This is tested on the login page, which then calls <code>wp_logout</code>, and redirects back to the login page with a GET parameter of <code>logout=0</code>, to force a refresh.</p>\n\n<pre><code>add_action('init', 'check_logout');\n\nfunction check_logout() {\n if(!isset($_GET['logout']) || ($_GET['logout'] != '1'))\n return;\n\n // get_permalink() and $post are not available here, so:\n $path = parse_url($_SERVER[\"REQUEST_URI\"], PHP_URL_PATH);\n if($path != \"/login/\")\n return;\n\n if(is_user_logged_in()) {\n wp_logout();\n header(\"Location: http://fubar.com/login/?logout=0\");\n exit();\n } \n} // check_logout()\n</code></pre>\n" }, { "answer_id": 216232, "author": "Vasim Shaikh", "author_id": 87704, "author_profile": "https://wordpress.stackexchange.com/users/87704", "pm_score": 3, "selected": false, "text": "<p>If you're using <code>wp_logout</code> in your own code, its probably best to <code>exit</code> or <code>wp_redirect</code> immediately afterwards.</p>\n\n<p>You can call <code>wp_set_current_user(0)</code> after <code>wp_logout()</code> to manually log the user out instantly, if you need to continue executing PHP but don't want the user to be logged in.</p>\n" } ]
2015/05/01
[ "https://wordpress.stackexchange.com/questions/186069", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69329/" ]
I can get `wp_logout` to work, but not without generating lots of warnings ('PHP warning: Cannot modify header information - headers already sent'). `wp_logout` calls `wp_clear_auth_cookie`, which calls `setcookie`, and the cookies have to go with the HTTP headers. I'm calling `wp_logout` inside the page (in the header or footer), hence the problem. So, how exactly am I meant to programmatically log a user out? I could do this in response to an ajax request, but that seems way over the top. Thanks. *EDIT* Current code as follows: ``` add_action('wp_footer', 'fp_onload_php2'); function fp_onload_php2() { $slug = basename(get_permalink()); if($slug != 'club-login') return; $jsmsg = ''; $loggedin = false; if(is_user_logged_in()) { $current_user = wp_get_current_user(); $loggedin = $current_user->has_cap('customer'); } if($loggedin && isset($_GET['logout'])) { wp_logout(); $jsmsg = 'You have been logged out.'; $loggedin = false; } else if(!$loggedin && isset($_GET['logout'])) $jsmsg = "You are not logged in."; if(!$loggedin) echo "<script type='text/javascript'> fp_onload_js2(0, '" . $jsmsg . "'); </script>\n"; else echo "<script type='text/javascript'> fp_onload_js2(1, '" . $jsmsg . "'); </script>\n"; } // fp_onload_php2() ```
If you're using `wp_logout` in your own code, its probably best to `exit` or `wp_redirect` immediately afterwards. You can call `wp_set_current_user(0)` after `wp_logout()` to manually log the user out instantly, if you need to continue executing PHP but don't want the user to be logged in.
186,071
<p>In the WP Admin panel, I have a plugin that does certain calculations based on input from a form. I need it to print pretty, so I am attempting to render the plugin page without the admin menu etc.</p> <p>I thought that <code>remove_action( 'wp_footer', 'wp_admin_bar_render', 10000 );</code> would accomplish this, but it seems to not be working as it still renders the admin panel, and not just a blank white page.</p> <p>Here's what I have:</p> <pre><code>public function cpui_setup() { add_submenu_page( NULL, __( 'WooCommerce Print Order Recipe', 'woocommerce' ), __( 'Print Recipe', 'woocommerce' ) , 'manage_woocommerce', 'cpui_print_recipe', array( $this, 'print_recipe_page' ) ); } public function print_recipe_page() { remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); require_once( 'admin/print_recipe.php' ); } ... </code></pre> <p>What am I overlooking?</p>
[ { "answer_id": 186080, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 0, "selected": false, "text": "<p>If you will disable the admin bar for all users on this page, use this </p>\n\n<pre><code>wp_deregister_script( 'admin-bar' );\n wp_deregister_style( 'admin-bar' );\n remove_action( 'init', '_wp_admin_bar_init' ); \n remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); \n remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 ); \n</code></pre>\n\n<p>in a function, where you check for your plugin page, like with <code>get_current_sreen()</code>. The <a href=\"https://codex.wordpress.org/Function_Reference/get_current_screen\" rel=\"nofollow\">codex</a> have all information and examples.</p>\n" }, { "answer_id": 186086, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>In modern WordPress toolbar is considered <em>mandatory</em> part of admin. That is WordPress is explicitly opinionated about not letting you to disable it. While you still can kind of hack it out, it's unnecessary struggle.</p>\n\n<p>If you need a blank page there is no reason to struggle with blanking admin interface for it. You could simply use <code>wp-admin/admin-post.php</code> to handle your form. Ajax endpoint would work just as well, or maybe even custom \"pretty\" URL endpoint.</p>\n" } ]
2015/05/01
[ "https://wordpress.stackexchange.com/questions/186071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50860/" ]
In the WP Admin panel, I have a plugin that does certain calculations based on input from a form. I need it to print pretty, so I am attempting to render the plugin page without the admin menu etc. I thought that `remove_action( 'wp_footer', 'wp_admin_bar_render', 10000 );` would accomplish this, but it seems to not be working as it still renders the admin panel, and not just a blank white page. Here's what I have: ``` public function cpui_setup() { add_submenu_page( NULL, __( 'WooCommerce Print Order Recipe', 'woocommerce' ), __( 'Print Recipe', 'woocommerce' ) , 'manage_woocommerce', 'cpui_print_recipe', array( $this, 'print_recipe_page' ) ); } public function print_recipe_page() { remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); require_once( 'admin/print_recipe.php' ); } ... ``` What am I overlooking?
In modern WordPress toolbar is considered *mandatory* part of admin. That is WordPress is explicitly opinionated about not letting you to disable it. While you still can kind of hack it out, it's unnecessary struggle. If you need a blank page there is no reason to struggle with blanking admin interface for it. You could simply use `wp-admin/admin-post.php` to handle your form. Ajax endpoint would work just as well, or maybe even custom "pretty" URL endpoint.
186,119
<p>I have a custom table in database named <code>wp_tasks</code> which has 5 fields. </p> <p>But I am unable to insert the current time to <code>assign_date</code> field.</p> <p><strong>wp_tasks table</strong></p> <pre><code>id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, worker_id INT(6) , project_id INT(6), work_id INT(6), assign_date DATETIME </code></pre> <p><strong>Inserting records</strong></p> <pre><code>function insert_record_to_db( $worker_id, $work_id, $project_id ){ global $wpdb; $tablename = $wpdb-&gt;prefix.'tasks'; $data = array( 'id' =&gt; "", 'worker_id' =&gt; $worker_id, 'project_id' =&gt; $project_id, 'work_id' =&gt; $work_id, 'assign_date' =&gt; date( "Y-m-d H:i:s" ) ); $format= array( '%d', '%d', '%d','%s'); $wpdb-&gt;insert( $tablename, $data, $format ); } </code></pre> <p>What is the problem?</p>
[ { "answer_id": 186105, "author": "Ibrahim", "author_id": 30773, "author_profile": "https://wordpress.stackexchange.com/users/30773", "pm_score": 0, "selected": false, "text": "<p>You can not get \"list of all\" wordpress plugin from api.wordpress , this api is set to display information about single plugin when you pass it a plugin slug. </p>\n\n<p>To get list of all published wordpress plugins you can try this page <a href=\"http://plugins.svn.wordpress.org/\" rel=\"nofollow\">http://plugins.svn.wordpress.org/</a> or You can scrape plugin slug from this page <a href=\"https://wordpress.org/plugins\" rel=\"nofollow\">https://wordpress.org/plugins</a></p>\n" }, { "answer_id": 186111, "author": "Paras Shah", "author_id": 71530, "author_profile": "https://wordpress.stackexchange.com/users/71530", "pm_score": 2, "selected": false, "text": "<p>Guys I found the answer.\nWell, after a lot of changes in codes, I finally did it through API.</p>\n\n<p>Through that PHP page, you can search in any plugin which exist in Wordpress Repository.</p>\n\n<p>Sorry, I cannot include the code because it's too long.</p>\n\n<p>Basically, I am just listing down in short what exactly I did.</p>\n\n<p>First of all I included a PHP cURL script through CallAPI function. (I copied the same script which is included in the most-voted answer of this question: <a href=\"https://stackoverflow.com/questions/21182946/using-curl-to-get-api-data-within-php\">https://stackoverflow.com/questions/21182946/using-curl-to-get-api-data-within-php</a>)</p>\n\n<p>Then, I added actions and requests to that PHP script as explained here: <a href=\"http://code.tutsplus.com/articles/interacting-with-wordpress-plug-in-theme-api--wp-25805\" rel=\"nofollow noreferrer\">http://code.tutsplus.com/articles/interacting-with-wordpress-plug-in-theme-api--wp-25805</a></p>\n\n<p>After this, I unserialized the execution of the CallAPI function</p>\n\n<p>Through this, I got all the info that I needed.\nFinally, I then made a table in foreach loop so that details of each and every plugin will show up by loop according to what I wanted to show.</p>\n\n<p>For eg: I only wanted to show the Name, Author, Plugin Version and Downloads. So, according to that I changed the elements of the table.</p>\n\n<p>Through this, I can see 25 last updated wordpress plugins on opening that PHP page and when searched, I can find out any plugin from the Wordpress Repository.</p>\n\n<p>The only thing which is missing is live AJAX search which I am trying to implement now.</p>\n\n<p>Hope this explanation will help you guys.</p>\n\n<p>After shortening that code, I'll add it here. (If possible!)</p>\n" } ]
2015/05/02
[ "https://wordpress.stackexchange.com/questions/186119", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71448/" ]
I have a custom table in database named `wp_tasks` which has 5 fields. But I am unable to insert the current time to `assign_date` field. **wp\_tasks table** ``` id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, worker_id INT(6) , project_id INT(6), work_id INT(6), assign_date DATETIME ``` **Inserting records** ``` function insert_record_to_db( $worker_id, $work_id, $project_id ){ global $wpdb; $tablename = $wpdb->prefix.'tasks'; $data = array( 'id' => "", 'worker_id' => $worker_id, 'project_id' => $project_id, 'work_id' => $work_id, 'assign_date' => date( "Y-m-d H:i:s" ) ); $format= array( '%d', '%d', '%d','%s'); $wpdb->insert( $tablename, $data, $format ); } ``` What is the problem?
Guys I found the answer. Well, after a lot of changes in codes, I finally did it through API. Through that PHP page, you can search in any plugin which exist in Wordpress Repository. Sorry, I cannot include the code because it's too long. Basically, I am just listing down in short what exactly I did. First of all I included a PHP cURL script through CallAPI function. (I copied the same script which is included in the most-voted answer of this question: <https://stackoverflow.com/questions/21182946/using-curl-to-get-api-data-within-php>) Then, I added actions and requests to that PHP script as explained here: <http://code.tutsplus.com/articles/interacting-with-wordpress-plug-in-theme-api--wp-25805> After this, I unserialized the execution of the CallAPI function Through this, I got all the info that I needed. Finally, I then made a table in foreach loop so that details of each and every plugin will show up by loop according to what I wanted to show. For eg: I only wanted to show the Name, Author, Plugin Version and Downloads. So, according to that I changed the elements of the table. Through this, I can see 25 last updated wordpress plugins on opening that PHP page and when searched, I can find out any plugin from the Wordpress Repository. The only thing which is missing is live AJAX search which I am trying to implement now. Hope this explanation will help you guys. After shortening that code, I'll add it here. (If possible!)
186,126
<p>I understand there are 2 different types when it comes to a custom post type: -page -post. </p> <p>Where <strong>page</strong> supports child pages, and <strong>post</strong> does not. </p> <p>However, when i try to make a child page with only numbers in it's slug, wordpress puts -2 behind it. Example:</p> <p>/posttype/parent/10-2/</p> <p>instead of what i would have wanted:</p> <p>/posttype/parent/10/</p> <p>Why is this, and how can i solve it? I have searched for hours, but i can't seem to find a solution, other than it's perhaps a limitation in Wordpress, do to a conflict with it's date permalink system. I'm not using this system, but could this be true?</p> <p>EDIT, some more information: There are no posts whatsoever which can conflict with my permalink. The permalink is definitely not taken.</p> <p>I get this behaviour with a completely new install of wordpress, and only 1 custom post type. The only posts in the wordpress database are 'parent' and '02'. Where '02' turns into '02-2'. </p> <p>I was wondering if maybe pagination /slug/page/02 was maybe the reason numeric slugs were not accepted? </p> <p>It is important to note, I only get this with numeric slugs, /parent/child/ is not a problem.</p> <p>I've seen something about overriding the filters, but won't that simply hide the problem? I prefer to solve it.</p> <p>The code I use to register my custom post type:</p> <pre><code> $labels = array( 'name' =&gt; _x( $options['euthus_posttype_meervoud'], 'Post Type General Name', 'text_domain' ), 'singular_name' =&gt; _x( $options['euthus_posttype'], 'Post Type Singular Name', 'text_domain' ), 'menu_name' =&gt; __( $options['euthus_posttype_meervoud'], 'text_domain' ), 'name_admin_bar' =&gt; __( $options['euthus_posttype_meervoud'], 'text_domain' ), 'parent_item_colon' =&gt; __( 'Parent Item:', 'text_domain' ), 'all_items' =&gt; __( 'All Items', 'text_domain' ), 'add_new_item' =&gt; __( 'Add New Item', 'text_domain' ), 'add_new' =&gt; __( 'Add New', 'text_domain' ), 'new_item' =&gt; __( 'New Item', 'text_domain' ), 'edit_item' =&gt; __( 'Edit Item', 'text_domain' ), 'update_item' =&gt; __( 'Update Item', 'text_domain' ), 'view_item' =&gt; __( 'View Item', 'text_domain' ), 'search_items' =&gt; __( 'Search Item', 'text_domain' ), 'not_found' =&gt; __( 'Not found', 'text_domain' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'text_domain' ), ); $rewrite = array( 'slug' =&gt; $options['euthus_posttype_baseurl'], 'with_front' =&gt; true, 'pages' =&gt; false, 'feeds' =&gt; true, ); $args = array( 'label' =&gt; __( 'euthus_childs', 'text_domain' ), 'description' =&gt; __( $options['euthus_posttype_meervoud'], 'text_domain' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'thumbnail', 'page-attributes',), 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 20, 'menu_icon' =&gt; 'dashicons-networking', 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; true, 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'rewrite' =&gt; $rewrite, 'capability_type' =&gt; 'page', ); register_post_type( 'euthus_childs', $args ); </code></pre> <p>As I understand, the 'capability_type' must be set to <strong>page</strong> and not <strong>post</strong> to allow for hierarchical, where setting it to 'post' does not allow this. </p>
[ { "answer_id": 186145, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>It would be more correct to say that CPTs can be hierarchical and non–hierarchical. Page and post are just respective examples of such, and by the way as native post types they aren't quite the same thing as CPTs.</p>\n\n<p>Clearly, when you have multiple CPTs in a site it's important that not a single combination of slugs leads to <em>ambiguous</em> permalink, that might refer to more than one post.</p>\n\n<p>When WP generates post slugs <a href=\"http://queryposts.com/function/wp_unique_post_slug/\" rel=\"nofollow\"><code>wp_unique_post_slug()</code></a> checks and modifies slug as necessary to achieve that.</p>\n\n<p>It is hard to guess with certainty why your specific slug gets modified, without seeing rest of the data.</p>\n\n<p>In a nutshell:</p>\n\n<ul>\n<li>WP considers it to be insufficiently unique</li>\n<li>there are filters that allow you to override this behavior</li>\n<li>however enforcing non–unique slug <em>might</em> explode in interesting ways</li>\n</ul>\n" }, { "answer_id": 187659, "author": "bonger", "author_id": 57034, "author_profile": "https://wordpress.stackexchange.com/users/57034", "pm_score": 3, "selected": true, "text": "<p>As you guessed and @Rarst suspected, there's a pagination check in <code>wp_unique_post_slug()</code> for hierarchical post types:</p>\n\n<pre><code>preg_match( \"@^($wp_rewrite-&gt;pagination_base)?\\d+$@\", $slug )\n</code></pre>\n\n<p>which will match any numeric only slug, optionally preceded by \"page\". To get around this you could use the <code>'wp_unique_post_slug'</code> filter, basically replicating the original code without the pagination check, eg</p>\n\n<pre><code>add_filter( 'wp_unique_post_slug', function ( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {\n if ( $slug !== $original_slug &amp;&amp; is_post_type_hierarchical( $post_type ) ) {\n\n global $wpdb, $wp_rewrite;\n\n $slug = $original_slug; // Undo any previous processing.\n\n // The following is just a copy &amp; paste of the WP code without the pagination check.\n $feeds = $wp_rewrite-&gt;feeds;\n if ( ! is_array( $feeds ) )\n $feeds = array();\n\n if ( 'nav_menu_item' == $post_type )\n return $slug;\n\n /*\n * Page slugs must be unique within their own trees. Pages are in a separate\n * namespace than posts so page slugs are allowed to overlap post slugs.\n */\n $check_sql = \"SELECT post_name FROM $wpdb-&gt;posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1\";\n $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );\n\n /**\n * Filter whether the post slug would make a bad hierarchical post slug.\n *\n * @since 3.1.0\n *\n * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.\n * @param string $slug The post slug.\n * @param string $post_type Post type.\n * @param int $post_parent Post parent ID.\n */\n if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {\n $suffix = 2;\n do {\n $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . \"-$suffix\";\n $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );\n $suffix++;\n } while ( $post_name_check );\n $slug = $alt_post_name;\n }\n }\n return $slug;\n}, 10, 6 );\n</code></pre>\n" } ]
2015/05/02
[ "https://wordpress.stackexchange.com/questions/186126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64516/" ]
I understand there are 2 different types when it comes to a custom post type: -page -post. Where **page** supports child pages, and **post** does not. However, when i try to make a child page with only numbers in it's slug, wordpress puts -2 behind it. Example: /posttype/parent/10-2/ instead of what i would have wanted: /posttype/parent/10/ Why is this, and how can i solve it? I have searched for hours, but i can't seem to find a solution, other than it's perhaps a limitation in Wordpress, do to a conflict with it's date permalink system. I'm not using this system, but could this be true? EDIT, some more information: There are no posts whatsoever which can conflict with my permalink. The permalink is definitely not taken. I get this behaviour with a completely new install of wordpress, and only 1 custom post type. The only posts in the wordpress database are 'parent' and '02'. Where '02' turns into '02-2'. I was wondering if maybe pagination /slug/page/02 was maybe the reason numeric slugs were not accepted? It is important to note, I only get this with numeric slugs, /parent/child/ is not a problem. I've seen something about overriding the filters, but won't that simply hide the problem? I prefer to solve it. The code I use to register my custom post type: ``` $labels = array( 'name' => _x( $options['euthus_posttype_meervoud'], 'Post Type General Name', 'text_domain' ), 'singular_name' => _x( $options['euthus_posttype'], 'Post Type Singular Name', 'text_domain' ), 'menu_name' => __( $options['euthus_posttype_meervoud'], 'text_domain' ), 'name_admin_bar' => __( $options['euthus_posttype_meervoud'], 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'all_items' => __( 'All Items', 'text_domain' ), 'add_new_item' => __( 'Add New Item', 'text_domain' ), 'add_new' => __( 'Add New', 'text_domain' ), 'new_item' => __( 'New Item', 'text_domain' ), 'edit_item' => __( 'Edit Item', 'text_domain' ), 'update_item' => __( 'Update Item', 'text_domain' ), 'view_item' => __( 'View Item', 'text_domain' ), 'search_items' => __( 'Search Item', 'text_domain' ), 'not_found' => __( 'Not found', 'text_domain' ), 'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ), ); $rewrite = array( 'slug' => $options['euthus_posttype_baseurl'], 'with_front' => true, 'pages' => false, 'feeds' => true, ); $args = array( 'label' => __( 'euthus_childs', 'text_domain' ), 'description' => __( $options['euthus_posttype_meervoud'], 'text_domain' ), 'labels' => $labels, 'supports' => array( 'title', 'thumbnail', 'page-attributes',), 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 20, 'menu_icon' => 'dashicons-networking', 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'rewrite' => $rewrite, 'capability_type' => 'page', ); register_post_type( 'euthus_childs', $args ); ``` As I understand, the 'capability\_type' must be set to **page** and not **post** to allow for hierarchical, where setting it to 'post' does not allow this.
As you guessed and @Rarst suspected, there's a pagination check in `wp_unique_post_slug()` for hierarchical post types: ``` preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) ``` which will match any numeric only slug, optionally preceded by "page". To get around this you could use the `'wp_unique_post_slug'` filter, basically replicating the original code without the pagination check, eg ``` add_filter( 'wp_unique_post_slug', function ( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) { if ( $slug !== $original_slug && is_post_type_hierarchical( $post_type ) ) { global $wpdb, $wp_rewrite; $slug = $original_slug; // Undo any previous processing. // The following is just a copy & paste of the WP code without the pagination check. $feeds = $wp_rewrite->feeds; if ( ! is_array( $feeds ) ) $feeds = array(); if ( 'nav_menu_item' == $post_type ) return $slug; /* * Page slugs must be unique within their own trees. Pages are in a separate * namespace than posts so page slugs are allowed to overlap post slugs. */ $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) ); /** * Filter whether the post slug would make a bad hierarchical post slug. * * @since 3.1.0 * * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context. * @param string $slug The post slug. * @param string $post_type Post type. * @param int $post_parent Post parent ID. */ if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) { $suffix = 2; do { $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } return $slug; }, 10, 6 ); ```
186,128
<p>My question title might be little confuse. Here is the scenario, For example: I am giving an API service from my wordpress site.</p> <p>Using it others can know few information. Like if they send a User ID in query URL then i'll send them user phone number.</p> <p>For Example: If they access the site with <code>www.example.com/?cuid=23</code></p> <p>Now on <code>init</code> hook i'll check if <code>cuid</code> is present in <code>$_GET</code> variable, if it is present then i'll get phone number and die the function with phone number. Since <code>init</code> hook is the earliest hook i choose to use it.</p> <pre><code>function tell_phone_num(){ if(isset($_GET['cuid'])){ //some one wants the service //I'll get the phone number and show it -&gt; $user_phone //setting response format, like json etc die($user_phone); } } add_action('init','tell_phone_num'); </code></pre> <p>This works fine. When site is accessed with <code>cuid</code> then only this function will work.</p> <p>This is just an example but phone number is not my real information. I don't need authentication because the information i am giving in are not sensitive.</p> <p>Here is my question. Is this correct way to do or should I do some other best practice method.</p>
[ { "answer_id": 186131, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 0, "selected": false, "text": "<p>Yes, <code>init</code> is good for this purpose. In <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow\">codex</a> is written:</p>\n\n<blockquote>\n <p>init is useful for intercepting $_GET or $_POST triggers.</p>\n</blockquote>\n" }, { "answer_id": 186133, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>If you want a more user-friendly URL structure, you could <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">add a rewrite endpoint</a>.</p>\n\n<p>This will add the rules for and intercept requests to <code>/my-api/</code>:</p>\n\n<pre><code>function wpd_add_api_endpoint() {\n add_rewrite_endpoint( 'my-api', EP_ROOT );\n}\nadd_action( 'init', 'wpd_add_api_endpoint' );\n\nfunction wpd_api_request( $request ){\n if( isset( $request-&gt;query_vars['my-api'] ) ){\n\n // $request-&gt;query_vars['my-api'] is a string containing everything after your url slug\n // convert it to array\n $parts = explode( '/', $request-&gt;query_vars['my-api'] );\n\n echo '&lt;pre&gt;';\n print_r( $parts );\n echo '&lt;/pre&gt;';\n\n die;\n }\n}\nadd_action( 'parse_request', 'wpd_api_request' );\n</code></pre>\n\n<p>After you flush rules, try a request like:</p>\n\n<blockquote>\n <p><a href=\"http://example.com/my-api/something/else/123/4,5,6/&amp;7\" rel=\"nofollow\">http://example.com/my-api/something/else/123/4,5,6/&amp;7</a></p>\n</blockquote>\n\n<p>Which will output:</p>\n\n<pre><code>Array\n(\n [0] =&gt; something\n [1] =&gt; else\n [2] =&gt; 123\n [3] =&gt; 4,5,6\n [4] =&gt; &amp;7\n)\n</code></pre>\n" } ]
2015/05/02
[ "https://wordpress.stackexchange.com/questions/186128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37102/" ]
My question title might be little confuse. Here is the scenario, For example: I am giving an API service from my wordpress site. Using it others can know few information. Like if they send a User ID in query URL then i'll send them user phone number. For Example: If they access the site with `www.example.com/?cuid=23` Now on `init` hook i'll check if `cuid` is present in `$_GET` variable, if it is present then i'll get phone number and die the function with phone number. Since `init` hook is the earliest hook i choose to use it. ``` function tell_phone_num(){ if(isset($_GET['cuid'])){ //some one wants the service //I'll get the phone number and show it -> $user_phone //setting response format, like json etc die($user_phone); } } add_action('init','tell_phone_num'); ``` This works fine. When site is accessed with `cuid` then only this function will work. This is just an example but phone number is not my real information. I don't need authentication because the information i am giving in are not sensitive. Here is my question. Is this correct way to do or should I do some other best practice method.
If you want a more user-friendly URL structure, you could [add a rewrite endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). This will add the rules for and intercept requests to `/my-api/`: ``` function wpd_add_api_endpoint() { add_rewrite_endpoint( 'my-api', EP_ROOT ); } add_action( 'init', 'wpd_add_api_endpoint' ); function wpd_api_request( $request ){ if( isset( $request->query_vars['my-api'] ) ){ // $request->query_vars['my-api'] is a string containing everything after your url slug // convert it to array $parts = explode( '/', $request->query_vars['my-api'] ); echo '<pre>'; print_r( $parts ); echo '</pre>'; die; } } add_action( 'parse_request', 'wpd_api_request' ); ``` After you flush rules, try a request like: > > <http://example.com/my-api/something/else/123/4,5,6/&7> > > > Which will output: ``` Array ( [0] => something [1] => else [2] => 123 [3] => 4,5,6 [4] => &7 ) ```
186,150
<p>I've searched many places and tried many ways for this but no success.</p> <p>I have a shortcode in my WP Theme like;</p> <pre><code>[recent_posts layout="thumbnails-on-side" columns="4" number_posts="4" offset="" cat_slug="" exclude_cats="" thumbnail="yes" title="no" meta="no" excerpt="no" excerpt_length="35" strip_html="yes" animation_type="0" animation_direction="down" animation_speed="0.1" class="" id=""][/recent_posts] </code></pre> <p>(It is Avada theme's recent posts shortcode). In the core, this shortcode executes </p> <pre><code>WP_Query( $args ) </code></pre> <p>function to get posts. But this shortcode cannot be used with Custom Post Types because coders didn't put 'post_type' attribute to shortcode $args (so because of default value is 'posts', shortcode only fetches standard posts).</p> <p>As a result, i would like to extend/define new extended version of this shortcode for adding 'post_type' attribute <strong>as a variable</strong> (because i would like to use it for many custom post types). How can i do that? Thanks.</p>
[ { "answer_id": 186131, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 0, "selected": false, "text": "<p>Yes, <code>init</code> is good for this purpose. In <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow\">codex</a> is written:</p>\n\n<blockquote>\n <p>init is useful for intercepting $_GET or $_POST triggers.</p>\n</blockquote>\n" }, { "answer_id": 186133, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>If you want a more user-friendly URL structure, you could <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">add a rewrite endpoint</a>.</p>\n\n<p>This will add the rules for and intercept requests to <code>/my-api/</code>:</p>\n\n<pre><code>function wpd_add_api_endpoint() {\n add_rewrite_endpoint( 'my-api', EP_ROOT );\n}\nadd_action( 'init', 'wpd_add_api_endpoint' );\n\nfunction wpd_api_request( $request ){\n if( isset( $request-&gt;query_vars['my-api'] ) ){\n\n // $request-&gt;query_vars['my-api'] is a string containing everything after your url slug\n // convert it to array\n $parts = explode( '/', $request-&gt;query_vars['my-api'] );\n\n echo '&lt;pre&gt;';\n print_r( $parts );\n echo '&lt;/pre&gt;';\n\n die;\n }\n}\nadd_action( 'parse_request', 'wpd_api_request' );\n</code></pre>\n\n<p>After you flush rules, try a request like:</p>\n\n<blockquote>\n <p><a href=\"http://example.com/my-api/something/else/123/4,5,6/&amp;7\" rel=\"nofollow\">http://example.com/my-api/something/else/123/4,5,6/&amp;7</a></p>\n</blockquote>\n\n<p>Which will output:</p>\n\n<pre><code>Array\n(\n [0] =&gt; something\n [1] =&gt; else\n [2] =&gt; 123\n [3] =&gt; 4,5,6\n [4] =&gt; &amp;7\n)\n</code></pre>\n" } ]
2015/05/02
[ "https://wordpress.stackexchange.com/questions/186150", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3405/" ]
I've searched many places and tried many ways for this but no success. I have a shortcode in my WP Theme like; ``` [recent_posts layout="thumbnails-on-side" columns="4" number_posts="4" offset="" cat_slug="" exclude_cats="" thumbnail="yes" title="no" meta="no" excerpt="no" excerpt_length="35" strip_html="yes" animation_type="0" animation_direction="down" animation_speed="0.1" class="" id=""][/recent_posts] ``` (It is Avada theme's recent posts shortcode). In the core, this shortcode executes ``` WP_Query( $args ) ``` function to get posts. But this shortcode cannot be used with Custom Post Types because coders didn't put 'post\_type' attribute to shortcode $args (so because of default value is 'posts', shortcode only fetches standard posts). As a result, i would like to extend/define new extended version of this shortcode for adding 'post\_type' attribute **as a variable** (because i would like to use it for many custom post types). How can i do that? Thanks.
If you want a more user-friendly URL structure, you could [add a rewrite endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). This will add the rules for and intercept requests to `/my-api/`: ``` function wpd_add_api_endpoint() { add_rewrite_endpoint( 'my-api', EP_ROOT ); } add_action( 'init', 'wpd_add_api_endpoint' ); function wpd_api_request( $request ){ if( isset( $request->query_vars['my-api'] ) ){ // $request->query_vars['my-api'] is a string containing everything after your url slug // convert it to array $parts = explode( '/', $request->query_vars['my-api'] ); echo '<pre>'; print_r( $parts ); echo '</pre>'; die; } } add_action( 'parse_request', 'wpd_api_request' ); ``` After you flush rules, try a request like: > > <http://example.com/my-api/something/else/123/4,5,6/&7> > > > Which will output: ``` Array ( [0] => something [1] => else [2] => 123 [3] => 4,5,6 [4] => &7 ) ```
186,195
<p>I want to get all info of top level menu from childrens</p> <pre><code>&lt;li class="l-nav-item dropdown"&gt;&lt;button class="open-icon visible-xs fa fa-angle-down"&gt;&lt;/button&gt;&lt;a href=" "&gt;Home&lt;/a&gt; &lt;ul class="dropdown-menu l-nav-sublist"&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Home Style I&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem dropdown"&gt;&lt;button class="open-icon visible-xs fa fa-angle-down"&gt;&lt;/button&gt;&lt;a href=""&gt;Home Style II&lt;/a&gt; &lt;ul class="dropdown-menu l-nav-sublist"&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Home Style I&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Home Style II&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Home Style Portfolio&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem dropdown"&gt;&lt;button class="open-icon visible-xs fa fa-angle-down"&gt;&lt;/button&gt;&lt;a href=""&gt;Home Style II&lt;/a&gt; &lt;ul class="dropdown-menu l-nav-sublist"&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Home Style I&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Home Style II&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Home Style Portfolio&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Subitem&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;One Page Home&lt;/a&gt;&lt;/li&gt; &lt;li class="l-nav-subitem"&gt;&lt;a href=""&gt;Without Header&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p>i want to output the li children elements based on their top level parent. I use a custom field that is called </p> <pre><code>$item-&gt;megamenu </code></pre> <p>this field is present only on the top li element. for example </p> <pre><code> if($item-&gt;megamenu == 1 ) { do something } </code></pre> <p>but this isn't working on childrens so i need to have </p> <pre><code> if($theparentitem-&gt;megamenu == 1) { } </code></pre> <p>where $theparentitem is the top parent of the $item</p>
[ { "answer_id": 186131, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 0, "selected": false, "text": "<p>Yes, <code>init</code> is good for this purpose. In <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow\">codex</a> is written:</p>\n\n<blockquote>\n <p>init is useful for intercepting $_GET or $_POST triggers.</p>\n</blockquote>\n" }, { "answer_id": 186133, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>If you want a more user-friendly URL structure, you could <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint\" rel=\"nofollow\">add a rewrite endpoint</a>.</p>\n\n<p>This will add the rules for and intercept requests to <code>/my-api/</code>:</p>\n\n<pre><code>function wpd_add_api_endpoint() {\n add_rewrite_endpoint( 'my-api', EP_ROOT );\n}\nadd_action( 'init', 'wpd_add_api_endpoint' );\n\nfunction wpd_api_request( $request ){\n if( isset( $request-&gt;query_vars['my-api'] ) ){\n\n // $request-&gt;query_vars['my-api'] is a string containing everything after your url slug\n // convert it to array\n $parts = explode( '/', $request-&gt;query_vars['my-api'] );\n\n echo '&lt;pre&gt;';\n print_r( $parts );\n echo '&lt;/pre&gt;';\n\n die;\n }\n}\nadd_action( 'parse_request', 'wpd_api_request' );\n</code></pre>\n\n<p>After you flush rules, try a request like:</p>\n\n<blockquote>\n <p><a href=\"http://example.com/my-api/something/else/123/4,5,6/&amp;7\" rel=\"nofollow\">http://example.com/my-api/something/else/123/4,5,6/&amp;7</a></p>\n</blockquote>\n\n<p>Which will output:</p>\n\n<pre><code>Array\n(\n [0] =&gt; something\n [1] =&gt; else\n [2] =&gt; 123\n [3] =&gt; 4,5,6\n [4] =&gt; &amp;7\n)\n</code></pre>\n" } ]
2015/05/03
[ "https://wordpress.stackexchange.com/questions/186195", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59052/" ]
I want to get all info of top level menu from childrens ``` <li class="l-nav-item dropdown"><button class="open-icon visible-xs fa fa-angle-down"></button><a href=" ">Home</a> <ul class="dropdown-menu l-nav-sublist"> <li class="l-nav-subitem"><a href="">Home Style I</a></li> <li class="l-nav-subitem dropdown"><button class="open-icon visible-xs fa fa-angle-down"></button><a href="">Home Style II</a> <ul class="dropdown-menu l-nav-sublist"> <li class="l-nav-subitem"><a href="">Home Style I</a></li> <li class="l-nav-subitem"><a href="">Home Style II</a></li> <li class="l-nav-subitem"><a href="">Home Style Portfolio</a></li> <li class="l-nav-subitem dropdown"><button class="open-icon visible-xs fa fa-angle-down"></button><a href="">Home Style II</a> <ul class="dropdown-menu l-nav-sublist"> <li class="l-nav-subitem"><a href="">Home Style I</a></li> <li class="l-nav-subitem"><a href="">Home Style II</a></li> <li class="l-nav-subitem"><a href="">Home Style Portfolio</a></li> <li class="l-nav-subitem"><a href="">Subitem</a></li> </ul> </li> </ul> </li> <li class="l-nav-subitem"><a href="">One Page Home</a></li> <li class="l-nav-subitem"><a href="">Without Header</a></li> </ul> </li> ``` i want to output the li children elements based on their top level parent. I use a custom field that is called ``` $item->megamenu ``` this field is present only on the top li element. for example ``` if($item->megamenu == 1 ) { do something } ``` but this isn't working on childrens so i need to have ``` if($theparentitem->megamenu == 1) { } ``` where $theparentitem is the top parent of the $item
If you want a more user-friendly URL structure, you could [add a rewrite endpoint](https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint). This will add the rules for and intercept requests to `/my-api/`: ``` function wpd_add_api_endpoint() { add_rewrite_endpoint( 'my-api', EP_ROOT ); } add_action( 'init', 'wpd_add_api_endpoint' ); function wpd_api_request( $request ){ if( isset( $request->query_vars['my-api'] ) ){ // $request->query_vars['my-api'] is a string containing everything after your url slug // convert it to array $parts = explode( '/', $request->query_vars['my-api'] ); echo '<pre>'; print_r( $parts ); echo '</pre>'; die; } } add_action( 'parse_request', 'wpd_api_request' ); ``` After you flush rules, try a request like: > > <http://example.com/my-api/something/else/123/4,5,6/&7> > > > Which will output: ``` Array ( [0] => something [1] => else [2] => 123 [3] => 4,5,6 [4] => &7 ) ```
186,198
<p>I want to display Y number of authors' info randomly. These authors have to have at least X numbers of posts published.</p> <p>Please keep in mind that this would be for a blog with thousands of users where most of them have published 0 posts.</p> <p>I have looked at functions like <code>wp_list_authors()</code> and <code>WP_User_Query()</code> but I cant seem to be able to set the minimum number of posts each author needs to have.</p> <p>I have tried to get the authors with those functions and then, with a loop, test for each author id and see if they have posted X number of posts or more. (I want to avoid this because it seems too tedious and might be too poor performance wise.</p> <p>I could order them in descending order, shuffle the array and display the users' info, but I do not want this because I prefer to showcase users with low number of posts.</p> <p>If I order them in ascending order, I would get hundrends or thousands of users with 0 posts. However, here I can use <code>wp_list_authors()</code> as indicated by @s_ha_dum in: <a href="https://wordpress.stackexchange.com/questions/100240/total-number-of-authors-with-more-than-one-post">Total number of authors with more than one post</a> that excludes authors with 0 posts but what if I want to get users that have at least 2 or more posts?</p> <p>Finally, I could use a <code>pre_user_query</code> filter as explained by @helgatheviking in: <a href="https://wordpress.stackexchange.com/questions/76622/wp-user-query-to-exclude-users-with-no-posts">WP_User_Query to exclude users with no posts</a> </p> <p>Is this the best solution?What about performance? Is there a better solution? If so, what would you recommend me do?</p>
[ { "answer_id": 186220, "author": "Gixty", "author_id": 14128, "author_profile": "https://wordpress.stackexchange.com/users/14128", "pm_score": 1, "selected": false, "text": "<p>This is a rough draft of what I have so far. Please feel free to update it and improve it.</p>\n\n<p>First of all, we use the <code>pre_user_action</code> to choose the minimum number of posts a user needs to have in order to get their info and display it. It was taken from <a href=\"https://wordpress.stackexchange.com/questions/76622/wp-user-query-to-exclude-users-with-no-posts\">WP_User_Query to exclude users with no posts</a> (by @helgatheviking). I just made some minor changes to fit my needs.</p>\n\n<pre><code>add_action( 'pre_user_query', 'users_with_posts',10, 1 );\n\nfunction users_with_posts( &amp;$query) {\n global $wpdb;\n $min_posts = 5; \n if ( isset( $query-&gt;query_vars['query_id'] ) &amp;&amp; 'wps_last_name' == $query-&gt;query_vars['query_id'] )\n $query-&gt;query_from = $query-&gt;query_from . \" LEFT OUTER JOIN (\n SELECT post_author, COUNT(*) as post_count\n FROM $wpdb-&gt;posts\n WHERE post_type = post AND post_status = publish\n GROUP BY post_author\n ) p ON ({$wpdb-&gt;users}.ID = p.post_author)\n \";\n\n $query-&gt;query_where = $query-&gt;query_where . \" AND post_count &gt; {$min_posts} \"; \n}\n</code></pre>\n\n<p>Then, we need the total number of users who have posted more than X number of posts.</p>\n\n<pre><code>function count_users_with_posts($min_posts) {\n global $wpdb;\n $author_ids = $wpdb-&gt;get_col($wpdb-&gt;prepare(\"SELECT post_author FROM\n (SELECT post_author, COUNT(*) AS post_count FROM {$wpdb-&gt;posts}\n WHERE post_type = 'post' AND post_status='publish' GROUP BY post_author) AS stats\n WHERE post_count &gt; %s ORDER BY count DESC;\",$min_posts));\n return count($author_ids);\n}\n</code></pre>\n\n<p>Now we are ready to proceed and use the <code>WP_User_query()</code> function to get our \"random\" users. They are not 100% randomly chosen but it is as close as I can get it.</p>\n\n<p>These are the args for our function:</p>\n\n<pre><code>$args = array (\n 'query_id' =&gt; 'users_with_posts',\n 'orderby' =&gt; 'post_count',\n 'order' =&gt; 'ASC', //default\n 'number' =&gt; $total_number,\n 'offset' =&gt; $offset,\n\n); \n</code></pre>\n\n<p>You can see we are missing two variables, well here is where get to play a little. We will generate a random offset to get the \"random\" effect.</p>\n\n<pre><code>$total_number = 12; //number of users we want to display\n$total_authors = count_users_with_posts(5); //total number of users with more than 5 posts\n$offset = mt_rand(0,$total_authors - $total_number); //randomly generated offset.\n\n$users = new WP_User_Query( $args );\n</code></pre>\n\n<p>There is plenty of room for improvement, I hope someone takes it from here, or if there is a different and better way, you are more than welcome to share it.</p>\n" }, { "answer_id": 186309, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>You can get rid of most of your code above. <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow noreferrer\"><code>WP_User_Query</code></a> has an <code>include</code> parameter (<em>introduced in Wordpress 3.9</em>)</p>\n\n<blockquote>\n <p><strong>include</strong> (array) - List of users to be included.</p>\n</blockquote>\n\n<p>So we need to get a random array of author ID's. I have modified your <code>count_users_with_posts()</code> a bit here to extend it to make it more dynamic and to get a set amount of authors randomly. I also had to repair a few bugs (<em>some SQL errors, specially this line: <code>WHERE post_count &gt; %s ORDER BY count DESC</code>. You should enable debugging when developing :-)</em>)</p>\n\n<p><em>CAVEAT: This works on my local install with 4 users.</em></p>\n\n<pre><code>function get_author_posts_count( $min_posts = 1, $max_posts = 10, $limit = 10, $post_type = 'post' )\n{\n global $wpdb;\n\n $authors = $wpdb-&gt;get_col(\n $wpdb-&gt;prepare(\n \"SELECT post_author FROM (\n SELECT post_author, COUNT(*) AS count \n FROM $wpdb-&gt;posts\n WHERE post_type = %s \n AND post_status='publish' \n GROUP BY post_author\n ) AS stats\n WHERE stats.count BETWEEN %d AND %d\n ORDER BY RAND()\n LIMIT 0,%d\",\n $post_type,\n $min_posts,\n $max_posts,\n $limit\n )\n );\n\n return $authors;\n}\n</code></pre>\n\n<p>As you can see, I have included 4 parameters here. </p>\n\n<ul>\n<li><p><code>$min_posts</code> -> Minimum amount of published posts an author must have. Default <code>1</code></p></li>\n<li><p><code>$max_posts</code> -> As you would like to get authors with low post count, I have included a maximum post count. You can remove that if you wish, just remember to change the SQL accordingly then Default <code>10</code></p></li>\n<li><p><code>$limit</code> -> The amount of post authors to get. Default <code>10</code></p></li>\n<li><p><code>$post_type</code> -> The post type to get use. Default <code>post</code></p></li>\n</ul>\n\n<p>You can then use the function above in your <code>WP_User_query</code> as follow</p>\n\n<pre><code>$args = [\n 'include' =&gt; get_author_posts_count( 5, 20, 5, 'my_post_type' )\n];\n\n$authors = new WP_User_Query( $args );\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>From comments (thanks @birgire), there are a few issues that you should take note of</p>\n\n<ul>\n<li><p>Before passing the result of <code>get_author_posts_count()</code> to the <code>include</code> parameter of <code>WP_User_Query</code>, you should check whether or not if any values are available. If the result of <code>get_author_posts_count()</code> is empty or invalid, the <code>include</code> parameter will be ignored and all users will be returned. The query will not return an empty array of users</p></li>\n<li><p>There is a limit on the lenght of an SQL query, so very big author queries might crash. As I already stated, my test site is really small, so I cannot test my code to the max. You should also check out <a href=\"https://stackoverflow.com/q/3026134/1908141\">this post</a> on SQL query lentghs </p></li>\n</ul>\n\n<p>I would appreciate any feedback on tests on large sites with many posts and plenty authors</p>\n" } ]
2015/05/03
[ "https://wordpress.stackexchange.com/questions/186198", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14128/" ]
I want to display Y number of authors' info randomly. These authors have to have at least X numbers of posts published. Please keep in mind that this would be for a blog with thousands of users where most of them have published 0 posts. I have looked at functions like `wp_list_authors()` and `WP_User_Query()` but I cant seem to be able to set the minimum number of posts each author needs to have. I have tried to get the authors with those functions and then, with a loop, test for each author id and see if they have posted X number of posts or more. (I want to avoid this because it seems too tedious and might be too poor performance wise. I could order them in descending order, shuffle the array and display the users' info, but I do not want this because I prefer to showcase users with low number of posts. If I order them in ascending order, I would get hundrends or thousands of users with 0 posts. However, here I can use `wp_list_authors()` as indicated by @s\_ha\_dum in: [Total number of authors with more than one post](https://wordpress.stackexchange.com/questions/100240/total-number-of-authors-with-more-than-one-post) that excludes authors with 0 posts but what if I want to get users that have at least 2 or more posts? Finally, I could use a `pre_user_query` filter as explained by @helgatheviking in: [WP\_User\_Query to exclude users with no posts](https://wordpress.stackexchange.com/questions/76622/wp-user-query-to-exclude-users-with-no-posts) Is this the best solution?What about performance? Is there a better solution? If so, what would you recommend me do?
You can get rid of most of your code above. [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query) has an `include` parameter (*introduced in Wordpress 3.9*) > > **include** (array) - List of users to be included. > > > So we need to get a random array of author ID's. I have modified your `count_users_with_posts()` a bit here to extend it to make it more dynamic and to get a set amount of authors randomly. I also had to repair a few bugs (*some SQL errors, specially this line: `WHERE post_count > %s ORDER BY count DESC`. You should enable debugging when developing :-)*) *CAVEAT: This works on my local install with 4 users.* ``` function get_author_posts_count( $min_posts = 1, $max_posts = 10, $limit = 10, $post_type = 'post' ) { global $wpdb; $authors = $wpdb->get_col( $wpdb->prepare( "SELECT post_author FROM ( SELECT post_author, COUNT(*) AS count FROM $wpdb->posts WHERE post_type = %s AND post_status='publish' GROUP BY post_author ) AS stats WHERE stats.count BETWEEN %d AND %d ORDER BY RAND() LIMIT 0,%d", $post_type, $min_posts, $max_posts, $limit ) ); return $authors; } ``` As you can see, I have included 4 parameters here. * `$min_posts` -> Minimum amount of published posts an author must have. Default `1` * `$max_posts` -> As you would like to get authors with low post count, I have included a maximum post count. You can remove that if you wish, just remember to change the SQL accordingly then Default `10` * `$limit` -> The amount of post authors to get. Default `10` * `$post_type` -> The post type to get use. Default `post` You can then use the function above in your `WP_User_query` as follow ``` $args = [ 'include' => get_author_posts_count( 5, 20, 5, 'my_post_type' ) ]; $authors = new WP_User_Query( $args ); ``` EDIT ---- From comments (thanks @birgire), there are a few issues that you should take note of * Before passing the result of `get_author_posts_count()` to the `include` parameter of `WP_User_Query`, you should check whether or not if any values are available. If the result of `get_author_posts_count()` is empty or invalid, the `include` parameter will be ignored and all users will be returned. The query will not return an empty array of users * There is a limit on the lenght of an SQL query, so very big author queries might crash. As I already stated, my test site is really small, so I cannot test my code to the max. You should also check out [this post](https://stackoverflow.com/q/3026134/1908141) on SQL query lentghs I would appreciate any feedback on tests on large sites with many posts and plenty authors
186,201
<p>how can I change the 1st child name of the admin menu in wp? I have upload a picture, I want to have a different name of the 1st child of the menu and the parent will be the same.</p> <p><img src="https://i.stack.imgur.com/Di3m8.png" alt="enter image description here"></p> <p>this is mycode</p> <pre><code>add_action('admin_menu', 'mymenu_admin_actions'); function mymenu_admin_actions(){ add_menu_page('Axcelerate Client Link', 'Axcelerate Client Link', 'manage_options', 'Axcelerate_Link_Admin', 'axcelerate_link_admin_page'); add_submenu_page('Axcelerate_Link_Admin','Page Setup','Page Setup', 'manage_options','Axcelerate_Link_Admin_Pages_Setup','axcelerate_link_admin_pages_setup_page'); } </code></pre> <p>what I really want is to be link this:</p> <pre><code>Axecelerate Client Link - Link Admin - Page Setup </code></pre> <p>is this possible?</p>
[ { "answer_id": 186220, "author": "Gixty", "author_id": 14128, "author_profile": "https://wordpress.stackexchange.com/users/14128", "pm_score": 1, "selected": false, "text": "<p>This is a rough draft of what I have so far. Please feel free to update it and improve it.</p>\n\n<p>First of all, we use the <code>pre_user_action</code> to choose the minimum number of posts a user needs to have in order to get their info and display it. It was taken from <a href=\"https://wordpress.stackexchange.com/questions/76622/wp-user-query-to-exclude-users-with-no-posts\">WP_User_Query to exclude users with no posts</a> (by @helgatheviking). I just made some minor changes to fit my needs.</p>\n\n<pre><code>add_action( 'pre_user_query', 'users_with_posts',10, 1 );\n\nfunction users_with_posts( &amp;$query) {\n global $wpdb;\n $min_posts = 5; \n if ( isset( $query-&gt;query_vars['query_id'] ) &amp;&amp; 'wps_last_name' == $query-&gt;query_vars['query_id'] )\n $query-&gt;query_from = $query-&gt;query_from . \" LEFT OUTER JOIN (\n SELECT post_author, COUNT(*) as post_count\n FROM $wpdb-&gt;posts\n WHERE post_type = post AND post_status = publish\n GROUP BY post_author\n ) p ON ({$wpdb-&gt;users}.ID = p.post_author)\n \";\n\n $query-&gt;query_where = $query-&gt;query_where . \" AND post_count &gt; {$min_posts} \"; \n}\n</code></pre>\n\n<p>Then, we need the total number of users who have posted more than X number of posts.</p>\n\n<pre><code>function count_users_with_posts($min_posts) {\n global $wpdb;\n $author_ids = $wpdb-&gt;get_col($wpdb-&gt;prepare(\"SELECT post_author FROM\n (SELECT post_author, COUNT(*) AS post_count FROM {$wpdb-&gt;posts}\n WHERE post_type = 'post' AND post_status='publish' GROUP BY post_author) AS stats\n WHERE post_count &gt; %s ORDER BY count DESC;\",$min_posts));\n return count($author_ids);\n}\n</code></pre>\n\n<p>Now we are ready to proceed and use the <code>WP_User_query()</code> function to get our \"random\" users. They are not 100% randomly chosen but it is as close as I can get it.</p>\n\n<p>These are the args for our function:</p>\n\n<pre><code>$args = array (\n 'query_id' =&gt; 'users_with_posts',\n 'orderby' =&gt; 'post_count',\n 'order' =&gt; 'ASC', //default\n 'number' =&gt; $total_number,\n 'offset' =&gt; $offset,\n\n); \n</code></pre>\n\n<p>You can see we are missing two variables, well here is where get to play a little. We will generate a random offset to get the \"random\" effect.</p>\n\n<pre><code>$total_number = 12; //number of users we want to display\n$total_authors = count_users_with_posts(5); //total number of users with more than 5 posts\n$offset = mt_rand(0,$total_authors - $total_number); //randomly generated offset.\n\n$users = new WP_User_Query( $args );\n</code></pre>\n\n<p>There is plenty of room for improvement, I hope someone takes it from here, or if there is a different and better way, you are more than welcome to share it.</p>\n" }, { "answer_id": 186309, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>You can get rid of most of your code above. <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow noreferrer\"><code>WP_User_Query</code></a> has an <code>include</code> parameter (<em>introduced in Wordpress 3.9</em>)</p>\n\n<blockquote>\n <p><strong>include</strong> (array) - List of users to be included.</p>\n</blockquote>\n\n<p>So we need to get a random array of author ID's. I have modified your <code>count_users_with_posts()</code> a bit here to extend it to make it more dynamic and to get a set amount of authors randomly. I also had to repair a few bugs (<em>some SQL errors, specially this line: <code>WHERE post_count &gt; %s ORDER BY count DESC</code>. You should enable debugging when developing :-)</em>)</p>\n\n<p><em>CAVEAT: This works on my local install with 4 users.</em></p>\n\n<pre><code>function get_author_posts_count( $min_posts = 1, $max_posts = 10, $limit = 10, $post_type = 'post' )\n{\n global $wpdb;\n\n $authors = $wpdb-&gt;get_col(\n $wpdb-&gt;prepare(\n \"SELECT post_author FROM (\n SELECT post_author, COUNT(*) AS count \n FROM $wpdb-&gt;posts\n WHERE post_type = %s \n AND post_status='publish' \n GROUP BY post_author\n ) AS stats\n WHERE stats.count BETWEEN %d AND %d\n ORDER BY RAND()\n LIMIT 0,%d\",\n $post_type,\n $min_posts,\n $max_posts,\n $limit\n )\n );\n\n return $authors;\n}\n</code></pre>\n\n<p>As you can see, I have included 4 parameters here. </p>\n\n<ul>\n<li><p><code>$min_posts</code> -> Minimum amount of published posts an author must have. Default <code>1</code></p></li>\n<li><p><code>$max_posts</code> -> As you would like to get authors with low post count, I have included a maximum post count. You can remove that if you wish, just remember to change the SQL accordingly then Default <code>10</code></p></li>\n<li><p><code>$limit</code> -> The amount of post authors to get. Default <code>10</code></p></li>\n<li><p><code>$post_type</code> -> The post type to get use. Default <code>post</code></p></li>\n</ul>\n\n<p>You can then use the function above in your <code>WP_User_query</code> as follow</p>\n\n<pre><code>$args = [\n 'include' =&gt; get_author_posts_count( 5, 20, 5, 'my_post_type' )\n];\n\n$authors = new WP_User_Query( $args );\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>From comments (thanks @birgire), there are a few issues that you should take note of</p>\n\n<ul>\n<li><p>Before passing the result of <code>get_author_posts_count()</code> to the <code>include</code> parameter of <code>WP_User_Query</code>, you should check whether or not if any values are available. If the result of <code>get_author_posts_count()</code> is empty or invalid, the <code>include</code> parameter will be ignored and all users will be returned. The query will not return an empty array of users</p></li>\n<li><p>There is a limit on the lenght of an SQL query, so very big author queries might crash. As I already stated, my test site is really small, so I cannot test my code to the max. You should also check out <a href=\"https://stackoverflow.com/q/3026134/1908141\">this post</a> on SQL query lentghs </p></li>\n</ul>\n\n<p>I would appreciate any feedback on tests on large sites with many posts and plenty authors</p>\n" } ]
2015/05/04
[ "https://wordpress.stackexchange.com/questions/186201", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68933/" ]
how can I change the 1st child name of the admin menu in wp? I have upload a picture, I want to have a different name of the 1st child of the menu and the parent will be the same. ![enter image description here](https://i.stack.imgur.com/Di3m8.png) this is mycode ``` add_action('admin_menu', 'mymenu_admin_actions'); function mymenu_admin_actions(){ add_menu_page('Axcelerate Client Link', 'Axcelerate Client Link', 'manage_options', 'Axcelerate_Link_Admin', 'axcelerate_link_admin_page'); add_submenu_page('Axcelerate_Link_Admin','Page Setup','Page Setup', 'manage_options','Axcelerate_Link_Admin_Pages_Setup','axcelerate_link_admin_pages_setup_page'); } ``` what I really want is to be link this: ``` Axecelerate Client Link - Link Admin - Page Setup ``` is this possible?
You can get rid of most of your code above. [`WP_User_Query`](https://codex.wordpress.org/Class_Reference/WP_User_Query) has an `include` parameter (*introduced in Wordpress 3.9*) > > **include** (array) - List of users to be included. > > > So we need to get a random array of author ID's. I have modified your `count_users_with_posts()` a bit here to extend it to make it more dynamic and to get a set amount of authors randomly. I also had to repair a few bugs (*some SQL errors, specially this line: `WHERE post_count > %s ORDER BY count DESC`. You should enable debugging when developing :-)*) *CAVEAT: This works on my local install with 4 users.* ``` function get_author_posts_count( $min_posts = 1, $max_posts = 10, $limit = 10, $post_type = 'post' ) { global $wpdb; $authors = $wpdb->get_col( $wpdb->prepare( "SELECT post_author FROM ( SELECT post_author, COUNT(*) AS count FROM $wpdb->posts WHERE post_type = %s AND post_status='publish' GROUP BY post_author ) AS stats WHERE stats.count BETWEEN %d AND %d ORDER BY RAND() LIMIT 0,%d", $post_type, $min_posts, $max_posts, $limit ) ); return $authors; } ``` As you can see, I have included 4 parameters here. * `$min_posts` -> Minimum amount of published posts an author must have. Default `1` * `$max_posts` -> As you would like to get authors with low post count, I have included a maximum post count. You can remove that if you wish, just remember to change the SQL accordingly then Default `10` * `$limit` -> The amount of post authors to get. Default `10` * `$post_type` -> The post type to get use. Default `post` You can then use the function above in your `WP_User_query` as follow ``` $args = [ 'include' => get_author_posts_count( 5, 20, 5, 'my_post_type' ) ]; $authors = new WP_User_Query( $args ); ``` EDIT ---- From comments (thanks @birgire), there are a few issues that you should take note of * Before passing the result of `get_author_posts_count()` to the `include` parameter of `WP_User_Query`, you should check whether or not if any values are available. If the result of `get_author_posts_count()` is empty or invalid, the `include` parameter will be ignored and all users will be returned. The query will not return an empty array of users * There is a limit on the lenght of an SQL query, so very big author queries might crash. As I already stated, my test site is really small, so I cannot test my code to the max. You should also check out [this post](https://stackoverflow.com/q/3026134/1908141) on SQL query lentghs I would appreciate any feedback on tests on large sites with many posts and plenty authors
186,253
<p>Given a user id, $user_id, and post id, $post_id, how can I programatically update a wordpress post author?</p> <p>Note: these posts are already created and the author cannot be set upon creation. Another process is creating the post and defaulting to the admin as the author. I don't have access to creating the post but have access after it is created.</p>
[ { "answer_id": 186275, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 6, "selected": true, "text": "<p>It shouldn't be any problem. Try this:</p>\n\n<pre><code>$arg = array(\n 'ID' =&gt; $post_id,\n 'post_author' =&gt; $user_id,\n);\nwp_update_post( $arg );\n</code></pre>\n" }, { "answer_id": 321239, "author": "jesse", "author_id": 155435, "author_profile": "https://wordpress.stackexchange.com/users/155435", "pm_score": -1, "selected": false, "text": "<p>you can also just add another admin account. delete the one that's authoring the posts and WP will ask where to assign posts. Choose preferred author, done.</p>\n" } ]
2015/05/04
[ "https://wordpress.stackexchange.com/questions/186253", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71608/" ]
Given a user id, $user\_id, and post id, $post\_id, how can I programatically update a wordpress post author? Note: these posts are already created and the author cannot be set upon creation. Another process is creating the post and defaulting to the admin as the author. I don't have access to creating the post but have access after it is created.
It shouldn't be any problem. Try this: ``` $arg = array( 'ID' => $post_id, 'post_author' => $user_id, ); wp_update_post( $arg ); ```
186,267
<p>I'm using Nginx and a custom add_rewrite_rule that looks like this:</p> <pre><code>function add_pony() { //this should allow me to POST to domain.com/pony add_rewrite_rule('^pony$', 'index.php?pony=true', 'top'); } add_action( 'init', 'add_pony'); function parse_pony( $params ) { if(isset($params-&gt;query_vars['pony'])){ //kick off endpoint specific code } return $params; } add_action( 'parse_request', 'parse_pony' ); </code></pre> <p>My nginx config for WP looks like this:</p> <pre><code>server { listen 80; root /var/www/domain.net; index index.php; server_name domain.net; location / { try_files $uri $uri/ /index.php?q=$uri&amp;$args; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/www; } location ~ \.php$ { try_files $uri = 404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_intercept_errors on; include fastcgi_params; } } </code></pre> <p>When I POST or GET the new URL I get a 404. The rest of WordPress works just fine, but when I change the permalink settings to something other than post-name, WordPress stops working correctly.</p> <p>I'm stumped.</p>
[ { "answer_id": 186275, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 6, "selected": true, "text": "<p>It shouldn't be any problem. Try this:</p>\n\n<pre><code>$arg = array(\n 'ID' =&gt; $post_id,\n 'post_author' =&gt; $user_id,\n);\nwp_update_post( $arg );\n</code></pre>\n" }, { "answer_id": 321239, "author": "jesse", "author_id": 155435, "author_profile": "https://wordpress.stackexchange.com/users/155435", "pm_score": -1, "selected": false, "text": "<p>you can also just add another admin account. delete the one that's authoring the posts and WP will ask where to assign posts. Choose preferred author, done.</p>\n" } ]
2015/05/04
[ "https://wordpress.stackexchange.com/questions/186267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34359/" ]
I'm using Nginx and a custom add\_rewrite\_rule that looks like this: ``` function add_pony() { //this should allow me to POST to domain.com/pony add_rewrite_rule('^pony$', 'index.php?pony=true', 'top'); } add_action( 'init', 'add_pony'); function parse_pony( $params ) { if(isset($params->query_vars['pony'])){ //kick off endpoint specific code } return $params; } add_action( 'parse_request', 'parse_pony' ); ``` My nginx config for WP looks like this: ``` server { listen 80; root /var/www/domain.net; index index.php; server_name domain.net; location / { try_files $uri $uri/ /index.php?q=$uri&$args; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/www; } location ~ \.php$ { try_files $uri = 404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_intercept_errors on; include fastcgi_params; } } ``` When I POST or GET the new URL I get a 404. The rest of WordPress works just fine, but when I change the permalink settings to something other than post-name, WordPress stops working correctly. I'm stumped.
It shouldn't be any problem. Try this: ``` $arg = array( 'ID' => $post_id, 'post_author' => $user_id, ); wp_update_post( $arg ); ```
186,272
<p>I'm running a WP site on my laptop using localhost, and I often need my coworkers to see it. If they enter my home's IP, they were able to access the site, but all the URL's in WP that used site_url() or similar were echoing out "localhost" which of course didn't work for outsiders.</p> <p>So I changed WP to use my IP for the site URL which solved that problem, but created another. If I bring my laptop away from home and try to view my site, now all the links appear as <a href="http://home-ip/">http://home-ip/</a> which isn't available. Furthermore, I'm unable to to get into wp-admin to change the site URL back to localhost since I'm being redirected to <a href="http://home-ip/site/wp-admin/">http://home-ip/site/wp-admin/</a>.</p> <p>Is there a way to deal with this without having to constantly change the URL every time I want someone else to access it from outside, or every time I leave the house.</p>
[ { "answer_id": 186283, "author": "adelval", "author_id": 40965, "author_profile": "https://wordpress.stackexchange.com/users/40965", "pm_score": 4, "selected": true, "text": "<p>You can use <code>wp-config.php</code> to change the site url depending on where the site is accesed from, using <code>$_SERVER['REMOTE_ADDR']</code>. Mine has something like this:</p>\n\n<pre><code>if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { \n // accesing site from my local server\n define('WP_SITEURL', 'http://localhost/mysite/');\n define('WP_HOME', 'http://localhost/mysite');\n} else if (strpos($_SERVER['REMOTE_ADDR'],'192.168.0.') !== false) {\n // accesing site from another machine in my home network, \n // all their (internal) network addresses begin with this number;\n // the next line provides the server's own internal network address \n define('WP_SITEURL', 'http://192.168.0.192/mysite/');\n define('WP_HOME', 'http://192.168.0.192/mysite');\n} else { //accesing site from outside home\n define('WP_SITEURL', 'http://89.*.*.*/mysite/'); //replace by your external home IP\n define('WP_HOME', 'http://89.*.*.*/mysite');\n}\n//error_log(\"Siteurl is \".WP_SITEURL);\n</code></pre>\n\n<p>This technique also helps a lot to simplify uploading the site to a production server or keeping in sync local and production versions of the site. (Though, obviously, the <code>wp-config.php</code> on the production server should not have this code.) </p>\n\n<p>Note: For some reason, I cannot use my external home IP from other machines in my home network; if that's not your case, you can remove the <code>else if</code>, leaving only the <code>else</code> part.</p>\n" }, { "answer_id": 186296, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 1, "selected": false, "text": "<p>Although the accepted answer looks to be a good one, just changing WP_SITEURL/WP_HOME doesn't work in my case because there always ends up being lots of absolute links in the text content on pages (i.e. images or links added through the WYSIWYG editor). In other words, I pretty much <em>have</em> to use the same domain if I want the site to work properly.</p>\n\n<p>So in case it helps someone else who comes across this, my solution was an outside-of-Wordpress one - although it may not help in all cases.</p>\n\n<p>I use a domain, for example me.mycompany.com, and then in my HOSTS file I make it resolve to 127.0.0.1 (in other words, localhost). For any of my colleagues who need to view the site, I add my domain to their HOSTS file with my local IP.</p>\n\n<p>This solution also gets extended when clients outside our network need to view the site; we simply make sure me.mycompany.com resolves to our public IP (usually your web host can help with this, and it definitely helps if you have a static IP for your Internet connection too), and then at our router, route the web requests to my internal IP, effectively setting up an easy web hosting solution (for development only of course, not production!)</p>\n\n<p>Hope this helps someone. The HOSTS file can be edited on any platform, obviously the instructions differ for Windows, Mac and Linux so best you Google for help if you need it, but in Windows the file is C:\\Windows\\System32\\drivers\\etc\\hosts - open it in Notepad and make the neccessary changes, following the format in the file (you will need to run as Administrator in order to save the file).</p>\n" }, { "answer_id": 385467, "author": "katiedev", "author_id": 201500, "author_profile": "https://wordpress.stackexchange.com/users/201500", "pm_score": 1, "selected": false, "text": "<p>From WordPress 5.5.1 you can use the <a href=\"https://developer.wordpress.org/reference/functions/wp_get_environment_type\" rel=\"nofollow noreferrer\">wp_get_environment_type</a> fuction. Set <code>wp_get_environment_type</code> within wp-config.</p>\n" } ]
2015/05/04
[ "https://wordpress.stackexchange.com/questions/186272", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70599/" ]
I'm running a WP site on my laptop using localhost, and I often need my coworkers to see it. If they enter my home's IP, they were able to access the site, but all the URL's in WP that used site\_url() or similar were echoing out "localhost" which of course didn't work for outsiders. So I changed WP to use my IP for the site URL which solved that problem, but created another. If I bring my laptop away from home and try to view my site, now all the links appear as <http://home-ip/> which isn't available. Furthermore, I'm unable to to get into wp-admin to change the site URL back to localhost since I'm being redirected to <http://home-ip/site/wp-admin/>. Is there a way to deal with this without having to constantly change the URL every time I want someone else to access it from outside, or every time I leave the house.
You can use `wp-config.php` to change the site url depending on where the site is accesed from, using `$_SERVER['REMOTE_ADDR']`. Mine has something like this: ``` if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { // accesing site from my local server define('WP_SITEURL', 'http://localhost/mysite/'); define('WP_HOME', 'http://localhost/mysite'); } else if (strpos($_SERVER['REMOTE_ADDR'],'192.168.0.') !== false) { // accesing site from another machine in my home network, // all their (internal) network addresses begin with this number; // the next line provides the server's own internal network address define('WP_SITEURL', 'http://192.168.0.192/mysite/'); define('WP_HOME', 'http://192.168.0.192/mysite'); } else { //accesing site from outside home define('WP_SITEURL', 'http://89.*.*.*/mysite/'); //replace by your external home IP define('WP_HOME', 'http://89.*.*.*/mysite'); } //error_log("Siteurl is ".WP_SITEURL); ``` This technique also helps a lot to simplify uploading the site to a production server or keeping in sync local and production versions of the site. (Though, obviously, the `wp-config.php` on the production server should not have this code.) Note: For some reason, I cannot use my external home IP from other machines in my home network; if that's not your case, you can remove the `else if`, leaving only the `else` part.
186,282
<p>I am currently using a wordpress installation in which all the website is intended to be shown in http while the https part is protected by a self signed certificate, distributed manually to the admins. The problem I have is that the images uploaded are all uploaded with the "https" prefix, I imagine because the link is generated somehow using the full path of the admin interface. Do you know how I can fix this behaviour to use the protocol http for every image uploaded? I don't really need https for this and the site name and URL is in http. </p> <p>Thanks in advance.</p> <p>Some specs: </p> <ul> <li>wordpress version: 4.2.1</li> <li>plugins installed: Category Posts Widget, Jetpack, Post Types Order, Relative Image URLs, WordPress SEO, WP Statistics. </li> </ul>
[ { "answer_id": 186283, "author": "adelval", "author_id": 40965, "author_profile": "https://wordpress.stackexchange.com/users/40965", "pm_score": 4, "selected": true, "text": "<p>You can use <code>wp-config.php</code> to change the site url depending on where the site is accesed from, using <code>$_SERVER['REMOTE_ADDR']</code>. Mine has something like this:</p>\n\n<pre><code>if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { \n // accesing site from my local server\n define('WP_SITEURL', 'http://localhost/mysite/');\n define('WP_HOME', 'http://localhost/mysite');\n} else if (strpos($_SERVER['REMOTE_ADDR'],'192.168.0.') !== false) {\n // accesing site from another machine in my home network, \n // all their (internal) network addresses begin with this number;\n // the next line provides the server's own internal network address \n define('WP_SITEURL', 'http://192.168.0.192/mysite/');\n define('WP_HOME', 'http://192.168.0.192/mysite');\n} else { //accesing site from outside home\n define('WP_SITEURL', 'http://89.*.*.*/mysite/'); //replace by your external home IP\n define('WP_HOME', 'http://89.*.*.*/mysite');\n}\n//error_log(\"Siteurl is \".WP_SITEURL);\n</code></pre>\n\n<p>This technique also helps a lot to simplify uploading the site to a production server or keeping in sync local and production versions of the site. (Though, obviously, the <code>wp-config.php</code> on the production server should not have this code.) </p>\n\n<p>Note: For some reason, I cannot use my external home IP from other machines in my home network; if that's not your case, you can remove the <code>else if</code>, leaving only the <code>else</code> part.</p>\n" }, { "answer_id": 186296, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 1, "selected": false, "text": "<p>Although the accepted answer looks to be a good one, just changing WP_SITEURL/WP_HOME doesn't work in my case because there always ends up being lots of absolute links in the text content on pages (i.e. images or links added through the WYSIWYG editor). In other words, I pretty much <em>have</em> to use the same domain if I want the site to work properly.</p>\n\n<p>So in case it helps someone else who comes across this, my solution was an outside-of-Wordpress one - although it may not help in all cases.</p>\n\n<p>I use a domain, for example me.mycompany.com, and then in my HOSTS file I make it resolve to 127.0.0.1 (in other words, localhost). For any of my colleagues who need to view the site, I add my domain to their HOSTS file with my local IP.</p>\n\n<p>This solution also gets extended when clients outside our network need to view the site; we simply make sure me.mycompany.com resolves to our public IP (usually your web host can help with this, and it definitely helps if you have a static IP for your Internet connection too), and then at our router, route the web requests to my internal IP, effectively setting up an easy web hosting solution (for development only of course, not production!)</p>\n\n<p>Hope this helps someone. The HOSTS file can be edited on any platform, obviously the instructions differ for Windows, Mac and Linux so best you Google for help if you need it, but in Windows the file is C:\\Windows\\System32\\drivers\\etc\\hosts - open it in Notepad and make the neccessary changes, following the format in the file (you will need to run as Administrator in order to save the file).</p>\n" }, { "answer_id": 385467, "author": "katiedev", "author_id": 201500, "author_profile": "https://wordpress.stackexchange.com/users/201500", "pm_score": 1, "selected": false, "text": "<p>From WordPress 5.5.1 you can use the <a href=\"https://developer.wordpress.org/reference/functions/wp_get_environment_type\" rel=\"nofollow noreferrer\">wp_get_environment_type</a> fuction. Set <code>wp_get_environment_type</code> within wp-config.</p>\n" } ]
2015/05/04
[ "https://wordpress.stackexchange.com/questions/186282", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71623/" ]
I am currently using a wordpress installation in which all the website is intended to be shown in http while the https part is protected by a self signed certificate, distributed manually to the admins. The problem I have is that the images uploaded are all uploaded with the "https" prefix, I imagine because the link is generated somehow using the full path of the admin interface. Do you know how I can fix this behaviour to use the protocol http for every image uploaded? I don't really need https for this and the site name and URL is in http. Thanks in advance. Some specs: * wordpress version: 4.2.1 * plugins installed: Category Posts Widget, Jetpack, Post Types Order, Relative Image URLs, WordPress SEO, WP Statistics.
You can use `wp-config.php` to change the site url depending on where the site is accesed from, using `$_SERVER['REMOTE_ADDR']`. Mine has something like this: ``` if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { // accesing site from my local server define('WP_SITEURL', 'http://localhost/mysite/'); define('WP_HOME', 'http://localhost/mysite'); } else if (strpos($_SERVER['REMOTE_ADDR'],'192.168.0.') !== false) { // accesing site from another machine in my home network, // all their (internal) network addresses begin with this number; // the next line provides the server's own internal network address define('WP_SITEURL', 'http://192.168.0.192/mysite/'); define('WP_HOME', 'http://192.168.0.192/mysite'); } else { //accesing site from outside home define('WP_SITEURL', 'http://89.*.*.*/mysite/'); //replace by your external home IP define('WP_HOME', 'http://89.*.*.*/mysite'); } //error_log("Siteurl is ".WP_SITEURL); ``` This technique also helps a lot to simplify uploading the site to a production server or keeping in sync local and production versions of the site. (Though, obviously, the `wp-config.php` on the production server should not have this code.) Note: For some reason, I cannot use my external home IP from other machines in my home network; if that's not your case, you can remove the `else if`, leaving only the `else` part.
186,313
<p>I am trying to create custom template for custom taxonomy. For example i have a custom taxonomy registered in WP with name brands and slug brand i used following code to register custom taxonomy.</p> <pre><code>function brand() { $labels = array( 'name' =&gt; _x( 'brands', 'Taxonomy General Name', 'text_domain' ), 'singular_name' =&gt; _x( 'brand', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' =&gt; __( 'Brands', 'text_domain' ), 'all_items' =&gt; __( 'All Brands', 'text_domain' ), 'parent_item' =&gt; __( 'Brand Parent Item', 'text_domain' ), 'parent_item_colon' =&gt; __( 'Parent Item:', 'text_domain' ), 'new_item_name' =&gt; __( 'New Brand', 'text_domain' ), 'add_new_item' =&gt; __( 'Add New Brand', 'text_domain' ), 'edit_item' =&gt; __( 'Edit Brand', 'text_domain' ), 'update_item' =&gt; __( 'Update Brand', 'text_domain' ), 'view_item' =&gt; __( 'View Brand', 'text_domain' ), 'separate_items_with_commas' =&gt; __( 'Separate items with commas', 'text_domain' ), 'add_or_remove_items' =&gt; __( 'Add or remove Brands', 'text_domain' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used', 'text_domain' ), 'popular_items' =&gt; __( 'Popular Brands', 'text_domain' ), 'search_items' =&gt; __( 'Search Brands', 'text_domain' ), 'not_found' =&gt; __( 'Not Found', 'text_domain' ), ); $rewrite = array( 'slug' =&gt; 'brand', 'with_front' =&gt; true, 'hierarchical' =&gt; true, ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, 'rewrite' =&gt; $rewrite, ); register_taxonomy( 'brand', array( 'product' ), $args ); } // Hook into the 'init' action add_action( 'init', 'brand', 0 ); </code></pre> <p>I am trying to create a template to show details of brand taxonomy in a page. i tried creating page templates with name</p> <pre><code>taxonomy-brand.php (taxonomy-{slug}.php) taxonomy-brands.php (taxonomy-{name}.php) single-brand.php (single-{slug}.php) single-brands.php (single-{name}.php) </code></pre> <p>But they are not working and wordpress is showing brand details on single.php instead of showing on a custom template. Please tell me where i am doing wrong.</p> <p>Thank you</p>
[ { "answer_id": 186283, "author": "adelval", "author_id": 40965, "author_profile": "https://wordpress.stackexchange.com/users/40965", "pm_score": 4, "selected": true, "text": "<p>You can use <code>wp-config.php</code> to change the site url depending on where the site is accesed from, using <code>$_SERVER['REMOTE_ADDR']</code>. Mine has something like this:</p>\n\n<pre><code>if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { \n // accesing site from my local server\n define('WP_SITEURL', 'http://localhost/mysite/');\n define('WP_HOME', 'http://localhost/mysite');\n} else if (strpos($_SERVER['REMOTE_ADDR'],'192.168.0.') !== false) {\n // accesing site from another machine in my home network, \n // all their (internal) network addresses begin with this number;\n // the next line provides the server's own internal network address \n define('WP_SITEURL', 'http://192.168.0.192/mysite/');\n define('WP_HOME', 'http://192.168.0.192/mysite');\n} else { //accesing site from outside home\n define('WP_SITEURL', 'http://89.*.*.*/mysite/'); //replace by your external home IP\n define('WP_HOME', 'http://89.*.*.*/mysite');\n}\n//error_log(\"Siteurl is \".WP_SITEURL);\n</code></pre>\n\n<p>This technique also helps a lot to simplify uploading the site to a production server or keeping in sync local and production versions of the site. (Though, obviously, the <code>wp-config.php</code> on the production server should not have this code.) </p>\n\n<p>Note: For some reason, I cannot use my external home IP from other machines in my home network; if that's not your case, you can remove the <code>else if</code>, leaving only the <code>else</code> part.</p>\n" }, { "answer_id": 186296, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 1, "selected": false, "text": "<p>Although the accepted answer looks to be a good one, just changing WP_SITEURL/WP_HOME doesn't work in my case because there always ends up being lots of absolute links in the text content on pages (i.e. images or links added through the WYSIWYG editor). In other words, I pretty much <em>have</em> to use the same domain if I want the site to work properly.</p>\n\n<p>So in case it helps someone else who comes across this, my solution was an outside-of-Wordpress one - although it may not help in all cases.</p>\n\n<p>I use a domain, for example me.mycompany.com, and then in my HOSTS file I make it resolve to 127.0.0.1 (in other words, localhost). For any of my colleagues who need to view the site, I add my domain to their HOSTS file with my local IP.</p>\n\n<p>This solution also gets extended when clients outside our network need to view the site; we simply make sure me.mycompany.com resolves to our public IP (usually your web host can help with this, and it definitely helps if you have a static IP for your Internet connection too), and then at our router, route the web requests to my internal IP, effectively setting up an easy web hosting solution (for development only of course, not production!)</p>\n\n<p>Hope this helps someone. The HOSTS file can be edited on any platform, obviously the instructions differ for Windows, Mac and Linux so best you Google for help if you need it, but in Windows the file is C:\\Windows\\System32\\drivers\\etc\\hosts - open it in Notepad and make the neccessary changes, following the format in the file (you will need to run as Administrator in order to save the file).</p>\n" }, { "answer_id": 385467, "author": "katiedev", "author_id": 201500, "author_profile": "https://wordpress.stackexchange.com/users/201500", "pm_score": 1, "selected": false, "text": "<p>From WordPress 5.5.1 you can use the <a href=\"https://developer.wordpress.org/reference/functions/wp_get_environment_type\" rel=\"nofollow noreferrer\">wp_get_environment_type</a> fuction. Set <code>wp_get_environment_type</code> within wp-config.</p>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186313", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71641/" ]
I am trying to create custom template for custom taxonomy. For example i have a custom taxonomy registered in WP with name brands and slug brand i used following code to register custom taxonomy. ``` function brand() { $labels = array( 'name' => _x( 'brands', 'Taxonomy General Name', 'text_domain' ), 'singular_name' => _x( 'brand', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' => __( 'Brands', 'text_domain' ), 'all_items' => __( 'All Brands', 'text_domain' ), 'parent_item' => __( 'Brand Parent Item', 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'new_item_name' => __( 'New Brand', 'text_domain' ), 'add_new_item' => __( 'Add New Brand', 'text_domain' ), 'edit_item' => __( 'Edit Brand', 'text_domain' ), 'update_item' => __( 'Update Brand', 'text_domain' ), 'view_item' => __( 'View Brand', 'text_domain' ), 'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ), 'add_or_remove_items' => __( 'Add or remove Brands', 'text_domain' ), 'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ), 'popular_items' => __( 'Popular Brands', 'text_domain' ), 'search_items' => __( 'Search Brands', 'text_domain' ), 'not_found' => __( 'Not Found', 'text_domain' ), ); $rewrite = array( 'slug' => 'brand', 'with_front' => true, 'hierarchical' => true, ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, 'rewrite' => $rewrite, ); register_taxonomy( 'brand', array( 'product' ), $args ); } // Hook into the 'init' action add_action( 'init', 'brand', 0 ); ``` I am trying to create a template to show details of brand taxonomy in a page. i tried creating page templates with name ``` taxonomy-brand.php (taxonomy-{slug}.php) taxonomy-brands.php (taxonomy-{name}.php) single-brand.php (single-{slug}.php) single-brands.php (single-{name}.php) ``` But they are not working and wordpress is showing brand details on single.php instead of showing on a custom template. Please tell me where i am doing wrong. Thank you
You can use `wp-config.php` to change the site url depending on where the site is accesed from, using `$_SERVER['REMOTE_ADDR']`. Mine has something like this: ``` if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { // accesing site from my local server define('WP_SITEURL', 'http://localhost/mysite/'); define('WP_HOME', 'http://localhost/mysite'); } else if (strpos($_SERVER['REMOTE_ADDR'],'192.168.0.') !== false) { // accesing site from another machine in my home network, // all their (internal) network addresses begin with this number; // the next line provides the server's own internal network address define('WP_SITEURL', 'http://192.168.0.192/mysite/'); define('WP_HOME', 'http://192.168.0.192/mysite'); } else { //accesing site from outside home define('WP_SITEURL', 'http://89.*.*.*/mysite/'); //replace by your external home IP define('WP_HOME', 'http://89.*.*.*/mysite'); } //error_log("Siteurl is ".WP_SITEURL); ``` This technique also helps a lot to simplify uploading the site to a production server or keeping in sync local and production versions of the site. (Though, obviously, the `wp-config.php` on the production server should not have this code.) Note: For some reason, I cannot use my external home IP from other machines in my home network; if that's not your case, you can remove the `else if`, leaving only the `else` part.
186,315
<p>First i write manually update, delete, insert and select query and execute data with <code>mysql_query</code> function</p> <p>Like this:</p> <p>Select query</p> <pre><code>$prefix = $wpdb-&gt;prefix; $postSql = "SELECT DISTINCT post_id FROM " . $prefix . "postmeta As meta Inner Join " . $prefix . "posts As post On post.ID = meta.post_id Where post_type = 'product' And post_status = 'publish' And meta_key Like '%product_img%'"; $postQry = mysql_query($postSql); while ($postRow = mysql_fetch_array($postQry)) { $post_id = $postRow['post_id']; } </code></pre> <p>Insert Query</p> <pre><code>$insert_images = "Insert Into " . $prefix . "postmeta(post_id,meta_key,meta_value) Value('$post_id','$meta_key','$data_serialize')"; mysql_query($insert_images); </code></pre> <p>Update Query:</p> <pre><code>$update_price = "Update " . $prefix . "postmeta Set meta_key = 'wpc_product_price' Where post_id = $supportMetaID And meta_key Like '%product_price%'"; mysql_query($update_price); </code></pre> <p>Delete Query</p> <pre><code>mysql_query("Delete From " . $prefix . "postmeta Where meta_key IN ('product_img1','product_img2','product_img3')"); </code></pre> <p>All queries are working perfectly ... but now i want to embed all queries in wordpress queries.</p> <p>I can also use wordpress queries like</p> <pre><code>$wpdb-&gt;get_results( "SELECT id, name FROM mytable" ); $wpdb-&gt;insert( 'table', array( 'column1' =&gt; 'value1', 'column2' =&gt; 123 ), ); $wpdb-&gt;update( 'table', array( 'column1' =&gt; 'value1', // string 'column2' =&gt; 'value2' // integer (number) ), array( 'ID' =&gt; 1 ) ); $wpdb-&gt;delete( 'table', array( 'ID' =&gt; 1 ) ); </code></pre> <p>But you can see that i use <code>and / or</code> conditions in my queries. So any body help me how can i embed my queries in wordpress</p>
[ { "answer_id": 237866, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 2, "selected": false, "text": "<h1>About UPDATE+INSERT:</h1>\n\n<p>I have made a function for myself, and might help you too, i.e. :</p>\n\n<pre><code>UPDATE_OR_INSERT('wp_users', array('gender'=&gt;'female'), array('name'=&gt;'Monika') );\n</code></pre>\n\n<p>that will UPDATE A VALUE in column (where <code>name=monika</code>), but in case that value doesnt exists, then it creates a new record in DB.<br>\nWhy this is necessary? because As far as i know, there is no sophisticated WP function, that will update data in DB (if value exists) or inserts data (if not exists). Instead, we use : <code>$wpdb-&gt;update()</code> or <code>$wpdb-&gt;insert()</code>. \nSo, use that function, it helps:</p>\n\n<pre><code>function UPDATE_OR_INSERT($tablename, $NewArray, $WhereArray){ global $wpdb; $arrayNames= array_keys($WhereArray);\n //convert array to STRING\n $o=''; $i=1; foreach ($WhereArray as $key=&gt;$value){ $o .= $key . ' = \\''. $value .'\\''; if ($i != count($WhereArray)) { $o .=' AND '; $i++;} }\n //check if already exist\n $CheckIfExists = $wpdb-&gt;get_var(\"SELECT \".$arrayNames[0].\" FROM \".$tablename.\" WHERE \".$o);\n if (!empty($CheckIfExists)) { return $wpdb-&gt;update($tablename, $NewArray, $WhereArray );}\n else { return $wpdb-&gt;insert($tablename, array_merge($NewArray, $WhereArray) ); } \n}\n</code></pre>\n" }, { "answer_id": 365789, "author": "Gurpreet Singh", "author_id": 165487, "author_profile": "https://wordpress.stackexchange.com/users/165487", "pm_score": 2, "selected": false, "text": "<p>Update Query:</p>\n\n<pre><code>$table = $wpdb-&gt;prefix . 'tablename';\n\n$wpdb-&gt;update( $table_name, array( 'role_id' =&gt; 1),array('user_id'=&gt;$user_id));\n</code></pre>\n\n<p>Delete Query:</p>\n\n<pre><code>$wpdb-&gt;delete( $table, array( 'id' =&gt; $id ) );\n</code></pre>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186315", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64316/" ]
First i write manually update, delete, insert and select query and execute data with `mysql_query` function Like this: Select query ``` $prefix = $wpdb->prefix; $postSql = "SELECT DISTINCT post_id FROM " . $prefix . "postmeta As meta Inner Join " . $prefix . "posts As post On post.ID = meta.post_id Where post_type = 'product' And post_status = 'publish' And meta_key Like '%product_img%'"; $postQry = mysql_query($postSql); while ($postRow = mysql_fetch_array($postQry)) { $post_id = $postRow['post_id']; } ``` Insert Query ``` $insert_images = "Insert Into " . $prefix . "postmeta(post_id,meta_key,meta_value) Value('$post_id','$meta_key','$data_serialize')"; mysql_query($insert_images); ``` Update Query: ``` $update_price = "Update " . $prefix . "postmeta Set meta_key = 'wpc_product_price' Where post_id = $supportMetaID And meta_key Like '%product_price%'"; mysql_query($update_price); ``` Delete Query ``` mysql_query("Delete From " . $prefix . "postmeta Where meta_key IN ('product_img1','product_img2','product_img3')"); ``` All queries are working perfectly ... but now i want to embed all queries in wordpress queries. I can also use wordpress queries like ``` $wpdb->get_results( "SELECT id, name FROM mytable" ); $wpdb->insert( 'table', array( 'column1' => 'value1', 'column2' => 123 ), ); $wpdb->update( 'table', array( 'column1' => 'value1', // string 'column2' => 'value2' // integer (number) ), array( 'ID' => 1 ) ); $wpdb->delete( 'table', array( 'ID' => 1 ) ); ``` But you can see that i use `and / or` conditions in my queries. So any body help me how can i embed my queries in wordpress
About UPDATE+INSERT: ==================== I have made a function for myself, and might help you too, i.e. : ``` UPDATE_OR_INSERT('wp_users', array('gender'=>'female'), array('name'=>'Monika') ); ``` that will UPDATE A VALUE in column (where `name=monika`), but in case that value doesnt exists, then it creates a new record in DB. Why this is necessary? because As far as i know, there is no sophisticated WP function, that will update data in DB (if value exists) or inserts data (if not exists). Instead, we use : `$wpdb->update()` or `$wpdb->insert()`. So, use that function, it helps: ``` function UPDATE_OR_INSERT($tablename, $NewArray, $WhereArray){ global $wpdb; $arrayNames= array_keys($WhereArray); //convert array to STRING $o=''; $i=1; foreach ($WhereArray as $key=>$value){ $o .= $key . ' = \''. $value .'\''; if ($i != count($WhereArray)) { $o .=' AND '; $i++;} } //check if already exist $CheckIfExists = $wpdb->get_var("SELECT ".$arrayNames[0]." FROM ".$tablename." WHERE ".$o); if (!empty($CheckIfExists)) { return $wpdb->update($tablename, $NewArray, $WhereArray );} else { return $wpdb->insert($tablename, array_merge($NewArray, $WhereArray) ); } } ```
186,316
<p>well, I'm using woo-commerce plugin to manage a shop. I need to add a user who can manage products(add new, edit). so I added a user and gave him a shop manager role, but the permissions granted for this role is much more than what I wanted (e.g. listing other users, accessing orders, being able to change shop's setting and ...).</p> <p>And I can't figure out how WordPress is managing roles and permissions and in which PHP file woo-commerce is defining this role so that I can edit it.</p>
[ { "answer_id": 187398, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>This is treading very close to being off-topic as it asks specifically about a particular plugin, but the answer is quite generic:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/remove_cap\" rel=\"nofollow\">You can remove the capabilities you don't need.</a></p>\n\n<pre><code>function remove_cap_wpse_186316(){ \n remove_cap( 'yourwoorole', 'yourwoocap' );\n remove_cap( 'yourwoorole', 'yourwoocap1' );\n}\nadd_action( 'admin_init', 'remove_cap_wpse_186316' );\n</code></pre>\n\n<p>The above is code is for demonstration/experimentation only. Note the note in the codex about this needing to only run once:</p>\n\n<blockquote>\n <p>Note: This setting is saved to the database (in table wp_options,\n field 'wp_user_roles'), so you should run this only once, on\n theme/plugin activation and/or deactivation.</p>\n</blockquote>\n\n<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_role\" rel=\"nofollow\"><code>get_role()</code></a> and dump the output to see what capabilities you are dealing with:</p>\n\n<pre><code>var_dump(get_role( 'yourwoorole' ));\n</code></pre>\n" }, { "answer_id": 266198, "author": "J. Shabu", "author_id": 118124, "author_profile": "https://wordpress.stackexchange.com/users/118124", "pm_score": 2, "selected": false, "text": "<p>Please add the following code to the functions.php of your wordpress theme. And change the true to false for the following you don't need to provide access for shopmanger.</p>\n<pre><code> add_role('shop_manager', __('Shop Manager', 'woocommerce'), array(\n \n 'read' =&gt; true,\n \n 'read_private_pages' =&gt; true,\n \n 'read_private_posts' =&gt; true,\n \n 'edit_posts' =&gt; true,\n \n 'edit_pages' =&gt; true,\n \n 'edit_published_posts' =&gt; true,\n \n 'edit_published_pages' =&gt; true,\n \n 'edit_private_pages' =&gt; true,\n \n 'edit_private_posts' =&gt; true,\n \n 'edit_others_posts' =&gt; true,\n \n 'edit_others_pages' =&gt; true,\n \n 'publish_posts' =&gt; true,\n \n 'publish_pages' =&gt; true,\n \n 'delete_posts' =&gt; true,\n \n 'delete_pages' =&gt; true,\n \n 'delete_private_pages' =&gt; true,\n \n 'delete_private_posts' =&gt; true,\n \n 'delete_published_pages' =&gt; true,\n \n 'delete_published_posts' =&gt; true,\n \n 'delete_others_posts' =&gt; true,\n \n 'delete_others_pages' =&gt; true,\n \n 'manage_categories' =&gt; true,\n \n 'manage_links' =&gt; true,\n \n 'moderate_comments' =&gt; true,\n \n 'unfiltered_html' =&gt; true,\n \n ‘upload_files’ =&gt; true,\n \n ‘export’ =&gt; true,\n \n ‘import’ =&gt; true,\n \n ‘manage_woocommerce’ =&gt; true,\n \n 'manage_woocommerce_orders' =&gt; true,\n \n 'manage_woocommerce_coupons' =&gt; true,\n \n 'manage_woocommerce_products' =&gt; true,\n \n 'view_woocommerce_reports' =&gt; true\n \n ));\n</code></pre>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186316", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71621/" ]
well, I'm using woo-commerce plugin to manage a shop. I need to add a user who can manage products(add new, edit). so I added a user and gave him a shop manager role, but the permissions granted for this role is much more than what I wanted (e.g. listing other users, accessing orders, being able to change shop's setting and ...). And I can't figure out how WordPress is managing roles and permissions and in which PHP file woo-commerce is defining this role so that I can edit it.
This is treading very close to being off-topic as it asks specifically about a particular plugin, but the answer is quite generic: [You can remove the capabilities you don't need.](http://codex.wordpress.org/Function_Reference/remove_cap) ``` function remove_cap_wpse_186316(){ remove_cap( 'yourwoorole', 'yourwoocap' ); remove_cap( 'yourwoorole', 'yourwoocap1' ); } add_action( 'admin_init', 'remove_cap_wpse_186316' ); ``` The above is code is for demonstration/experimentation only. Note the note in the codex about this needing to only run once: > > Note: This setting is saved to the database (in table wp\_options, > field 'wp\_user\_roles'), so you should run this only once, on > theme/plugin activation and/or deactivation. > > > You can use [`get_role()`](https://codex.wordpress.org/Function_Reference/get_role) and dump the output to see what capabilities you are dealing with: ``` var_dump(get_role( 'yourwoorole' )); ```
186,319
<p>I am getting started with Docker and I'm still new to professional WordPress development practices. I would like to set up a Docker development environment (on my Mac) so that I can do custom WordPress theme development.</p> <p>Assuming you have done this before and are already using Docker, how did you set this up? What does your Dockerfile and docker-compose.yml look like? I'm sure this has been done before. I wouldn't be surprised if there's already one-line command that can set this up for you.</p> <p><strong>Update:</strong> I've narrow this topic down to the following question:</p> <h3>How can I configure Docker for developing and deploying a custom theme?</h3>
[ { "answer_id": 187430, "author": "Andrew", "author_id": 60152, "author_profile": "https://wordpress.stackexchange.com/users/60152", "pm_score": 3, "selected": false, "text": "<p>I'm going to post a partial answer to start the discussion in the hope of getting some helpful comments to fill in the blanks or alternative answers...</p>\n\n<h1>Step 1: Install and Set Up boot2docker</h1>\n\n<p>Docker only runs on Linux. So in order to use Docker on our Mac, we need to install <code>boot2docker</code>, which will run Docker in a Linux VM. You can install <code>boot2docker</code> using <a href=\"http://brew.sh/\">Homebrew</a>:</p>\n\n<pre><code>brew install boot2docker\n</code></pre>\n\n<p>Once it has finished installing, set up and start boot2docker:</p>\n\n<pre><code>boot2docker init\nboot2docker start\n</code></pre>\n\n<p>Next, we need to run a command to set up some environment variables so that docker-compose will know to find Docker inside our boot2docker VM.</p>\n\n<pre><code>eval \"$(boot2docker shellinit)\"\n</code></pre>\n\n<p>You may want to add the lines that export variables to your <code>~/.bash_profile</code> so that you don't have to run the command every time you open a new terminal window.</p>\n\n<h1>Step 2: Install docker-compose</h1>\n\n<p>There is a Docker plugin called <code>docker-compose</code> (originally called <code>fig</code>) which makes it really easy to define the relationship between your Docker containers. You can also install it using Homebrew:</p>\n\n<pre><code>brew install docker-compose\n</code></pre>\n\n<h1>Step 3: Create docker-compose.yml</h1>\n\n<p>There's an <a href=\"https://registry.hub.docker.com/_/wordpress/\">official WordPress Docker image</a> in the Docker registry. It includes some information about manually starting up Docker with all of the command line flags necessary to make it all work. As far as I can tell, you can skip all of that because we will be using <code>docker-compose</code>. In the directory where you will be working on your WordPress theme, create a <code>docker-compose.yml</code> with the following contents:</p>\n\n<pre><code>wordpress:\n image: wordpress\n links:\n - db:mysql\n ports:\n - 8080:80\n volumes:\n - .:/var/www/html/wp-content/themes/my-theme-name\n\ndb:\n image: mariadb\n environment:\n MYSQL_ROOT_PASSWORD: example\n</code></pre>\n\n<p>The <code>volumes</code> configuration links our theme files in our current directory to a new theme directory inside the Docker container.</p>\n\n<h1>Step 4: Start the containers</h1>\n\n<p>Run <code>docker-compose up</code> and you will set up two Docker containers (\"wordpress\" and \"db\") running an installation of WordPress.</p>\n\n<h1>Step 5: Open the site in the browser</h1>\n\n<p>Our <code>docker-compose.yml</code> configuration specified that we are forwarding port 80 to port 8080. Also, <code>boot2docker</code> runs its VM on a specific IP address. Thus, in order to figure out the URL, we need to use the <code>boot2docker ip</code> command:</p>\n\n<pre><code>open http://$(boot2docker ip):8080\n</code></pre>\n\n<h1>Questions</h1>\n\n<p>Now that I have the containers up and running, I have a few questions...</p>\n\n<ol>\n<li><p>Is there an automated way of setting up the boot2docker environment variables, other than copy and paste the exports listed in <code>boot2docker shellinit</code>?</p></li>\n<li><p>When I'm working on a Rails application, I like to use <a href=\"http://pow.cx/\">Pow</a> so that I can access the app using a named <code>.dev</code> domain instead of working with specific ports/IPs. How can I configure my system (or Pow) so that I can access the host using <a href=\"http://mysite.dev\">http://mysite.dev</a>?</p></li>\n<li><p>Are there any steps that I missed? Or are there any steps that should be added to the end?</p></li>\n</ol>\n" }, { "answer_id": 305160, "author": "Alex MacArthur", "author_id": 89080, "author_profile": "https://wordpress.stackexchange.com/users/89080", "pm_score": 0, "selected": false, "text": "<p>My preferred solution for this is using Composer in combination with Docker. Docker handles the environment, Composer handles the dependencies, which includes themes, plugins, and any other packages I might need. </p>\n\n<p>Here's my own local Docker setup: </p>\n\n<p><a href=\"https://github.com/alexmacarthur/wp-skateboard\" rel=\"nofollow noreferrer\">https://github.com/alexmacarthur/wp-skateboard</a></p>\n\n<p>And here's a branch that uses Composer to download the _s theme and place it in my <code>themes</code> directory: </p>\n\n<p><a href=\"https://github.com/alexmacarthur/wp-skateboard/tree/starter-theme-underscores\" rel=\"nofollow noreferrer\">https://github.com/alexmacarthur/wp-skateboard/tree/starter-theme-underscores</a></p>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186319", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60152/" ]
I am getting started with Docker and I'm still new to professional WordPress development practices. I would like to set up a Docker development environment (on my Mac) so that I can do custom WordPress theme development. Assuming you have done this before and are already using Docker, how did you set this up? What does your Dockerfile and docker-compose.yml look like? I'm sure this has been done before. I wouldn't be surprised if there's already one-line command that can set this up for you. **Update:** I've narrow this topic down to the following question: ### How can I configure Docker for developing and deploying a custom theme?
I'm going to post a partial answer to start the discussion in the hope of getting some helpful comments to fill in the blanks or alternative answers... Step 1: Install and Set Up boot2docker ====================================== Docker only runs on Linux. So in order to use Docker on our Mac, we need to install `boot2docker`, which will run Docker in a Linux VM. You can install `boot2docker` using [Homebrew](http://brew.sh/): ``` brew install boot2docker ``` Once it has finished installing, set up and start boot2docker: ``` boot2docker init boot2docker start ``` Next, we need to run a command to set up some environment variables so that docker-compose will know to find Docker inside our boot2docker VM. ``` eval "$(boot2docker shellinit)" ``` You may want to add the lines that export variables to your `~/.bash_profile` so that you don't have to run the command every time you open a new terminal window. Step 2: Install docker-compose ============================== There is a Docker plugin called `docker-compose` (originally called `fig`) which makes it really easy to define the relationship between your Docker containers. You can also install it using Homebrew: ``` brew install docker-compose ``` Step 3: Create docker-compose.yml ================================= There's an [official WordPress Docker image](https://registry.hub.docker.com/_/wordpress/) in the Docker registry. It includes some information about manually starting up Docker with all of the command line flags necessary to make it all work. As far as I can tell, you can skip all of that because we will be using `docker-compose`. In the directory where you will be working on your WordPress theme, create a `docker-compose.yml` with the following contents: ``` wordpress: image: wordpress links: - db:mysql ports: - 8080:80 volumes: - .:/var/www/html/wp-content/themes/my-theme-name db: image: mariadb environment: MYSQL_ROOT_PASSWORD: example ``` The `volumes` configuration links our theme files in our current directory to a new theme directory inside the Docker container. Step 4: Start the containers ============================ Run `docker-compose up` and you will set up two Docker containers ("wordpress" and "db") running an installation of WordPress. Step 5: Open the site in the browser ==================================== Our `docker-compose.yml` configuration specified that we are forwarding port 80 to port 8080. Also, `boot2docker` runs its VM on a specific IP address. Thus, in order to figure out the URL, we need to use the `boot2docker ip` command: ``` open http://$(boot2docker ip):8080 ``` Questions ========= Now that I have the containers up and running, I have a few questions... 1. Is there an automated way of setting up the boot2docker environment variables, other than copy and paste the exports listed in `boot2docker shellinit`? 2. When I'm working on a Rails application, I like to use [Pow](http://pow.cx/) so that I can access the app using a named `.dev` domain instead of working with specific ports/IPs. How can I configure my system (or Pow) so that I can access the host using <http://mysite.dev>? 3. Are there any steps that I missed? Or are there any steps that should be added to the end?
186,326
<p>I need change WP password without logout profile. When I use wp_set_password( $password, $user_ID ) i have problem with logout.</p>
[ { "answer_id": 186331, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>I have no working example, only hints for thinking about this topic.\nThe function to set a new password via the function of the core is right. But if you are using this function on the user update page, then the user will be automatic get logged out as it is deleting the cache of the logged-in users.</p>\n<p>After the logout, can you hook in <code>wp</code> and create a new login. You must do this before anything is sent via 'headers'.</p>\n<pre><code>`add_action( 'wp', 'your_login' );`\n</code></pre>\n<p>Also think about the cookie of the login - <a href=\"http://codex.wordpress.org/Function_Reference/wp_set_auth_cookie\" rel=\"nofollow noreferrer\"><code>wp_set_auth_cookie</code></a>! Also you can delete the current cache for the user - <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache#wp_cache_functions\" rel=\"nofollow noreferrer\"><code>wp_cache_delete()</code></a>.</p>\n<p>Maybe this <a href=\"https://stackoverflow.com/questions/5706075/php-wordpress-password-change-logging-me-out\">question</a> and his answers help you, the same topic.</p>\n" }, { "answer_id": 217345, "author": "Mayur Chauhan", "author_id": 85001, "author_profile": "https://wordpress.stackexchange.com/users/85001", "pm_score": 3, "selected": false, "text": "<p>Try below code, it won't log you out after the password change and it works with Ajax functions too. No need to reset cookies/sessions afterwards.</p>\n<pre><code>$userdata['ID'] = 1; //user ID\n$userdata['user_pass'] = 'new_password';\nwp_update_user( $userdata ); // this will handle encryption and everything\n</code></pre>\n<p>Cheers</p>\n" }, { "answer_id": 265267, "author": "liviucmg", "author_id": 19418, "author_profile": "https://wordpress.stackexchange.com/users/19418", "pm_score": 3, "selected": false, "text": "<p>If you are changing the password for the current logged-in user, it will log you out. You have to log in again:</p>\n\n<pre><code>// Get current logged-in user.\n$user = wp_get_current_user();\n\n// Change password.\nwp_set_password($new_password, $user-&gt;ID);\n\n// Log-in again.\nwp_set_auth_cookie($user-&gt;ID);\nwp_set_current_user($user-&gt;ID);\ndo_action('wp_login', $user-&gt;user_login, $user);\n</code></pre>\n\n<p>Note that since you are setting a new log-in cookie (i.e. changing headers), you need to run this code before any other output (HTML or echos).</p>\n" }, { "answer_id": 309629, "author": "Dragi Postolovski", "author_id": 119457, "author_profile": "https://wordpress.stackexchange.com/users/119457", "pm_score": 0, "selected": false, "text": "<pre><code>function change_client_password() {\n $current_user = $_POST['current_user'];\n $current_password = $_POST['current_password'];\n $new_password = $_POST['new_password'];\n $confirm_password = $_POST['confirm_password'];\n $user = get_user_by( 'ID', $current_user );\n\n $result = wp_check_password( $current_password, $user-&gt;data-&gt;user_pass, $current_user );\n\n if ( $result ) {\n if ( $new_password == $confirm_password ) {\n wp_set_password( $new_password, $current_user );\n wp_set_auth_cookie ( $current_user );\n wp_set_current_user( $current_user );\n do_action('wp_login', $user-&gt;user_login, $user );\n echo 'Your new password is changed.';\n } else {\n echo 'Your current password is correct, but the new and confirm passwords do not match.';\n }\n } else {\n echo 'Your current password is incorrect.';\n }\n\n wp_die();\n}\n</code></pre>\n" }, { "answer_id": 350204, "author": "Akel", "author_id": 43678, "author_profile": "https://wordpress.stackexchange.com/users/43678", "pm_score": 0, "selected": false, "text": "<p>Update the user's password using wp_set_password(), and then log the user back in, using wp_signon(). </p>\n\n<p>wp_signon will create the authentication cookie for you, as other users have suggested, but in a much more streamlined way. </p>\n\n<pre><code>function create_new_password_for_user($new_password){\n //Get the current user's details, while they're still signed in, in this scope.\n $current_user = wp_get_current_user();\n $current_user_id = $current_user-&gt;ID;\n $users_login = $current_user-&gt;user_email;\n\n //set their new password (this will trigger the logout)\n wp_set_password($new_password, $current_user_id);\n\n //setup the data to be passed on to wp_signon\n $user_data = array(\n 'user_login' =&gt; $users_login,\n 'user_password' =&gt; $new_password,\n 'remember' =&gt; false\n );\n\n // Sign them back in.\n $result = wp_signon( $user_data );\n\n if(is_wp_error($result)){\n //do something with an error, if there is one.\n }else{\n //do something with the successful change. \n }\n}\n</code></pre>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186326", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71646/" ]
I need change WP password without logout profile. When I use wp\_set\_password( $password, $user\_ID ) i have problem with logout.
Try below code, it won't log you out after the password change and it works with Ajax functions too. No need to reset cookies/sessions afterwards. ``` $userdata['ID'] = 1; //user ID $userdata['user_pass'] = 'new_password'; wp_update_user( $userdata ); // this will handle encryption and everything ``` Cheers
186,327
<p>This function will show the last 3 posts from any category on front page:</p> <pre><code> // Only top 3 posts from CHR category add_action('pre_get_posts', 'ad_filter_categories'); function ad_filter_categories($query) { if ($query-&gt;is_main_query() &amp;&amp; is_home()) { $query-&gt;set('category_name','chatham-house-rules'); $query-&gt;set('showposts', 3); } </code></pre> <p>I want to do this twice more with two other categories but it will only ever work with one. It also defaults to the posts_per_page setting in the Admin panel. Any ideas how I can achieve 3 latest posts from 3 categories in specific order on front page? </p>
[ { "answer_id": 186331, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>I have no working example, only hints for thinking about this topic.\nThe function to set a new password via the function of the core is right. But if you are using this function on the user update page, then the user will be automatic get logged out as it is deleting the cache of the logged-in users.</p>\n<p>After the logout, can you hook in <code>wp</code> and create a new login. You must do this before anything is sent via 'headers'.</p>\n<pre><code>`add_action( 'wp', 'your_login' );`\n</code></pre>\n<p>Also think about the cookie of the login - <a href=\"http://codex.wordpress.org/Function_Reference/wp_set_auth_cookie\" rel=\"nofollow noreferrer\"><code>wp_set_auth_cookie</code></a>! Also you can delete the current cache for the user - <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache#wp_cache_functions\" rel=\"nofollow noreferrer\"><code>wp_cache_delete()</code></a>.</p>\n<p>Maybe this <a href=\"https://stackoverflow.com/questions/5706075/php-wordpress-password-change-logging-me-out\">question</a> and his answers help you, the same topic.</p>\n" }, { "answer_id": 217345, "author": "Mayur Chauhan", "author_id": 85001, "author_profile": "https://wordpress.stackexchange.com/users/85001", "pm_score": 3, "selected": false, "text": "<p>Try below code, it won't log you out after the password change and it works with Ajax functions too. No need to reset cookies/sessions afterwards.</p>\n<pre><code>$userdata['ID'] = 1; //user ID\n$userdata['user_pass'] = 'new_password';\nwp_update_user( $userdata ); // this will handle encryption and everything\n</code></pre>\n<p>Cheers</p>\n" }, { "answer_id": 265267, "author": "liviucmg", "author_id": 19418, "author_profile": "https://wordpress.stackexchange.com/users/19418", "pm_score": 3, "selected": false, "text": "<p>If you are changing the password for the current logged-in user, it will log you out. You have to log in again:</p>\n\n<pre><code>// Get current logged-in user.\n$user = wp_get_current_user();\n\n// Change password.\nwp_set_password($new_password, $user-&gt;ID);\n\n// Log-in again.\nwp_set_auth_cookie($user-&gt;ID);\nwp_set_current_user($user-&gt;ID);\ndo_action('wp_login', $user-&gt;user_login, $user);\n</code></pre>\n\n<p>Note that since you are setting a new log-in cookie (i.e. changing headers), you need to run this code before any other output (HTML or echos).</p>\n" }, { "answer_id": 309629, "author": "Dragi Postolovski", "author_id": 119457, "author_profile": "https://wordpress.stackexchange.com/users/119457", "pm_score": 0, "selected": false, "text": "<pre><code>function change_client_password() {\n $current_user = $_POST['current_user'];\n $current_password = $_POST['current_password'];\n $new_password = $_POST['new_password'];\n $confirm_password = $_POST['confirm_password'];\n $user = get_user_by( 'ID', $current_user );\n\n $result = wp_check_password( $current_password, $user-&gt;data-&gt;user_pass, $current_user );\n\n if ( $result ) {\n if ( $new_password == $confirm_password ) {\n wp_set_password( $new_password, $current_user );\n wp_set_auth_cookie ( $current_user );\n wp_set_current_user( $current_user );\n do_action('wp_login', $user-&gt;user_login, $user );\n echo 'Your new password is changed.';\n } else {\n echo 'Your current password is correct, but the new and confirm passwords do not match.';\n }\n } else {\n echo 'Your current password is incorrect.';\n }\n\n wp_die();\n}\n</code></pre>\n" }, { "answer_id": 350204, "author": "Akel", "author_id": 43678, "author_profile": "https://wordpress.stackexchange.com/users/43678", "pm_score": 0, "selected": false, "text": "<p>Update the user's password using wp_set_password(), and then log the user back in, using wp_signon(). </p>\n\n<p>wp_signon will create the authentication cookie for you, as other users have suggested, but in a much more streamlined way. </p>\n\n<pre><code>function create_new_password_for_user($new_password){\n //Get the current user's details, while they're still signed in, in this scope.\n $current_user = wp_get_current_user();\n $current_user_id = $current_user-&gt;ID;\n $users_login = $current_user-&gt;user_email;\n\n //set their new password (this will trigger the logout)\n wp_set_password($new_password, $current_user_id);\n\n //setup the data to be passed on to wp_signon\n $user_data = array(\n 'user_login' =&gt; $users_login,\n 'user_password' =&gt; $new_password,\n 'remember' =&gt; false\n );\n\n // Sign them back in.\n $result = wp_signon( $user_data );\n\n if(is_wp_error($result)){\n //do something with an error, if there is one.\n }else{\n //do something with the successful change. \n }\n}\n</code></pre>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186327", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71647/" ]
This function will show the last 3 posts from any category on front page: ``` // Only top 3 posts from CHR category add_action('pre_get_posts', 'ad_filter_categories'); function ad_filter_categories($query) { if ($query->is_main_query() && is_home()) { $query->set('category_name','chatham-house-rules'); $query->set('showposts', 3); } ``` I want to do this twice more with two other categories but it will only ever work with one. It also defaults to the posts\_per\_page setting in the Admin panel. Any ideas how I can achieve 3 latest posts from 3 categories in specific order on front page?
Try below code, it won't log you out after the password change and it works with Ajax functions too. No need to reset cookies/sessions afterwards. ``` $userdata['ID'] = 1; //user ID $userdata['user_pass'] = 'new_password'; wp_update_user( $userdata ); // this will handle encryption and everything ``` Cheers
186,337
<p>So I'm having some issues with this and I can't see why. I just need a custom role that can access the blog in the back end.</p> <p>I've added a new post type with a Capability type of <code>blog</code> and a new user role with all the caps fr it that would allow admin access users to add/edit the custom post type. This works for admins and they can access the post type in the back end. However users of my custom role can not get into the back end at all.</p> <p><strong>Post type args of note</strong></p> <pre><code>"capability_type" =&gt; 'blog', "map_meta_cap" =&gt; true, </code></pre> <p><strong>Register role</strong></p> <pre><code>function add_blog_manager_role(){ add_role( 'blog_manager', 'Blog Manager', array( 'read' =&gt; true, 'edit_posts' =&gt; false, 'delete_posts' =&gt; false, 'publish_posts' =&gt; false, 'upload_files' =&gt; true ) ); } add_action( 'admin_init', 'add_blog_manager_role', 4 ); </code></pre> <p><strong>Add Caps</strong></p> <pre><code>function add_blog_role_caps() { $roles = array('blog_manager', 'editor','administrator'); foreach($roles as $the_role) { $role = get_role($the_role); $role-&gt;add_cap( 'read' ); $role-&gt;add_cap( 'read_blog'); $role-&gt;add_cap( 'read_private_blog' ); $role-&gt;add_cap( 'edit_blog' ); $role-&gt;add_cap( 'edit_others_blog' ); $role-&gt;add_cap( 'edit_published_blog' ); $role-&gt;add_cap( 'publish_blog' ); $role-&gt;add_cap( 'delete_others_blog' ); $role-&gt;add_cap( 'delete_private_blog' ); $role-&gt;add_cap( 'delete_published_blog' ); } } add_action('admin_init', 'add_blog_role_caps', 5 ); </code></pre> <p>I've been googeling frantically trying to find the cause of this. I've tried with plural, non plural caps, tried adding capabilities into the post type args. However I'm never able to get into the back end. I've not got any other code in the theme that might kick users out of the admin (I removed my own code that kicked them out while testing this)</p> <p><strong>Edit</strong> Here you can see a dump of the blog_manager capabilities from the database, there is a fair bit of testing BS left in there, bu/t that shouldn't stop them being able to login from what I know.</p> <pre><code>'blog_manager' =&gt; array ( 'name' =&gt; 'Blog Manager', 'capabilities' =&gt; array ( 'read' =&gt; true, 'edit_posts' =&gt; false, 'delete_posts' =&gt; false, 'publish_posts' =&gt; false, 'upload_files' =&gt; true, 'read_blog' =&gt; true, 'read_private_blog' =&gt; true, 'edit_blog' =&gt; true, 'edit_others_blog' =&gt; true, 'edit_published_blog' =&gt; true, 'publish_blog' =&gt; true, 'delete_others_blog' =&gt; true, 'delete_private_blog' =&gt; true, 'delete_published_blog' =&gt; true, 'blog' =&gt; true, 'read_private_blogs' =&gt; true, 'edit_blogs' =&gt; true, 'edit_others_blogs' =&gt; true, 'edit_published_blogs' =&gt; true, 'publish_blogs' =&gt; true, 'delete_others_blogs' =&gt; true, 'delete_private_blogs' =&gt; true, 'delete_published_blogs' =&gt; true, 'delete_blogs' =&gt; true, 'delete_blog' =&gt; true, ), ) </code></pre>
[ { "answer_id": 235193, "author": "Akshay Shah", "author_id": 54263, "author_profile": "https://wordpress.stackexchange.com/users/54263", "pm_score": 0, "selected": false, "text": "<p>If you are ok with plugin than you can use velow plugin.</p>\n\n<p><a href=\"https://wordpress.org/plugins/capability-manager-enhanced/\" rel=\"nofollow\">https://wordpress.org/plugins/capability-manager-enhanced/</a></p>\n" }, { "answer_id": 257401, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": false, "text": "<p>It's hard to troubleshoot the above code because it's only a part of the actual code, but here's the minimum plugin needed to register a custom post type (called Example) and a custom role (Blog Manager) that has access to the Example custom post type.</p>\n\n<p>This can be used as part of a theme's functions.php file as well. Just use the theme activation and deactivation hooks instead.</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: WPSE 186337\n * Description: Debug WordPress StackExchange question 186337\n * Plugin URI: https://wordpress.stackexchange.com/questions/186337/\n * Author: Nathan Johnson\n * Licence: GPL2+\n * Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html\n */\n\n//* Don't access this file directly\ndefined( 'ABSPATH' ) or die();\n\n//* Add action to init to register custom post type\nadd_action( 'init', 'se186337_init' );\n\n//* Register activation hook to add Blog Manager role\nregister_activation_hook( __FILE__ , 'se186337_activation' );\n\n//* Register deactivation hook to remove Blog Manager role\nregister_deactivation_hook( __FILE__ , 'se186337_deactivation' );\n\nfunction se186337_activation() {\n $caps = [\n //* Meta capabilities\n 'read' =&gt; true,\n 'edit_blog' =&gt; true,\n 'read_blog' =&gt; true,\n 'delete_blog' =&gt; true,\n\n //* Primitive capabilities used outside of map_meta_cap()\n 'edit_blogs' =&gt; true,\n 'edit_others_blogs' =&gt; true,\n 'publish_blogs' =&gt; true,\n 'read_private_blogs' =&gt; true,\n\n //* Primitive capabilities used within of map_meta_cap()\n 'delete_blogs' =&gt; true,\n 'delete_private_blogs' =&gt; true,\n 'delete_published_blogs' =&gt; true,\n 'delete_others_blogs' =&gt; true,\n 'edit_private_blogs' =&gt; true,\n 'edit_published_blogs' =&gt; true,\n ];\n\n add_role( 'blog_manager', 'Blog Manager', $caps );\n}\n\nfunction se186337_deactivation() {\n remove_role( 'blog_manager' );\n}\n\nfunction se186337_init() {\n $labels = [\n 'name' =&gt; __( 'Examples' ),\n 'singular_name' =&gt; __( 'Example' ),\n ];\n $args = [\n 'labels' =&gt; $labels,\n 'public' =&gt; true,\n 'has_archive' =&gt; true,\n 'capability_type' =&gt; 'blog',\n 'map_meta_cap' =&gt; true,\n ];\n register_post_type( 'examples', $args );\n}\n</code></pre>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39242/" ]
So I'm having some issues with this and I can't see why. I just need a custom role that can access the blog in the back end. I've added a new post type with a Capability type of `blog` and a new user role with all the caps fr it that would allow admin access users to add/edit the custom post type. This works for admins and they can access the post type in the back end. However users of my custom role can not get into the back end at all. **Post type args of note** ``` "capability_type" => 'blog', "map_meta_cap" => true, ``` **Register role** ``` function add_blog_manager_role(){ add_role( 'blog_manager', 'Blog Manager', array( 'read' => true, 'edit_posts' => false, 'delete_posts' => false, 'publish_posts' => false, 'upload_files' => true ) ); } add_action( 'admin_init', 'add_blog_manager_role', 4 ); ``` **Add Caps** ``` function add_blog_role_caps() { $roles = array('blog_manager', 'editor','administrator'); foreach($roles as $the_role) { $role = get_role($the_role); $role->add_cap( 'read' ); $role->add_cap( 'read_blog'); $role->add_cap( 'read_private_blog' ); $role->add_cap( 'edit_blog' ); $role->add_cap( 'edit_others_blog' ); $role->add_cap( 'edit_published_blog' ); $role->add_cap( 'publish_blog' ); $role->add_cap( 'delete_others_blog' ); $role->add_cap( 'delete_private_blog' ); $role->add_cap( 'delete_published_blog' ); } } add_action('admin_init', 'add_blog_role_caps', 5 ); ``` I've been googeling frantically trying to find the cause of this. I've tried with plural, non plural caps, tried adding capabilities into the post type args. However I'm never able to get into the back end. I've not got any other code in the theme that might kick users out of the admin (I removed my own code that kicked them out while testing this) **Edit** Here you can see a dump of the blog\_manager capabilities from the database, there is a fair bit of testing BS left in there, bu/t that shouldn't stop them being able to login from what I know. ``` 'blog_manager' => array ( 'name' => 'Blog Manager', 'capabilities' => array ( 'read' => true, 'edit_posts' => false, 'delete_posts' => false, 'publish_posts' => false, 'upload_files' => true, 'read_blog' => true, 'read_private_blog' => true, 'edit_blog' => true, 'edit_others_blog' => true, 'edit_published_blog' => true, 'publish_blog' => true, 'delete_others_blog' => true, 'delete_private_blog' => true, 'delete_published_blog' => true, 'blog' => true, 'read_private_blogs' => true, 'edit_blogs' => true, 'edit_others_blogs' => true, 'edit_published_blogs' => true, 'publish_blogs' => true, 'delete_others_blogs' => true, 'delete_private_blogs' => true, 'delete_published_blogs' => true, 'delete_blogs' => true, 'delete_blog' => true, ), ) ```
It's hard to troubleshoot the above code because it's only a part of the actual code, but here's the minimum plugin needed to register a custom post type (called Example) and a custom role (Blog Manager) that has access to the Example custom post type. This can be used as part of a theme's functions.php file as well. Just use the theme activation and deactivation hooks instead. ``` <?php /** * Plugin Name: WPSE 186337 * Description: Debug WordPress StackExchange question 186337 * Plugin URI: https://wordpress.stackexchange.com/questions/186337/ * Author: Nathan Johnson * Licence: GPL2+ * Licence URI: https://www.gnu.org/licenses/gpl-2.0.en.html */ //* Don't access this file directly defined( 'ABSPATH' ) or die(); //* Add action to init to register custom post type add_action( 'init', 'se186337_init' ); //* Register activation hook to add Blog Manager role register_activation_hook( __FILE__ , 'se186337_activation' ); //* Register deactivation hook to remove Blog Manager role register_deactivation_hook( __FILE__ , 'se186337_deactivation' ); function se186337_activation() { $caps = [ //* Meta capabilities 'read' => true, 'edit_blog' => true, 'read_blog' => true, 'delete_blog' => true, //* Primitive capabilities used outside of map_meta_cap() 'edit_blogs' => true, 'edit_others_blogs' => true, 'publish_blogs' => true, 'read_private_blogs' => true, //* Primitive capabilities used within of map_meta_cap() 'delete_blogs' => true, 'delete_private_blogs' => true, 'delete_published_blogs' => true, 'delete_others_blogs' => true, 'edit_private_blogs' => true, 'edit_published_blogs' => true, ]; add_role( 'blog_manager', 'Blog Manager', $caps ); } function se186337_deactivation() { remove_role( 'blog_manager' ); } function se186337_init() { $labels = [ 'name' => __( 'Examples' ), 'singular_name' => __( 'Example' ), ]; $args = [ 'labels' => $labels, 'public' => true, 'has_archive' => true, 'capability_type' => 'blog', 'map_meta_cap' => true, ]; register_post_type( 'examples', $args ); } ```
186,357
<p>I have made some changes (colours, etc...) in the appearance customize from my child theme, is actually working as is just applying to my child, but when I open the style.css from my child I don't see any change, where these changes are?</p>
[ { "answer_id": 186358, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": true, "text": "<p>If you mean the WordPress Customizer: These changes are not saved to the style.css, but they come most likely to be found shortly before <code>&lt;/head&gt;</code>. Probably you will find there something like</p>\n\n<pre><code>&lt;style&gt;\n//definitions via Customizer\n&lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 186359, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 0, "selected": false, "text": "<p>The theme changes in customizer are applied <code>inline</code> or before the <code>&lt;/head&gt;</code> to your WordPress site.</p>\n\n<p>Technically speaking there are three hooks: <code>$wp_customize</code> <code>customize_register</code> <code>wp_head</code> which are used by theme developers to include the changes directly to theme without using the default style.css</p>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186357", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71663/" ]
I have made some changes (colours, etc...) in the appearance customize from my child theme, is actually working as is just applying to my child, but when I open the style.css from my child I don't see any change, where these changes are?
If you mean the WordPress Customizer: These changes are not saved to the style.css, but they come most likely to be found shortly before `</head>`. Probably you will find there something like ``` <style> //definitions via Customizer </style> ```
186,366
<p>Woocommerce has three built in image sizes. But since there are more than three different container sizes, some images always get stretched or squeezed. Hence image quality and page speed suffer. Woocommerce uses for example the catalogue size for catalogue images and related product images. Wordpress offers an easy method to generate custom image sizes. And i've tried to generate a size for my related products:</p> <pre><code>add_action( 'after_setup_theme', 'jmt_theme_setup' ); function jmt_theme_setup() { add_image_size( 'related-thumb', 274, 274, true ); } </code></pre> <p>Is there a way to plug this size into woocommerce related product images?</p> <p>Thanks for your interest.</p> <p>regards theo</p>
[ { "answer_id": 186367, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 1, "selected": false, "text": "<p>You can overwrite the CSS of WooCommerce through this snippet, <a href=\"http://www.remicorson.com/woocommerce-change-related-products-image-size/\" rel=\"nofollow\">Remi Corson</a>:</p>\n\n<pre><code>&lt;?php\nadd_filter( 'wp_head' , 'related_products_style' );\n\nfunction related_products_style() {\n if( is_product() ) :\n ?&gt;\n &lt;style&gt;\n .woocommerce .related ul.products li.product img, .woocommerce .related ul li.product img, .woocommerce .upsells.products ul.products li.product img, .woocommerce .upsells.products ul li.product img, .woocommerce-page .related ul.products li.product img, .woocommerce-page .related ul li.product img, .woocommerce-page .upsells.products ul.products li.product img, .woocommerce-page .upsells.products ul li.product img\n {\n width: 274px !important;\n height: 274px !important;\n }\n &lt;/style&gt;\n&lt;?php\nendif;\n}\n</code></pre>\n" }, { "answer_id": 186368, "author": "Stefan", "author_id": 70492, "author_profile": "https://wordpress.stackexchange.com/users/70492", "pm_score": 0, "selected": false, "text": "<p>I think it's a CSS problem because WooCommerce (annoyingly) uses <code>width: 100%</code> when it (in my opinion) should be <code>max-width: 100%</code>. Try to overwrite the width using <code>width: auto</code>, that should help.</p>\n" }, { "answer_id": 186370, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": true, "text": "<p>There's a few options you can choose from whenever changing image sizes. Switching out the actual default WooCommerce images is more difficult than a normal WordPress install as they are ingrained with the plugin.</p>\n\n<hr>\n\n<p><strong>Modify Related Product Image Sizes:</strong></p>\n\n<p>I've tested this and it seems to work only on related products ( though I'm sure it could be expanded to other areas ). You may still need to take advantage of <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow\">Regenerate Thumbnails</a> to get the correct sizes.</p>\n\n<p>We need to put everything into a <code>wp</code> filter:</p>\n\n<pre><code>function woo_init() {\n // Below functions go here...\n}\nadd_action( 'wp', 'woo_init' );\n</code></pre>\n\n<p>I was able to skip the first portion of this, setting the query var and still have it work but since it uses a generic <code>content-product.php</code> template I wouldn't trust it, so we will set a query var ensuring we are only change the image size for related products:</p>\n\n<pre><code>if( is_singular( 'product' ) ) {\n add_filter( 'woocommerce_related_products_args', function( $query_args ) {\n if( ! empty( $query_args ) ) {\n set_query_var( 'related_products', true );\n }\n\n return $query_args;\n } );\n}\n</code></pre>\n\n<p>Next we need to remove the default <code>loop_product_thumbnail</code> and replace it with our custom one. We test to ensure <code>realted_products</code> queryvar is set and <code>TRUE</code> before we serve our new image, otherwise serve the default image.</p>\n\n<pre><code>remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );\nadd_action( 'woocommerce_before_shop_loop_item_title',\n function() {\n $related = get_query_var( 'related_products' );\n if( TRUE == $related ) {\n echo woocommerce_get_product_thumbnail( 'related-thumb', 274, 274 ); // Our new image size\n } else {\n echo woocommerce_get_product_thumbnail(); // Default Image Size\n }\n },\n 10\n);\n</code></pre>\n\n<hr>\n\n<p><strong>CSS</strong></p>\n\n<p>WooCommerce uses <code>width: 100%; height: auto;</code> on <em>all</em> their images. You could change this to <code>max-width: 100%; width: auto; height: auto;</code> and play around with the margins / number of columns to get the desired look.</p>\n\n<p><strong>Change the initial image sizes</strong></p>\n\n<p>You can change the actual image sizes WooCommerce uses by following the steps below:</p>\n\n<ul>\n<li>Log into WordPress</li>\n<li>Navigate to <code>WooCommerce -&gt; Products Tab -&gt; Display ( Sub-tab )</code></li>\n<li>Toward the bottom you can set the image sizes for:\n<ul>\n<li>Catalog Images</li>\n<li>Single Product Image</li>\n<li>Product Thumbnails</li>\n</ul></li>\n<li>Finally, you can install <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow\">Regenerate Thumbnails</a> to get the changed sizes.</li>\n</ul>\n\n<hr>\n\n<p>Another method is to have these sizes on install:</p>\n\n<pre><code>function yourtheme_woocommerce_image_dimensions() {\n global $pagenow;\n\n if ( ! isset( $_GET['activated'] ) || $pagenow != 'themes.php' ) {\n return;\n }\n\n $catalog = array(\n 'width' =&gt; '400', // px\n 'height' =&gt; '400', // px\n 'crop' =&gt; 1 // true\n );\n\n $single = array(\n 'width' =&gt; '600', // px\n 'height' =&gt; '600', // px\n 'crop' =&gt; 1 // true\n );\n\n $thumbnail = array(\n 'width' =&gt; '120', // px\n 'height' =&gt; '120', // px\n 'crop' =&gt; 0 // false\n );\n\n // Image sizes\n update_option( 'shop_catalog_image_size', $catalog ); // Product category thumbs\n update_option( 'shop_single_image_size', $single ); // Single product image\n update_option( 'shop_thumbnail_image_size', $thumbnail ); // Image gallery thumbs\n}\n\nadd_action( 'after_switch_theme', 'yourtheme_woocommerce_image_dimensions', 1 );\n</code></pre>\n\n<p>WooCommerce Reference Links:</p>\n\n<ul>\n<li><a href=\"http://docs.woothemes.com/document/using-the-appropriate-product-image-dimensions/\" rel=\"nofollow\">Using appropriate image dimensions to avoid distortion / pixellation</a></li>\n<li><a href=\"http://docs.woothemes.com/document/set-woocommerce-image-dimensions-upon-theme-activation/\" rel=\"nofollow\">Set WooCommerce image dimensions upon theme activation</a></li>\n<li><a href=\"http://docs.woothemes.com/wc-apidocs/function-woocommerce_get_product_thumbnail.html\" rel=\"nofollow\"><code>woocommerce_get_product_thumbnail</code> Function</a></li>\n</ul>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186366", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71669/" ]
Woocommerce has three built in image sizes. But since there are more than three different container sizes, some images always get stretched or squeezed. Hence image quality and page speed suffer. Woocommerce uses for example the catalogue size for catalogue images and related product images. Wordpress offers an easy method to generate custom image sizes. And i've tried to generate a size for my related products: ``` add_action( 'after_setup_theme', 'jmt_theme_setup' ); function jmt_theme_setup() { add_image_size( 'related-thumb', 274, 274, true ); } ``` Is there a way to plug this size into woocommerce related product images? Thanks for your interest. regards theo
There's a few options you can choose from whenever changing image sizes. Switching out the actual default WooCommerce images is more difficult than a normal WordPress install as they are ingrained with the plugin. --- **Modify Related Product Image Sizes:** I've tested this and it seems to work only on related products ( though I'm sure it could be expanded to other areas ). You may still need to take advantage of [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) to get the correct sizes. We need to put everything into a `wp` filter: ``` function woo_init() { // Below functions go here... } add_action( 'wp', 'woo_init' ); ``` I was able to skip the first portion of this, setting the query var and still have it work but since it uses a generic `content-product.php` template I wouldn't trust it, so we will set a query var ensuring we are only change the image size for related products: ``` if( is_singular( 'product' ) ) { add_filter( 'woocommerce_related_products_args', function( $query_args ) { if( ! empty( $query_args ) ) { set_query_var( 'related_products', true ); } return $query_args; } ); } ``` Next we need to remove the default `loop_product_thumbnail` and replace it with our custom one. We test to ensure `realted_products` queryvar is set and `TRUE` before we serve our new image, otherwise serve the default image. ``` remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 ); add_action( 'woocommerce_before_shop_loop_item_title', function() { $related = get_query_var( 'related_products' ); if( TRUE == $related ) { echo woocommerce_get_product_thumbnail( 'related-thumb', 274, 274 ); // Our new image size } else { echo woocommerce_get_product_thumbnail(); // Default Image Size } }, 10 ); ``` --- **CSS** WooCommerce uses `width: 100%; height: auto;` on *all* their images. You could change this to `max-width: 100%; width: auto; height: auto;` and play around with the margins / number of columns to get the desired look. **Change the initial image sizes** You can change the actual image sizes WooCommerce uses by following the steps below: * Log into WordPress * Navigate to `WooCommerce -> Products Tab -> Display ( Sub-tab )` * Toward the bottom you can set the image sizes for: + Catalog Images + Single Product Image + Product Thumbnails * Finally, you can install [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) to get the changed sizes. --- Another method is to have these sizes on install: ``` function yourtheme_woocommerce_image_dimensions() { global $pagenow; if ( ! isset( $_GET['activated'] ) || $pagenow != 'themes.php' ) { return; } $catalog = array( 'width' => '400', // px 'height' => '400', // px 'crop' => 1 // true ); $single = array( 'width' => '600', // px 'height' => '600', // px 'crop' => 1 // true ); $thumbnail = array( 'width' => '120', // px 'height' => '120', // px 'crop' => 0 // false ); // Image sizes update_option( 'shop_catalog_image_size', $catalog ); // Product category thumbs update_option( 'shop_single_image_size', $single ); // Single product image update_option( 'shop_thumbnail_image_size', $thumbnail ); // Image gallery thumbs } add_action( 'after_switch_theme', 'yourtheme_woocommerce_image_dimensions', 1 ); ``` WooCommerce Reference Links: * [Using appropriate image dimensions to avoid distortion / pixellation](http://docs.woothemes.com/document/using-the-appropriate-product-image-dimensions/) * [Set WooCommerce image dimensions upon theme activation](http://docs.woothemes.com/document/set-woocommerce-image-dimensions-upon-theme-activation/) * [`woocommerce_get_product_thumbnail` Function](http://docs.woothemes.com/wc-apidocs/function-woocommerce_get_product_thumbnail.html)
186,371
<p>I use cloudflare via the cloudflare plugin, have SSL enabled.</p> <p>Enabled ssl within the wp-config.php file:</p> <p><code>define('WP_HOME','https://example.org');</code></p> <p><code>define('WP_SITEURL','https://example.org');</code></p> <p><code>$_SERVER['HTTPS'] = 'on';</code></p> <p>Everything seems to work fine on the main site, but when trying to login to admin I see:</p> <p>You do not have sufficient permissions to access this page.</p> <p>This started after going into general settings and adjusting the 'Home' and 'Site URL' options.</p> <p>Following guides, I am able to get the page to appear (instead of being stuck in an infinite redirection loop).</p> <p>I'm not sure what else to change here, as I've just lost permissions out right after switching to https everywhere.</p>
[ { "answer_id": 186372, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 2, "selected": true, "text": "<p>You need to forward the http:// to https:// to avoid infinite loop.</p>\n\n<pre><code>if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')\n $_SERVER['HTTPS']='on';\n</code></pre>\n" }, { "answer_id": 186380, "author": "Derple Gerbensterp", "author_id": 71668, "author_profile": "https://wordpress.stackexchange.com/users/71668", "pm_score": 2, "selected": false, "text": "<p>The fellow above was correct, however the string MUST be above: </p>\n\n<p><code>require_once(ABSPATH . 'wp-settings.php');</code></p>\n\n<p>This is located within wp-config.php :)</p>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186371", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71668/" ]
I use cloudflare via the cloudflare plugin, have SSL enabled. Enabled ssl within the wp-config.php file: `define('WP_HOME','https://example.org');` `define('WP_SITEURL','https://example.org');` `$_SERVER['HTTPS'] = 'on';` Everything seems to work fine on the main site, but when trying to login to admin I see: You do not have sufficient permissions to access this page. This started after going into general settings and adjusting the 'Home' and 'Site URL' options. Following guides, I am able to get the page to appear (instead of being stuck in an infinite redirection loop). I'm not sure what else to change here, as I've just lost permissions out right after switching to https everywhere.
You need to forward the http:// to https:// to avoid infinite loop. ``` if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') $_SERVER['HTTPS']='on'; ```
186,379
<p>I created a custom key and wanted to store multiple values in the key with an array in my plugin using a drop down box, however, I printed out the array and came back out with this value...</p> <pre><code>Array ( [0] =&gt; a:2:{i:0;s:2:"75";i:1;s:2:"68";} ) </code></pre> <p>My thinking was that it would just add another value <code>[1] =&gt; 'content', [2] =&gt; 'lkajsdf'</code>. That is how I wanted it to happen, but instead I get the result above. It is storing the two ID values that I selected <code>75</code> and <code>68</code>.</p> <p>So, what does that result mean?</p>
[ { "answer_id": 186381, "author": "lampyridae", "author_id": 29163, "author_profile": "https://wordpress.stackexchange.com/users/29163", "pm_score": 0, "selected": false, "text": "<p>It seems like the your multiple values were simply serialized by PHP's <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow\"><code>serialize()</code> function</a>.</p>\n\n<p>You can unserialize it with <a href=\"http://php.net/manual/en/function.unserialize.php\" rel=\"nofollow\"><code>unserialize()</code></a>.</p>\n" }, { "answer_id": 186382, "author": "m4n0", "author_id": 70936, "author_profile": "https://wordpress.stackexchange.com/users/70936", "pm_score": 0, "selected": false, "text": "<p>After unserializing the result is:</p>\n\n<pre><code>Array\n(\n [0] =&gt; 75\n [1] =&gt; 68\n)\n</code></pre>\n\n<p>You can find the format of PHP serialized array here: <a href=\"https://stackoverflow.com/questions/14297926/structure-of-a-serialized-php-string\">Serialized PHP string</a></p>\n\n<p><code>a:2</code> is object array here\n<code>'s':&lt;i&gt;</code> is the string where i is the length of string</p>\n" }, { "answer_id": 186383, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 3, "selected": true, "text": "<p>You're looking at a <a href=\"https://stackoverflow.com/questions/8641889/how-to-use-php-serialize-and-unserialize\">serialized representation</a> of the array <code>Array( '75', '68' )</code>. Serialization is the process by which PHP stores a data object as a string, much like the manner in which JSON is a string representation of a Javascript object. PHP data structures may be converted into a serialized format via PHP's <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow noreferrer\"><code>serialize()</code></a>, and back again using <a href=\"http://php.net/manual/en/function.unserialize.php\" rel=\"nofollow noreferrer\"><code>unserialize()</code></a>.</p>\n\n<p>WordPress also provides functions which perform the necessary action only when needed in order to prevent accidental double-serialization or unserialization: <a href=\"https://codex.wordpress.org/Function_Reference/maybe_serialize\" rel=\"nofollow noreferrer\"><code>maybe_serialize()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/maybe_unserialize\" rel=\"nofollow noreferrer\"><code>maybe_unserialize()</code></a>. You can also check yourself with WordPress' <a href=\"https://codex.wordpress.org/Function_Reference/is_serialized\" rel=\"nofollow noreferrer\"><code>is_serialized()</code></a>.</p>\n\n<p>From the comments on PHP's <code>serialize()</code>, the anatomy of a serialized data object is as follows:</p>\n\n<blockquote>\n <p>String <code>s:size:value;</code></p>\n \n <p>Integer <code>i:value;</code></p>\n \n <p>Boolean <code>b:value;</code> (does not store <code>\"true\"</code> or <code>\"false\"</code>, does store <code>1</code> or\n <code>0</code>)</p>\n \n <p>Null <code>N;</code></p>\n \n <p>Array <code>a:size:{key definition;value definition;(repeated per element)}</code></p>\n \n <p>Object <code>O:strlen(object name):object name:object</code></p>\n \n <p>size <code>s:strlen(property name):property name:property definition;(repeated per property)</code></p>\n \n <p>String values are always in double quotes.</p>\n \n <p>Array keys are always integers or strings; using other types as keys produces undesirable results:</p>\n \n <ul>\n <li><code>null =&gt; 'value'</code> equates to <code>'s:0:\"\";s:5:\"value\";'</code></li>\n <li><code>true =&gt; 'value'</code> equates to <code>'i:1;s:5:\"value\";'</code></li>\n <li><code>false =&gt; 'value'</code> equates to <code>'i:0;s:5:\"value\";'</code></li>\n <li><code>array(whatever the contents) =&gt; 'value'</code> equates to an \"illegal offset type\" warning because you can't use an array as a key; however, if you use a variable containing an array as a key, it will equate to <code>'s:5:\"Array\";s:5:\"value\";'</code>, and attempting to use an object as a key will result in the same behavior as using an array will.</li>\n </ul>\n</blockquote>\n\n<p>Therefore, we can interpret your particular serialized array <code>a:2:{i:0;s:2:\"75\";i:1;s:2:\"68\";}</code> as such:</p>\n\n<ul>\n<li><code>a:2:{</code> an array of length 2, containing:\n\n<ul>\n<li><code>i:0;</code> at the integer key <code>0</code> (i.e. index <code>0</code>):\n\n<ul>\n<li><code>s:2:\"75\";</code> a string of length 2 with the value \"75\"</li>\n</ul></li>\n<li><code>i:1;</code> at the integer key <code>1</code> (i.e. index <code>1</code>):\n\n<ul>\n<li><code>s:2:\"68\"</code> a string of length 2 with the value \"68\"</li>\n</ul></li>\n</ul></li>\n<li><code>}</code> end of the array</li>\n</ul>\n\n<p>To alternately reflect the values of your items <code>'content'</code> and <code>'lkajsdf'</code> rather than their numerical identifiers, then, the array <code>Array( 'content', 'lkajsdf' )</code> would be serialized as</p>\n\n<p><code>a:2:{i:0;s:7:\"content\";i:1;s:7:\"lkajsdf\";}</code></p>\n\n<p>Knowing this can come in handy if you ever need to alter some of WordPress's settings, or selectively activate/deactivate specific plugins directly from the database.</p>\n" } ]
2015/05/05
[ "https://wordpress.stackexchange.com/questions/186379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71631/" ]
I created a custom key and wanted to store multiple values in the key with an array in my plugin using a drop down box, however, I printed out the array and came back out with this value... ``` Array ( [0] => a:2:{i:0;s:2:"75";i:1;s:2:"68";} ) ``` My thinking was that it would just add another value `[1] => 'content', [2] => 'lkajsdf'`. That is how I wanted it to happen, but instead I get the result above. It is storing the two ID values that I selected `75` and `68`. So, what does that result mean?
You're looking at a [serialized representation](https://stackoverflow.com/questions/8641889/how-to-use-php-serialize-and-unserialize) of the array `Array( '75', '68' )`. Serialization is the process by which PHP stores a data object as a string, much like the manner in which JSON is a string representation of a Javascript object. PHP data structures may be converted into a serialized format via PHP's [`serialize()`](http://php.net/manual/en/function.serialize.php), and back again using [`unserialize()`](http://php.net/manual/en/function.unserialize.php). WordPress also provides functions which perform the necessary action only when needed in order to prevent accidental double-serialization or unserialization: [`maybe_serialize()`](https://codex.wordpress.org/Function_Reference/maybe_serialize) and [`maybe_unserialize()`](https://codex.wordpress.org/Function_Reference/maybe_unserialize). You can also check yourself with WordPress' [`is_serialized()`](https://codex.wordpress.org/Function_Reference/is_serialized). From the comments on PHP's `serialize()`, the anatomy of a serialized data object is as follows: > > String `s:size:value;` > > > Integer `i:value;` > > > Boolean `b:value;` (does not store `"true"` or `"false"`, does store `1` or > `0`) > > > Null `N;` > > > Array `a:size:{key definition;value definition;(repeated per element)}` > > > Object `O:strlen(object name):object name:object` > > > size `s:strlen(property name):property name:property definition;(repeated per property)` > > > String values are always in double quotes. > > > Array keys are always integers or strings; using other types as keys produces undesirable results: > > > * `null => 'value'` equates to `'s:0:"";s:5:"value";'` > * `true => 'value'` equates to `'i:1;s:5:"value";'` > * `false => 'value'` equates to `'i:0;s:5:"value";'` > * `array(whatever the contents) => 'value'` equates to an "illegal offset type" warning because you can't use an array as a key; however, if you use a variable containing an array as a key, it will equate to `'s:5:"Array";s:5:"value";'`, and attempting to use an object as a key will result in the same behavior as using an array will. > > > Therefore, we can interpret your particular serialized array `a:2:{i:0;s:2:"75";i:1;s:2:"68";}` as such: * `a:2:{` an array of length 2, containing: + `i:0;` at the integer key `0` (i.e. index `0`): - `s:2:"75";` a string of length 2 with the value "75" + `i:1;` at the integer key `1` (i.e. index `1`): - `s:2:"68"` a string of length 2 with the value "68" * `}` end of the array To alternately reflect the values of your items `'content'` and `'lkajsdf'` rather than their numerical identifiers, then, the array `Array( 'content', 'lkajsdf' )` would be serialized as `a:2:{i:0;s:7:"content";i:1;s:7:"lkajsdf";}` Knowing this can come in handy if you ever need to alter some of WordPress's settings, or selectively activate/deactivate specific plugins directly from the database.
187,413
<p>I have written a small plugin where i have loaded following scripts</p> <pre><code>wp_enqueue_script('jquery', plugins_url('/js/jquery.min.js', __FILE__),'','1.7',true); wp_enqueue_script('new-cycle', plugins_url('/js/cycle.js', __FILE__),array( 'jquery' ),'1.0',true); wp_enqueue_script('new-jcarousellite', plugins_url('/js/jcarousellite.js', __FILE__),array( 'jquery' ),'1.0',true); wp_enqueue_script('new-fancybox', plugins_url('/js/fancybox.js', __FILE__),array( 'jquery' ),'1.0',true); </code></pre> <p>and i also have a javascript code to call cycle and fancybox functions ( with parameters/options loaded from options and post_meta tables )</p> <pre><code>function front_js(){ ?&gt; &lt;script&gt; $(document).ready(function(){ $(".video-popup").fancybox(); $(".video_msgs").cycle({speed:'&lt;?php echo get_option("cycle_speed");?&gt;'}); }); &lt;/script&gt; &lt;?php } </code></pre> <p>this code is added to footer by using <code>add_action('wp_footer', 'front_js');</code></p> <p>Now my javascript code is loaded before all the scripts required like</p> <pre><code>&lt;script&gt; $(document).ready(function(){ $(".video-popup").fancybox(); $(".video_msgs").cycle(); }); &lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/twentyfifteen/js/functions.js?ver=20141212'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/cycle.js?ver=1.0'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/jcarousellite.js?ver=1.0'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/fancybox.js?ver=1.0'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/counter.js?ver=1.0'&gt;&lt;/script&gt; </code></pre> <p>and giving error <code>$('...').fancybox()</code> not a function</p> <p>I think its because the code is loaded before fancybox.js file where this function is written. I tried to print_scripts functions but its recommended to not to use this and <code>wp_enqueue_script</code> only works with files not with custom javascript code.</p> <p>Is there any method to load my custom code after required files loaded or any other way to resolve this type of issue.</p> <p>It works if I load all the files in header but then it increases page load time that is also not a good approach.</p>
[ { "answer_id": 187416, "author": "Abhishek Deshpande", "author_id": 45590, "author_profile": "https://wordpress.stackexchange.com/users/45590", "pm_score": 0, "selected": false, "text": "<p>Instead of putting the code in function and hooking it to <code>wp_footer</code>.</p>\n\n<p>You can have another JS file stored in your plugin folder and enqueued it like other scripts you enqueued. </p>\n\n<p>OR </p>\n\n<pre><code>&lt;?php\nfunction front_js() {\n if ( wp_script_is( 'jquery', 'done' ) ) {\n?&gt;\n&lt;script type=\"text/javascript\"&gt;\n\n$(document).ready(function(){\n $(\".video-popup\").fancybox();\n $(\".video_msgs\").cycle();\n });\n\n&lt;/script&gt;\n&lt;?php\n }\n}\nadd_action( 'wp_footer', 'front_js' );\n?&gt; \n</code></pre>\n" }, { "answer_id": 187417, "author": "Stefan", "author_id": 70492, "author_profile": "https://wordpress.stackexchange.com/users/70492", "pm_score": 3, "selected": true, "text": "<p>Try to add the code to the footer using <code>add_action('wp_footer', 'front_js', 99);</code> where 99 specifies the order in which the functions are executed. Now it should be executed after your scripts are loaded.</p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187413", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35612/" ]
I have written a small plugin where i have loaded following scripts ``` wp_enqueue_script('jquery', plugins_url('/js/jquery.min.js', __FILE__),'','1.7',true); wp_enqueue_script('new-cycle', plugins_url('/js/cycle.js', __FILE__),array( 'jquery' ),'1.0',true); wp_enqueue_script('new-jcarousellite', plugins_url('/js/jcarousellite.js', __FILE__),array( 'jquery' ),'1.0',true); wp_enqueue_script('new-fancybox', plugins_url('/js/fancybox.js', __FILE__),array( 'jquery' ),'1.0',true); ``` and i also have a javascript code to call cycle and fancybox functions ( with parameters/options loaded from options and post\_meta tables ) ``` function front_js(){ ?> <script> $(document).ready(function(){ $(".video-popup").fancybox(); $(".video_msgs").cycle({speed:'<?php echo get_option("cycle_speed");?>'}); }); </script> <?php } ``` this code is added to footer by using `add_action('wp_footer', 'front_js');` Now my javascript code is loaded before all the scripts required like ``` <script> $(document).ready(function(){ $(".video-popup").fancybox(); $(".video_msgs").cycle(); }); </script> <script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/twentyfifteen/js/functions.js?ver=20141212'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/cycle.js?ver=1.0'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/jcarousellite.js?ver=1.0'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/fancybox.js?ver=1.0'></script> <script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/js/counter.js?ver=1.0'></script> ``` and giving error `$('...').fancybox()` not a function I think its because the code is loaded before fancybox.js file where this function is written. I tried to print\_scripts functions but its recommended to not to use this and `wp_enqueue_script` only works with files not with custom javascript code. Is there any method to load my custom code after required files loaded or any other way to resolve this type of issue. It works if I load all the files in header but then it increases page load time that is also not a good approach.
Try to add the code to the footer using `add_action('wp_footer', 'front_js', 99);` where 99 specifies the order in which the functions are executed. Now it should be executed after your scripts are loaded.
187,422
<p>I need to sort and paginate custom taxonomy post types. i have a page where i have next and previous link. on clicking next and previous link next or previous brand(custom taxonomy) should load. I have achieved this so far</p> <pre><code> $terms = get_the_terms( get_the_ID(), 'brand' ); if($terms) { $BrandId=$terms[0]-&gt;term_id; $nextBrandId=$BrandId+1; $prevBranId=$BrandId-1; $next=get_term_by('id', $nextBrandId, 'brand' ); $prev=get_term_by('id', $prevBranId, 'brand' ); //echo '&lt;pre&gt;'; echo $next-&gt;slug; echo $prev-&gt;slug; // echo '&lt;/pre&gt;'; } </code></pre> <p>I am getting next and previous brand slug by id and they are showing randomly (if i talk in alphabetic order).</p> <p>Please tell me how can i show next and previous link that are sorted by alphateicallhy.</p> <p>For eg I have following brands</p> <pre><code>Versace, Valentino, Armani, Rado, CK, Tissot </code></pre> <p>If currently i am at Tissot and click next then i should go to Valentino. If i am at Tissot and click prev then i should go to Rado.</p>
[ { "answer_id": 187432, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>As I stated in comments, you can either use <a href=\"http://php.net/manual/en/function.usort.php\" rel=\"nofollow\"><code>usort()</code></a> to sort the returned array of terms, or you can just use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow\"><code>wp_get_post_terms()</code></a> which is already sorted by default by name in ascending order</p>\n\n<pre><code>$terms = wp_get_post_terms( get_the_ID(), 'brand' );\nvar_dump( $terms );\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Here is an example with <code>usort()</code> and <code>get_the_terms()</code></p>\n\n<pre><code>$terms = get_the_terms( get_the_ID(), 'brand' );\nusort( $terms, function ( $a, $b )\n{\n\n return strcasecmp( $a-&gt;name, $b-&gt;name );\n\n});\n</code></pre>\n" }, { "answer_id": 187536, "author": "WordPress Mechanic", "author_id": 33660, "author_profile": "https://wordpress.stackexchange.com/users/33660", "pm_score": 0, "selected": false, "text": "<p>I was trying the same thing to achieve this but finally i found a better solution <a href=\"https://wordpress.org/plugins/alphabetic-pagination/\" rel=\"nofollow\">here</a>. It works with regular taxonomies (categories) and also work with custom taxonomies. You should check its code inside or can use it as it is if the requirements are the same.</p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187422", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71641/" ]
I need to sort and paginate custom taxonomy post types. i have a page where i have next and previous link. on clicking next and previous link next or previous brand(custom taxonomy) should load. I have achieved this so far ``` $terms = get_the_terms( get_the_ID(), 'brand' ); if($terms) { $BrandId=$terms[0]->term_id; $nextBrandId=$BrandId+1; $prevBranId=$BrandId-1; $next=get_term_by('id', $nextBrandId, 'brand' ); $prev=get_term_by('id', $prevBranId, 'brand' ); //echo '<pre>'; echo $next->slug; echo $prev->slug; // echo '</pre>'; } ``` I am getting next and previous brand slug by id and they are showing randomly (if i talk in alphabetic order). Please tell me how can i show next and previous link that are sorted by alphateicallhy. For eg I have following brands ``` Versace, Valentino, Armani, Rado, CK, Tissot ``` If currently i am at Tissot and click next then i should go to Valentino. If i am at Tissot and click prev then i should go to Rado.
As I stated in comments, you can either use [`usort()`](http://php.net/manual/en/function.usort.php) to sort the returned array of terms, or you can just use [`wp_get_post_terms()`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms) which is already sorted by default by name in ascending order ``` $terms = wp_get_post_terms( get_the_ID(), 'brand' ); var_dump( $terms ); ``` EDIT ---- Here is an example with `usort()` and `get_the_terms()` ``` $terms = get_the_terms( get_the_ID(), 'brand' ); usort( $terms, function ( $a, $b ) { return strcasecmp( $a->name, $b->name ); }); ```
187,425
<p>I am working on a plugin. The plugin make custom post type "product". First i use <code>template_redirect</code> action for redirection to single and category pages.</p> <p>Here is my template_redirect code:</p> <pre><code>add_action("template_redirect", 'my_theme_redirect'); function my_theme_redirect() { global $wp; $plugindir = dirname(__FILE__); //A Specific Custom Post Type if ($wp-&gt;query_vars["post_type"] == 'product') { $templatefilename = 'single-product.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } do_theme_redirect($return_template); } if (is_tax('prodcategories')) { $templatefilename = 'taxonomy-prodcategories.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } do_theme_redirect($return_template); } } function do_theme_redirect($url) { global $post, $wp_query; if (have_posts()) { include($url); die(); } else { $wp_query-&gt;is_404 = true; } } </code></pre> <p>Its working perfectly. But now i am trying to use <code>template_include</code> filter but its not working my site goes blank.</p> <p>Here is template_include Code:</p> <pre><code>add_filter("template_include", 'my_theme_redirect'); function my_theme_redirect($templatefilename) { global $wp; $plugindir = dirname(__FILE__); //A Specific Custom Post Type if ($wp-&gt;query_vars["post_type"] == 'product') { $templatefilename = 'single-product.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } return $return_template; } if (is_tax('prodcategories')) { $templatefilename = 'taxonomy-prodcategories.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } return $return_template; } } function do_theme_redirect($url) { global $post, $wp_query; if (have_posts()) { include($url); die(); } else { $wp_query-&gt;is_404 = true; } } </code></pre> <p>Any suggestions where i go wrong</p>
[ { "answer_id": 187442, "author": "deemi-D-nadeem", "author_id": 64316, "author_profile": "https://wordpress.stackexchange.com/users/64316", "pm_score": 3, "selected": true, "text": "<p>Ok i done by my own.</p>\n\n<p>I delete all above code and write this code. It works perfectly for me</p>\n\n<p>Code:</p>\n\n<pre><code>function template_chooser($template){\n global $wp_query;\n $plugindir = dirname(__FILE__);\n\n $post_type = get_query_var('post_type');\n\n if( $post_type == 'product' ){\n return $plugindir . '/themefiles/single-product.php';\n }\n\n if (is_tax('prodcategories')) {\n return $plugindir . '/themefiles/taxonomy-prodcategories.php';\n }\n\n return $template; \n}\nadd_filter('template_include', 'template_chooser');\n</code></pre>\n" }, { "answer_id": 265968, "author": "Saran", "author_id": 25868, "author_profile": "https://wordpress.stackexchange.com/users/25868", "pm_score": 1, "selected": false, "text": "<p>This is more safeway.</p>\n\n<pre><code>add_filter( 'template_include', 'wpse138858_woocommerce_category_archive_template');\n\n\nfunction wpse138858_woocommerce_category_archive_template( $original_template ) {\n // we're loading the template conditionally, \n\n\n global $post;\n if (is_archive() &amp;&amp; get_post_type($post)=='ym_package') {\n // you've to create the template you want to use here first\n return get_template_directory().'/archive-ym_package.php';\n } \n else if(is_archive() &amp;&amp; get_post_type($post)=='ym_place') {\n // you've to create the template you want to use here first\n return get_template_directory().'/archive-ym_place.php';\n } \n\n\n else {\n return $original_template;\n }\n}\n</code></pre>\n\n<p>Please note that put this code in function.php to works fine.</p>\n" }, { "answer_id": 370837, "author": "Ejaz UL Haq", "author_id": 178714, "author_profile": "https://wordpress.stackexchange.com/users/178714", "pm_score": 0, "selected": false, "text": "<p>This work for me, kindly try it, Thanks<br>\nTemplates is loaded into cpt file, which was located at<br>\ncustom_plugin -&gt; app -&gt; cpt -&gt; cpt_article.php<br>\nTemplate is located<br>\ncustom_plugin -&gt; app -&gt; templates</p>\n<pre><code>add_filter( 'template_include', 'load_my_custom_template', 99, 1 );\n function load_custom_templates($template) {\n $post_type = 'article';\n if( is_post_type_archive( $post_type ) &amp;&amp; file_exists( plugin_dir_path(__FILE__) . \n 'templates/archive_help_lessions.php' ) ){\n $template = trailingslashit( plugin_dir_path( __FILE__ ) .'app/templates' ).'archive_articles.php';\n }\n if ( is_singular( $post_type ) ) {\n $template = trailingslashit( plugin_dir_path( __FILE__ ) .'app/templates' ).'single_article.php';\n }\n return $template;\n}\n</code></pre>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187425", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64316/" ]
I am working on a plugin. The plugin make custom post type "product". First i use `template_redirect` action for redirection to single and category pages. Here is my template\_redirect code: ``` add_action("template_redirect", 'my_theme_redirect'); function my_theme_redirect() { global $wp; $plugindir = dirname(__FILE__); //A Specific Custom Post Type if ($wp->query_vars["post_type"] == 'product') { $templatefilename = 'single-product.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } do_theme_redirect($return_template); } if (is_tax('prodcategories')) { $templatefilename = 'taxonomy-prodcategories.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } do_theme_redirect($return_template); } } function do_theme_redirect($url) { global $post, $wp_query; if (have_posts()) { include($url); die(); } else { $wp_query->is_404 = true; } } ``` Its working perfectly. But now i am trying to use `template_include` filter but its not working my site goes blank. Here is template\_include Code: ``` add_filter("template_include", 'my_theme_redirect'); function my_theme_redirect($templatefilename) { global $wp; $plugindir = dirname(__FILE__); //A Specific Custom Post Type if ($wp->query_vars["post_type"] == 'product') { $templatefilename = 'single-product.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } return $return_template; } if (is_tax('prodcategories')) { $templatefilename = 'taxonomy-prodcategories.php'; if (file_exists(TEMPLATEPATH . '/' . $templatefilename)) { $return_template = TEMPLATEPATH . '/' . $templatefilename; } else { $return_template = $plugindir . '/themefiles/' . $templatefilename; } return $return_template; } } function do_theme_redirect($url) { global $post, $wp_query; if (have_posts()) { include($url); die(); } else { $wp_query->is_404 = true; } } ``` Any suggestions where i go wrong
Ok i done by my own. I delete all above code and write this code. It works perfectly for me Code: ``` function template_chooser($template){ global $wp_query; $plugindir = dirname(__FILE__); $post_type = get_query_var('post_type'); if( $post_type == 'product' ){ return $plugindir . '/themefiles/single-product.php'; } if (is_tax('prodcategories')) { return $plugindir . '/themefiles/taxonomy-prodcategories.php'; } return $template; } add_filter('template_include', 'template_chooser'); ```
187,443
<p>I have two categories</p> <ul> <li>Category1 (ID = 1)</li> <li>Category2 (ID = 2)</li> </ul> <p>I want to display posts Which are in Category2 and in (Category1 + Category2).</p> <p>If a post is only in Category1 then it should not display.</p> <p>I have used the following code.</p> <pre><code>'category__in' =&gt; array(2) </code></pre> <p>It works but I think it is not the correct way. As if in the future if I add a new category then I will have to add its id here in the code to display the post which also in that new category.</p> <p>Is there any proper way to exclude only Category1 posts if post in only in Category1?</p>
[ { "answer_id": 187449, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>This is very unusual case, and the only solution I can think of here is to get an array of category ids to include into <code>category__in</code> in order to skip posts that are <strong>only</strong> assigned to category <code>1</code></p>\n\n<p>In order to achieve this, we must</p>\n\n<ul>\n<li><p>use <a href=\"https://codex.wordpress.org/Function_Reference/get_terms\" rel=\"nofollow\"><code>get_terms()</code></a> to get all the categories. We will use the <code>exclude</code> parameter to exclude category <code>1</code> from that list. We will also set the <code>fields</code> parameter to <code>ids</code> in order to get an array of category ids</p></li>\n<li><p>pass the array from the result from <code>get_terms()</code> to <code>category__in</code></p></li>\n</ul>\n\n<p>Example</p>\n\n<pre><code>$cat_ids = get_terms( 'category', array( 'fields' =&gt; 'ids', 'exclude' =&gt; 1 ) );\n</code></pre>\n\n<p>and then use it as follow</p>\n\n<pre><code>'category__in' =&gt; $cat_ids,\n</code></pre>\n\n<p>Just a note, you would need to check if you actually have categories returned by <code>get_terms()</code> and that no error is returned before you run your query. You don't want to pass an empty array or error to <code>category__in</code></p>\n\n<h2>EDIT</h2>\n\n<p>I have scrapped the <code>get_categories</code> idea and went with <code>get_terms()</code> as <code>get_terms</code> is used by <code>get_categories</code> and we can also set <code>get_terms()</code> to only return the category ids, and that is exactly all that is needed. </p>\n\n<p>The original post is updated to reflect the changes</p>\n" }, { "answer_id": 187456, "author": "omxv", "author_id": 55070, "author_profile": "https://wordpress.stackexchange.com/users/55070", "pm_score": 0, "selected": false, "text": "<p>I am only guessing, but sollution must be similar to </p>\n\n<pre><code>$args = array(\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'id',\n 'terms' =&gt; array(1, 2),\n 'operator' =&gt; 'AND'\n )\n )\n);\n$results = new WP_Query( $args );\n</code></pre>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187443", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11985/" ]
I have two categories * Category1 (ID = 1) * Category2 (ID = 2) I want to display posts Which are in Category2 and in (Category1 + Category2). If a post is only in Category1 then it should not display. I have used the following code. ``` 'category__in' => array(2) ``` It works but I think it is not the correct way. As if in the future if I add a new category then I will have to add its id here in the code to display the post which also in that new category. Is there any proper way to exclude only Category1 posts if post in only in Category1?
This is very unusual case, and the only solution I can think of here is to get an array of category ids to include into `category__in` in order to skip posts that are **only** assigned to category `1` In order to achieve this, we must * use [`get_terms()`](https://codex.wordpress.org/Function_Reference/get_terms) to get all the categories. We will use the `exclude` parameter to exclude category `1` from that list. We will also set the `fields` parameter to `ids` in order to get an array of category ids * pass the array from the result from `get_terms()` to `category__in` Example ``` $cat_ids = get_terms( 'category', array( 'fields' => 'ids', 'exclude' => 1 ) ); ``` and then use it as follow ``` 'category__in' => $cat_ids, ``` Just a note, you would need to check if you actually have categories returned by `get_terms()` and that no error is returned before you run your query. You don't want to pass an empty array or error to `category__in` EDIT ---- I have scrapped the `get_categories` idea and went with `get_terms()` as `get_terms` is used by `get_categories` and we can also set `get_terms()` to only return the category ids, and that is exactly all that is needed. The original post is updated to reflect the changes
187,446
<p>My theme calls the update_meta_cache() function 58 times per page! This function appears to run the following query based on the post in question:</p> <pre><code>SELECT post_id, meta_key, meta_value -&gt; FROM wp_postmeta -&gt; WHERE post_id IN (81649) -&gt; ORDER BY meta_id ASC -&gt; ; </code></pre> <p>The vast majority of the meta_keys (and corresponding values) returned are not necessary for the page in question (e.g. yoast_wpseo_title, _edit_last, _edit_lock are not needed for the homepage loop). </p> <p>Is there a way to reduce or prevent calling of the update_meta_cache? Perhaps a way to include in a function on the pre_get_posts hook?</p>
[ { "answer_id": 190047, "author": "Anh Tran", "author_id": 2051, "author_profile": "https://wordpress.stackexchange.com/users/2051", "pm_score": 2, "selected": false, "text": "<p>Whenever you use the function <code>get_post_meta()</code>, the above query will be performed to get <em>all</em> post meta and store in the cache. The more posts you query, the more queries are made.</p>\n\n<p>To reduce the number of queries, we should <strong>pre-cache all meta values of all posts</strong> in the query before calling <code>get_post_meta</code>.</p>\n\n<p>This is the sample code taken from <a href=\"http://hitchhackerguide.com/2011/11/01/reducing-postmeta-queries-with-update_meta_cache/\" rel=\"nofollow\">a tutorial</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'posts_results', 'cache_meta_data', 9999, 2 );\nfunction cache_meta_data( $posts, $object ) {\n $posts_to_cache = array();\n // this usually makes only sense when we have a bunch of posts\n if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) &lt; 3 )\n return $posts;\n\n foreach( $posts as $post ) {\n if ( isset( $post-&gt;ID ) &amp;&amp; isset( $post-&gt;post_type ) ) {\n $posts_to_cache[$post-&gt;ID] = 1;\n }\n }\n\n if ( empty( $posts_to_cache ) )\n return $posts;\n\n update_meta_cache( 'post', array_keys( $posts_to_cache ) );\n unset( $posts_to_cache );\n\n return $posts;\n}\n</code></pre>\n" }, { "answer_id": 395481, "author": "plong0", "author_id": 192082, "author_profile": "https://wordpress.stackexchange.com/users/192082", "pm_score": 0, "selected": false, "text": "<p>For a <code>WP_Query</code>, caching can be disabled by setting certain <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#caching-parameters\" rel=\"nofollow noreferrer\">caching parameters</a> to <code>false</code>.</p>\n<p>Similarly for <code>WP_Term_Query</code>, it can be disabled by including <code>update_term_meta_cache =&gt; false</code> in the query args.</p>\n<p>Additionally, the filter <a href=\"https://developer.wordpress.org/reference/hooks/update_meta_type_metadata_cache/\" rel=\"nofollow noreferrer\">update_{$meta_type}_metadata_cache</a> can be used to disable metadata caching for all queries on the object type. (ex. <code>update_post_metadata_cache</code>, <code>update_term_metadata_cache</code>, etc)</p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187446", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17938/" ]
My theme calls the update\_meta\_cache() function 58 times per page! This function appears to run the following query based on the post in question: ``` SELECT post_id, meta_key, meta_value -> FROM wp_postmeta -> WHERE post_id IN (81649) -> ORDER BY meta_id ASC -> ; ``` The vast majority of the meta\_keys (and corresponding values) returned are not necessary for the page in question (e.g. yoast\_wpseo\_title, \_edit\_last, \_edit\_lock are not needed for the homepage loop). Is there a way to reduce or prevent calling of the update\_meta\_cache? Perhaps a way to include in a function on the pre\_get\_posts hook?
Whenever you use the function `get_post_meta()`, the above query will be performed to get *all* post meta and store in the cache. The more posts you query, the more queries are made. To reduce the number of queries, we should **pre-cache all meta values of all posts** in the query before calling `get_post_meta`. This is the sample code taken from [a tutorial](http://hitchhackerguide.com/2011/11/01/reducing-postmeta-queries-with-update_meta_cache/): ```php add_filter( 'posts_results', 'cache_meta_data', 9999, 2 ); function cache_meta_data( $posts, $object ) { $posts_to_cache = array(); // this usually makes only sense when we have a bunch of posts if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) < 3 ) return $posts; foreach( $posts as $post ) { if ( isset( $post->ID ) && isset( $post->post_type ) ) { $posts_to_cache[$post->ID] = 1; } } if ( empty( $posts_to_cache ) ) return $posts; update_meta_cache( 'post', array_keys( $posts_to_cache ) ); unset( $posts_to_cache ); return $posts; } ```
187,475
<p>My individual WP site is installed in a sub-directory (e.g., example.com/wordpress) and I would like visitors to be able to view it from BOTH the root directory (example.com) AND the sub-directory (example.com/wordpress). I followed the instructions on <a href="https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory#Using_a_pre-existing_subdirectory_install" rel="nofollow">Codex</a> and now the root works, but the sub-directory returns a 404 error. Is it possible to have both URLs return the full site?</p>
[ { "answer_id": 190047, "author": "Anh Tran", "author_id": 2051, "author_profile": "https://wordpress.stackexchange.com/users/2051", "pm_score": 2, "selected": false, "text": "<p>Whenever you use the function <code>get_post_meta()</code>, the above query will be performed to get <em>all</em> post meta and store in the cache. The more posts you query, the more queries are made.</p>\n\n<p>To reduce the number of queries, we should <strong>pre-cache all meta values of all posts</strong> in the query before calling <code>get_post_meta</code>.</p>\n\n<p>This is the sample code taken from <a href=\"http://hitchhackerguide.com/2011/11/01/reducing-postmeta-queries-with-update_meta_cache/\" rel=\"nofollow\">a tutorial</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'posts_results', 'cache_meta_data', 9999, 2 );\nfunction cache_meta_data( $posts, $object ) {\n $posts_to_cache = array();\n // this usually makes only sense when we have a bunch of posts\n if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) &lt; 3 )\n return $posts;\n\n foreach( $posts as $post ) {\n if ( isset( $post-&gt;ID ) &amp;&amp; isset( $post-&gt;post_type ) ) {\n $posts_to_cache[$post-&gt;ID] = 1;\n }\n }\n\n if ( empty( $posts_to_cache ) )\n return $posts;\n\n update_meta_cache( 'post', array_keys( $posts_to_cache ) );\n unset( $posts_to_cache );\n\n return $posts;\n}\n</code></pre>\n" }, { "answer_id": 395481, "author": "plong0", "author_id": 192082, "author_profile": "https://wordpress.stackexchange.com/users/192082", "pm_score": 0, "selected": false, "text": "<p>For a <code>WP_Query</code>, caching can be disabled by setting certain <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#caching-parameters\" rel=\"nofollow noreferrer\">caching parameters</a> to <code>false</code>.</p>\n<p>Similarly for <code>WP_Term_Query</code>, it can be disabled by including <code>update_term_meta_cache =&gt; false</code> in the query args.</p>\n<p>Additionally, the filter <a href=\"https://developer.wordpress.org/reference/hooks/update_meta_type_metadata_cache/\" rel=\"nofollow noreferrer\">update_{$meta_type}_metadata_cache</a> can be used to disable metadata caching for all queries on the object type. (ex. <code>update_post_metadata_cache</code>, <code>update_term_metadata_cache</code>, etc)</p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187475", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44332/" ]
My individual WP site is installed in a sub-directory (e.g., example.com/wordpress) and I would like visitors to be able to view it from BOTH the root directory (example.com) AND the sub-directory (example.com/wordpress). I followed the instructions on [Codex](https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory#Using_a_pre-existing_subdirectory_install) and now the root works, but the sub-directory returns a 404 error. Is it possible to have both URLs return the full site?
Whenever you use the function `get_post_meta()`, the above query will be performed to get *all* post meta and store in the cache. The more posts you query, the more queries are made. To reduce the number of queries, we should **pre-cache all meta values of all posts** in the query before calling `get_post_meta`. This is the sample code taken from [a tutorial](http://hitchhackerguide.com/2011/11/01/reducing-postmeta-queries-with-update_meta_cache/): ```php add_filter( 'posts_results', 'cache_meta_data', 9999, 2 ); function cache_meta_data( $posts, $object ) { $posts_to_cache = array(); // this usually makes only sense when we have a bunch of posts if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) < 3 ) return $posts; foreach( $posts as $post ) { if ( isset( $post->ID ) && isset( $post->post_type ) ) { $posts_to_cache[$post->ID] = 1; } } if ( empty( $posts_to_cache ) ) return $posts; update_meta_cache( 'post', array_keys( $posts_to_cache ) ); unset( $posts_to_cache ); return $posts; } ```
187,477
<p>I read <a href="http://codex.wordpress.org/The_Loop#Multiple_Loops_in_Action" rel="nofollow">this article</a> about how to set an offset for one specific category in the loop. I was wondering about if this was possible for more than just one category.</p> <p>My problem with the code suggested in the article linked above is that I am using a single widget to show five posts from a category I can set in the widget options by ID. I cannot wrap my head around how to collect the <code>post_ID</code>s of the posts already looped through.</p> <p><strong>Situation:</strong></p> <p>I am using custom widgets on my blog page to show the 5 latest posts in two specified categories - let's call them categoryA and categoryB. </p> <blockquote> <p>Answer to @Pieter Goosen's question in the comments: Yes, I can specify the category by manually entering an ID in the widget settings and it's saved in the DB.</p> </blockquote> <p>Below these widgets the blog page loops through all my posts and shows them.</p> <p><strong>Effect:</strong></p> <p>The main loop on the blog page (the one below the widgets) displays the posts from categoryA and categoryB again. They appear double because the widgets above already looped through the categories A and B.</p> <p><strong>Question:</strong></p> <p>Is it possible to exclude the first five posts from categoryA and categoryB in the main loop? Could it be done with <code>pre_get_posts</code>? Using <code>get_query_var</code>? How?</p> <p><strong>EDIT</strong></p> <p><strong>My own approaches</strong></p> <p><strong>FIRST TRY</strong></p> <p>I modified my widget codes like this:</p> <pre><code>global $do_not_duplicate; while($featured_posts-&gt;have_posts()): $featured_posts-&gt;the_post(); $do_not_duplicate[] = get_the_ID(); </code></pre> <p>As my widgets are being registered in my <code>functions.php</code> file, I added these lines to it:</p> <pre><code>global $do_not_duplicate; $do_not_duplicate = array(); include('widgets/widgets.php'); </code></pre> <p>Finally on the <code>index.php</code>, I added this line to the main loop:</p> <pre><code>if(have_posts()) : global $do_not_duplicate; while(have_posts()): the_post(); if( in_array( $post-&gt;ID, $do_not_duplicate ) ) continue; get_template_part('content'); endwhile; endif; </code></pre> <p><strong>Please note:</strong> This basically works but does not exactly remove the posts from the main query but skip them. This means the default <code>posts_per_page</code> setting won't be fulfilled and this won't work with Jetpack infinite scroll. Also, using globals is not the way to go.</p> <p><strong>SECOND TRY</strong></p> <p>I adapted @birgire suggestion and modified it a little. I thought about using the suggested pre_get_posts filter in combination with a foreach-loop for the categories used by the widgets in order to gather the IDs of the posts queried by them. Here's my snippet:</p> <pre><code>add_action('pre_get_posts', 'modified_mainloop', 10); function modified_mainloop($query) { if(!is_admin() &amp;&amp; $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query()) { $cats_to_exclude = get_categories('include=3,4,9'); foreach($cats_to_exclude as $category) { if($category-&gt;term_id == '9') { $num_posts_to_exclude = 3; } else { $num_posts_to_exclude = 5; } $posts_to_exclude = get_posts(array( 'posts_per_page' =&gt; $num_posts_to_exclude, 'category__in' =&gt; array($category-&gt;term_id), 'fields' =&gt; 'ids' )); } $query-&gt;set('post__not_in', (array) $posts_to_exclude); } } </code></pre> <p><strong>Please note:</strong> Idea is OK, but code does not work.</p>
[ { "answer_id": 190047, "author": "Anh Tran", "author_id": 2051, "author_profile": "https://wordpress.stackexchange.com/users/2051", "pm_score": 2, "selected": false, "text": "<p>Whenever you use the function <code>get_post_meta()</code>, the above query will be performed to get <em>all</em> post meta and store in the cache. The more posts you query, the more queries are made.</p>\n\n<p>To reduce the number of queries, we should <strong>pre-cache all meta values of all posts</strong> in the query before calling <code>get_post_meta</code>.</p>\n\n<p>This is the sample code taken from <a href=\"http://hitchhackerguide.com/2011/11/01/reducing-postmeta-queries-with-update_meta_cache/\" rel=\"nofollow\">a tutorial</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'posts_results', 'cache_meta_data', 9999, 2 );\nfunction cache_meta_data( $posts, $object ) {\n $posts_to_cache = array();\n // this usually makes only sense when we have a bunch of posts\n if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) &lt; 3 )\n return $posts;\n\n foreach( $posts as $post ) {\n if ( isset( $post-&gt;ID ) &amp;&amp; isset( $post-&gt;post_type ) ) {\n $posts_to_cache[$post-&gt;ID] = 1;\n }\n }\n\n if ( empty( $posts_to_cache ) )\n return $posts;\n\n update_meta_cache( 'post', array_keys( $posts_to_cache ) );\n unset( $posts_to_cache );\n\n return $posts;\n}\n</code></pre>\n" }, { "answer_id": 395481, "author": "plong0", "author_id": 192082, "author_profile": "https://wordpress.stackexchange.com/users/192082", "pm_score": 0, "selected": false, "text": "<p>For a <code>WP_Query</code>, caching can be disabled by setting certain <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#caching-parameters\" rel=\"nofollow noreferrer\">caching parameters</a> to <code>false</code>.</p>\n<p>Similarly for <code>WP_Term_Query</code>, it can be disabled by including <code>update_term_meta_cache =&gt; false</code> in the query args.</p>\n<p>Additionally, the filter <a href=\"https://developer.wordpress.org/reference/hooks/update_meta_type_metadata_cache/\" rel=\"nofollow noreferrer\">update_{$meta_type}_metadata_cache</a> can be used to disable metadata caching for all queries on the object type. (ex. <code>update_post_metadata_cache</code>, <code>update_term_metadata_cache</code>, etc)</p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187477", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52621/" ]
I read [this article](http://codex.wordpress.org/The_Loop#Multiple_Loops_in_Action) about how to set an offset for one specific category in the loop. I was wondering about if this was possible for more than just one category. My problem with the code suggested in the article linked above is that I am using a single widget to show five posts from a category I can set in the widget options by ID. I cannot wrap my head around how to collect the `post_ID`s of the posts already looped through. **Situation:** I am using custom widgets on my blog page to show the 5 latest posts in two specified categories - let's call them categoryA and categoryB. > > Answer to @Pieter Goosen's question in the comments: Yes, I can specify the > category by manually entering an ID in the widget settings and it's > saved in the DB. > > > Below these widgets the blog page loops through all my posts and shows them. **Effect:** The main loop on the blog page (the one below the widgets) displays the posts from categoryA and categoryB again. They appear double because the widgets above already looped through the categories A and B. **Question:** Is it possible to exclude the first five posts from categoryA and categoryB in the main loop? Could it be done with `pre_get_posts`? Using `get_query_var`? How? **EDIT** **My own approaches** **FIRST TRY** I modified my widget codes like this: ``` global $do_not_duplicate; while($featured_posts->have_posts()): $featured_posts->the_post(); $do_not_duplicate[] = get_the_ID(); ``` As my widgets are being registered in my `functions.php` file, I added these lines to it: ``` global $do_not_duplicate; $do_not_duplicate = array(); include('widgets/widgets.php'); ``` Finally on the `index.php`, I added this line to the main loop: ``` if(have_posts()) : global $do_not_duplicate; while(have_posts()): the_post(); if( in_array( $post->ID, $do_not_duplicate ) ) continue; get_template_part('content'); endwhile; endif; ``` **Please note:** This basically works but does not exactly remove the posts from the main query but skip them. This means the default `posts_per_page` setting won't be fulfilled and this won't work with Jetpack infinite scroll. Also, using globals is not the way to go. **SECOND TRY** I adapted @birgire suggestion and modified it a little. I thought about using the suggested pre\_get\_posts filter in combination with a foreach-loop for the categories used by the widgets in order to gather the IDs of the posts queried by them. Here's my snippet: ``` add_action('pre_get_posts', 'modified_mainloop', 10); function modified_mainloop($query) { if(!is_admin() && $query->is_home() && $query->is_main_query()) { $cats_to_exclude = get_categories('include=3,4,9'); foreach($cats_to_exclude as $category) { if($category->term_id == '9') { $num_posts_to_exclude = 3; } else { $num_posts_to_exclude = 5; } $posts_to_exclude = get_posts(array( 'posts_per_page' => $num_posts_to_exclude, 'category__in' => array($category->term_id), 'fields' => 'ids' )); } $query->set('post__not_in', (array) $posts_to_exclude); } } ``` **Please note:** Idea is OK, but code does not work.
Whenever you use the function `get_post_meta()`, the above query will be performed to get *all* post meta and store in the cache. The more posts you query, the more queries are made. To reduce the number of queries, we should **pre-cache all meta values of all posts** in the query before calling `get_post_meta`. This is the sample code taken from [a tutorial](http://hitchhackerguide.com/2011/11/01/reducing-postmeta-queries-with-update_meta_cache/): ```php add_filter( 'posts_results', 'cache_meta_data', 9999, 2 ); function cache_meta_data( $posts, $object ) { $posts_to_cache = array(); // this usually makes only sense when we have a bunch of posts if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) < 3 ) return $posts; foreach( $posts as $post ) { if ( isset( $post->ID ) && isset( $post->post_type ) ) { $posts_to_cache[$post->ID] = 1; } } if ( empty( $posts_to_cache ) ) return $posts; update_meta_cache( 'post', array_keys( $posts_to_cache ) ); unset( $posts_to_cache ); return $posts; } ```
187,480
<p>I'm attempting to use a .htaccess file to block access to the wp-admin folder. I've read through the Brute Force Attacks doc (<a href="https://wordpress.org/support/article/brute-force-attacks/" rel="nofollow noreferrer">https://wordpress.org/support/article/brute-force-attacks/</a>) and I've added the block below, using my ip addresses, to the .htaccess file and placed it in the wp-admin folder:</p> <pre><code># Block access to wp-admin. ErrorDocument 401 default order deny,allow allow from x.x.x.x allow from y.y.y.y allow from z.z.z.z deny from all </code></pre> <p>It seems to be working but the error that a user receives is &quot;This webpage has a redirect loop&quot;. Is there a way to send the user to a 404 or another error doc instead of the redirect loop? I'm not really sure how that is occurring since there is nothing else in the .htaccess file.</p> <p>I'm not password protecting the wp-admin folder and adding ErrorDocument 401 default doesn't seem to work either.</p>
[ { "answer_id": 187491, "author": "brandozz", "author_id": 64789, "author_profile": "https://wordpress.stackexchange.com/users/64789", "pm_score": 3, "selected": true, "text": "<p>Placing the htaccess file in the wp-admin directory did not work for me so I went a different route and it seems to be working very well. Below is what I have in my <strong>main</strong> htaccess file:</p>\n\n<pre><code>&lt;files wp-login.php&gt;\n# set up rule order\norder deny,allow\n# default deny\ndeny from all\nallow from x.x.x.x\nallow from y.y.y.y\nallow from z.z.z.z\n&lt;/files&gt;\n\nErrorDocument 401 default\nErrorDocument 403 default\nErrorDocument 404 default\n</code></pre>\n" }, { "answer_id": 202718, "author": "Plastikschnitzer", "author_id": 80295, "author_profile": "https://wordpress.stackexchange.com/users/80295", "pm_score": 1, "selected": false, "text": "<p>You can also block access to wp-admin with htaccess/htpasswd, which will force users to enter an extra name/password before they can access wp-admin. This way, brute force attacks will be blocked on server level, they do not even reach the wordpress login mask. </p>\n\n<p>You have to etit <code>/wp-admin/.htaccess</code></p>\n\n<p>Add the following lines:</p>\n\n<pre><code>AuthType Basic\nAuthName \"restricted area\"\nAuthUserFile /absolute-server-path-to-wp/wp-admin/.htpasswd\nrequire valid-user\n</code></pre>\n\n<p>Please note: You need to insert the absolute server path!\nThere you define the path were the password is stored.</p>\n\n<p>You also need to generate the .htpasswd file. You can use a tool like: <a href=\"http://www.kxs.net/support/htaccess_pw.html\" rel=\"nofollow\">http://www.kxs.net/support/htaccess_pw.html</a></p>\n\n<p>Upload the .htpasswd file to the location defined above in the line AuthUserFile. It should be located above the level which can be accessed by visitors of your site, so if your site is in <code>/httpdocs/wordpress/</code>, you might place it in <code>/httpdocs</code>.</p>\n\n<p>More details about setting it up can be found here: <a href=\"https://wordpress.org/support/topic/password-protect-a-directory-with-htaccess\" rel=\"nofollow\">How to protect a directory with htaccess</a></p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187480", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64789/" ]
I'm attempting to use a .htaccess file to block access to the wp-admin folder. I've read through the Brute Force Attacks doc (<https://wordpress.org/support/article/brute-force-attacks/>) and I've added the block below, using my ip addresses, to the .htaccess file and placed it in the wp-admin folder: ``` # Block access to wp-admin. ErrorDocument 401 default order deny,allow allow from x.x.x.x allow from y.y.y.y allow from z.z.z.z deny from all ``` It seems to be working but the error that a user receives is "This webpage has a redirect loop". Is there a way to send the user to a 404 or another error doc instead of the redirect loop? I'm not really sure how that is occurring since there is nothing else in the .htaccess file. I'm not password protecting the wp-admin folder and adding ErrorDocument 401 default doesn't seem to work either.
Placing the htaccess file in the wp-admin directory did not work for me so I went a different route and it seems to be working very well. Below is what I have in my **main** htaccess file: ``` <files wp-login.php> # set up rule order order deny,allow # default deny deny from all allow from x.x.x.x allow from y.y.y.y allow from z.z.z.z </files> ErrorDocument 401 default ErrorDocument 403 default ErrorDocument 404 default ```
187,487
<p>I would like to know how to do add a logo to my <a href="http://abraham-accountants.co.uk/" rel="nofollow">website</a>, before the site title.</p> <pre><code>&lt;html &lt;?php language_attributes(); ?&gt;&gt; &lt;head&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="profile" href="http://gmpg.org/xfn/11" /&gt; &lt;link rel="pingback" href="&lt;?php bloginfo( 'pingback_url' ); ?&gt;" /&gt; &lt;?php /* Embeds HTML5shiv to support HTML5 elements in older IE versions plus CSS Backgrounds */ ?&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="&lt;?php echo get_template_directory_uri(); ?&gt;/js/html5shiv.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt;&gt; &lt;?php // Get Theme Options from Database $theme_options = smartline_theme_options(); ?&gt; &lt;div id="wrapper" class="hfeed"&gt; &lt;div id="header-wrap"&gt; &lt;?php // Display Top Navigation if ( has_nav_menu( 'secondary' ) ) : ?&gt; &lt;nav id="topnav" class="clearfix" role="navigation"&gt; &lt;h5 id="topnav-icon"&gt;&lt;?php _e('Menu', 'smartline-lite'); ?&gt;&lt;/h5&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'secondary', 'container' =&gt; false, 'menu_id' =&gt; 'topnav-menu', 'fallback_cb' =&gt; '', 'depth' =&gt; 1) ); ?&gt; &lt;/nav&gt; &lt;?php endif; ?&gt; &lt;header id="header" class="clearfix" role="banner"&gt; &lt;div id="logo" class="clearfix"&gt; &lt;?php do_action('smartline_site_title'); ?&gt; &lt;?php // Display Tagline on header if activated if ( isset($theme_options['header_tagline']) and $theme_options['header_tagline'] == true ) : ?&gt; &lt;h2 class="site-description"&gt;&lt;?php echo bloginfo('description'); ?&gt;&lt;/h2&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;div id="header-content" class="clearfix"&gt; &lt;?php get_template_part('inc/header-content'); ?&gt; &lt;/div&gt; &lt;/header&gt; &lt;/div&gt; &lt;div id="navi-wrap"&gt; &lt;nav id="mainnav" class="clearfix" role="navigation"&gt; &lt;h4 id="mainnav-icon"&gt;&lt;?php _e('Menu', 'smartline-lite'); ?&gt;&lt;/h4&gt; &lt;?php // Display Main Navigation wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'container' =&gt; false, 'menu_id' =&gt; 'mainnav-menu', 'echo' =&gt; true, 'fallback_cb' =&gt; 'smartline_default_menu') ); ?&gt; &lt;/nav&gt; &lt;/div&gt; &lt;?php // Display Custom Header Image smartline_display_custom_header(); ?&gt; </code></pre>
[ { "answer_id": 187488, "author": "Interactive", "author_id": 52240, "author_profile": "https://wordpress.stackexchange.com/users/52240", "pm_score": 1, "selected": false, "text": "<p>The title is probably placed within the header.php file. </p>\n\n<p>So openup and find something like:</p>\n\n<pre><code>&lt;h1&gt;&lt;a href=\"&lt;?php bloginfo('url');?&gt;\"&gt;&lt;?php bloginfo('name');?&gt;&lt;/a&gt;&lt;/h1&gt;\n</code></pre>\n\n<p>This is what displays <code>Abraham &amp; Co</code> on your website.</p>\n\n<p>Now first of you need your image uploaded to you images folder in the theme folder.<br>Add the following code BEFORE the code above:</p>\n\n<pre><code>&lt;img src=\"&lt;?php bloginfo('template_directory');?&gt;/images/your-logo.png\"&gt;\n</code></pre>\n\n<p>make sure you change <code>your-logo.png</code> to whatever image file you have uploaded to you images folder.</p>\n\n<p>Optionally you can wrap the image in a div with a class to add some css in your <code>style.css</code> file</p>\n\n<p>-- UPDATE -- <br>\nI have downloaded the theme that you use but indeed this isn't in the <code>header.php</code> file. There is a file called <code>template-tags.php</code>. \nIn this file on rule 17 you find <code>&lt;h1 class=\"site-title\"&gt;&lt;?php bloginfo('name'); ?&gt;&lt;/h1&gt;</code></p>\n\n<p>This is what displays <code>Abraham &amp; Co</code> on your website. But you should first check to add a logo via the admin screen options of you theme because I believe you can just upload an image.</p>\n\n<p>If you can't do the following:\nUpload your image to your images folder in your theme folder.<br>\nReplace:</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo esc_url(home_url('/')); ?&gt;\" title=\"&lt;?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?&gt;\" rel=\"home\"&gt;\n &lt;h1 class=\"site-title\"&gt;&lt;?php bloginfo('name'); ?&gt;&lt;/h1&gt;\n&lt;/a&gt;\n</code></pre>\n\n<p>and replace it with:</p>\n\n<pre><code>&lt;img src=\"&lt;?php bloginfo('template_directory');?&gt;/images/your-logo.png\"&gt;\n&lt;a href=\"&lt;?php echo esc_url(home_url('/')); ?&gt;\" title=\"&lt;?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?&gt;\" rel=\"home\"&gt;\n &lt;h1 class=\"site-title\"&gt;&lt;?php bloginfo('name'); ?&gt;&lt;/h1&gt;\n&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 223122, "author": "Anurag", "author_id": 92034, "author_profile": "https://wordpress.stackexchange.com/users/92034", "pm_score": 0, "selected": false, "text": "<p>Navigate to Smartline Lite: header.php file and change the below given code. let me know if it works ....</p>\n\n<pre><code> &lt;div id=\"logo\" class=\"clearfix\"&gt;\n\n &lt;?php do_action('smartline_site_title'); ?&gt;\n&lt;img src=\"image location\" alt=\"alt title\" height=\"auto\" width=\"auto\"&gt;\n\n &lt;?php // Display Tagline on header if activated\n if ( isset($theme_options['header_tagline']) and $theme_options['header_tagline'] == true ) : ?&gt; \n &lt;h2 class=\"site-description\"&gt;&lt;?php echo bloginfo('description'); ?&gt;&lt;/h2&gt;\n &lt;?php endif; ?&gt;\n\n &lt;/div&gt;\n\n &lt;div id=\"header-content\" class=\"clearfix\"&gt;\n &lt;?php get_template_part('inc/header-content'); ?&gt;\n &lt;/div&gt;\n\n&lt;/header&gt;\n</code></pre>\n" }, { "answer_id": 393629, "author": "MacInnis", "author_id": 210536, "author_profile": "https://wordpress.stackexchange.com/users/210536", "pm_score": 0, "selected": false, "text": "<p>Two Options, either define the url or link your defined custom logo from the theme settings.</p>\n<pre><code>&lt;img src=&quot;&lt;?php bloginfo('template_directory');?&gt;/images/menuLogo.png&quot;&gt;\n</code></pre>\n<pre><code>&lt;?php the_custom_logo(); ?&gt;\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_custom_logo/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_custom_logo/</a>\n<a href=\"https://developer.wordpress.org/reference/functions/bloginfo/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/bloginfo/</a></p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187487", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/72715/" ]
I would like to know how to do add a logo to my [website](http://abraham-accountants.co.uk/), before the site title. ``` <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <?php /* Embeds HTML5shiv to support HTML5 elements in older IE versions plus CSS Backgrounds */ ?> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5shiv.min.js" type="text/javascript"></script> <![endif]--> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <?php // Get Theme Options from Database $theme_options = smartline_theme_options(); ?> <div id="wrapper" class="hfeed"> <div id="header-wrap"> <?php // Display Top Navigation if ( has_nav_menu( 'secondary' ) ) : ?> <nav id="topnav" class="clearfix" role="navigation"> <h5 id="topnav-icon"><?php _e('Menu', 'smartline-lite'); ?></h5> <?php wp_nav_menu( array( 'theme_location' => 'secondary', 'container' => false, 'menu_id' => 'topnav-menu', 'fallback_cb' => '', 'depth' => 1) ); ?> </nav> <?php endif; ?> <header id="header" class="clearfix" role="banner"> <div id="logo" class="clearfix"> <?php do_action('smartline_site_title'); ?> <?php // Display Tagline on header if activated if ( isset($theme_options['header_tagline']) and $theme_options['header_tagline'] == true ) : ?> <h2 class="site-description"><?php echo bloginfo('description'); ?></h2> <?php endif; ?> </div> <div id="header-content" class="clearfix"> <?php get_template_part('inc/header-content'); ?> </div> </header> </div> <div id="navi-wrap"> <nav id="mainnav" class="clearfix" role="navigation"> <h4 id="mainnav-icon"><?php _e('Menu', 'smartline-lite'); ?></h4> <?php // Display Main Navigation wp_nav_menu( array( 'theme_location' => 'primary', 'container' => false, 'menu_id' => 'mainnav-menu', 'echo' => true, 'fallback_cb' => 'smartline_default_menu') ); ?> </nav> </div> <?php // Display Custom Header Image smartline_display_custom_header(); ?> ```
The title is probably placed within the header.php file. So openup and find something like: ``` <h1><a href="<?php bloginfo('url');?>"><?php bloginfo('name');?></a></h1> ``` This is what displays `Abraham & Co` on your website. Now first of you need your image uploaded to you images folder in the theme folder. Add the following code BEFORE the code above: ``` <img src="<?php bloginfo('template_directory');?>/images/your-logo.png"> ``` make sure you change `your-logo.png` to whatever image file you have uploaded to you images folder. Optionally you can wrap the image in a div with a class to add some css in your `style.css` file -- UPDATE -- I have downloaded the theme that you use but indeed this isn't in the `header.php` file. There is a file called `template-tags.php`. In this file on rule 17 you find `<h1 class="site-title"><?php bloginfo('name'); ?></h1>` This is what displays `Abraham & Co` on your website. But you should first check to add a logo via the admin screen options of you theme because I believe you can just upload an image. If you can't do the following: Upload your image to your images folder in your theme folder. Replace: ``` <a href="<?php echo esc_url(home_url('/')); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"> <h1 class="site-title"><?php bloginfo('name'); ?></h1> </a> ``` and replace it with: ``` <img src="<?php bloginfo('template_directory');?>/images/your-logo.png"> <a href="<?php echo esc_url(home_url('/')); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"> <h1 class="site-title"><?php bloginfo('name'); ?></h1> </a> ```
187,494
<p>I am using Visual Composer to add an accordion to my page. Now I need to be able to deep link to arbitrary elements in the accordion. In other words, I need to be able to provide people with links that will open an arbitrary element in the accordion. So, a url like <code>/mypage#tab4</code> might used open the 4th accordion tab. Is it possible to do this?</p> <p>The documentation doesn't mention it. The source code doesn't appear to support it. And, I don't have a support account with WPBakery because I'm not the original developer.</p>
[ { "answer_id": 196705, "author": "gbuckingham89", "author_id": 13207, "author_profile": "https://wordpress.stackexchange.com/users/13207", "pm_score": 3, "selected": true, "text": "<p>After having the same issue, I've come up with a basic solution - hopefully it's not too late for you.</p>\n\n<p>The Visual Composer \"accordion plugin\" seems to be a wrapper around the jQuery UI accordion; so the same methods are available. I've written some basic (room for improvement no doubt) code that checks if there is a hash on the end of the URL, and then match that up to an accordion panel (gets an index number for it), and then open it. It just requires you to add an ID to each of the accordion items in the CMS.</p>\n\n<pre><code>jQuery(window).load(function() {\n if(location.hash) {\n var panelRef = (window.location.hash.substring(1)); \n jQuery(\".wpb_accordion_section\").each(function(index) {\n if(jQuery(this).attr(\"id\") == panelRef) {\n jQuery('.wpb_accordion_wrapper').accordion(\"option\", \"active\", index);\n }\n }); \n }\n});\n</code></pre>\n\n<p>You could modify it to use numbers instead of hard-coded IDs (remember the panels will be 0 indexed though).</p>\n" }, { "answer_id": 317643, "author": "Jason Smith", "author_id": 153015, "author_profile": "https://wordpress.stackexchange.com/users/153015", "pm_score": 0, "selected": false, "text": "<p>I know it's a little late, there is a much easier way to do this. Go to Add Element ID to each tab, if we name it custom1 for instance then if your went to (www.yourdomain.com/#custom1) that will redirect to the certain tab you want. As long as your tabs are on your homepage. </p>\n\n<p>It works on all pages so you can link a tab on home page to redirect to another page with your tabbed content, let's say your About page then your url will look like this (www.yourdomain.com/about/#custom1) for our linked tab we set earlier.</p>\n\n<p>You can get creative a little with the element id for instance custom1-more-info for your doomin would like like this: (www.yourdomain.com/#custom1#more#info) if you notice your dashes (-) are defined as (#) within your linking. </p>\n\n<p>Hope this helps someone, little easier than the above solution. </p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187494", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27667/" ]
I am using Visual Composer to add an accordion to my page. Now I need to be able to deep link to arbitrary elements in the accordion. In other words, I need to be able to provide people with links that will open an arbitrary element in the accordion. So, a url like `/mypage#tab4` might used open the 4th accordion tab. Is it possible to do this? The documentation doesn't mention it. The source code doesn't appear to support it. And, I don't have a support account with WPBakery because I'm not the original developer.
After having the same issue, I've come up with a basic solution - hopefully it's not too late for you. The Visual Composer "accordion plugin" seems to be a wrapper around the jQuery UI accordion; so the same methods are available. I've written some basic (room for improvement no doubt) code that checks if there is a hash on the end of the URL, and then match that up to an accordion panel (gets an index number for it), and then open it. It just requires you to add an ID to each of the accordion items in the CMS. ``` jQuery(window).load(function() { if(location.hash) { var panelRef = (window.location.hash.substring(1)); jQuery(".wpb_accordion_section").each(function(index) { if(jQuery(this).attr("id") == panelRef) { jQuery('.wpb_accordion_wrapper').accordion("option", "active", index); } }); } }); ``` You could modify it to use numbers instead of hard-coded IDs (remember the panels will be 0 indexed though).
187,499
<p>I'm getting started with a project that is making use of Backbone and the WP REST API, but I"m having a little trouble.</p> <p>Using the built in API JS for models and collections allows me to pretty easily update a post title or content. All I have to do is call:</p> <pre><code>this.model.set({title: 'New Title'}); this.model.save(); </code></pre> <p>And everything works really well. But for post meta, there doesn't appear to be an easy way to update an entry to the database. Does anyone know how to go about taking a post model in Backbone, and updating it's meta data?</p>
[ { "answer_id": 196705, "author": "gbuckingham89", "author_id": 13207, "author_profile": "https://wordpress.stackexchange.com/users/13207", "pm_score": 3, "selected": true, "text": "<p>After having the same issue, I've come up with a basic solution - hopefully it's not too late for you.</p>\n\n<p>The Visual Composer \"accordion plugin\" seems to be a wrapper around the jQuery UI accordion; so the same methods are available. I've written some basic (room for improvement no doubt) code that checks if there is a hash on the end of the URL, and then match that up to an accordion panel (gets an index number for it), and then open it. It just requires you to add an ID to each of the accordion items in the CMS.</p>\n\n<pre><code>jQuery(window).load(function() {\n if(location.hash) {\n var panelRef = (window.location.hash.substring(1)); \n jQuery(\".wpb_accordion_section\").each(function(index) {\n if(jQuery(this).attr(\"id\") == panelRef) {\n jQuery('.wpb_accordion_wrapper').accordion(\"option\", \"active\", index);\n }\n }); \n }\n});\n</code></pre>\n\n<p>You could modify it to use numbers instead of hard-coded IDs (remember the panels will be 0 indexed though).</p>\n" }, { "answer_id": 317643, "author": "Jason Smith", "author_id": 153015, "author_profile": "https://wordpress.stackexchange.com/users/153015", "pm_score": 0, "selected": false, "text": "<p>I know it's a little late, there is a much easier way to do this. Go to Add Element ID to each tab, if we name it custom1 for instance then if your went to (www.yourdomain.com/#custom1) that will redirect to the certain tab you want. As long as your tabs are on your homepage. </p>\n\n<p>It works on all pages so you can link a tab on home page to redirect to another page with your tabbed content, let's say your About page then your url will look like this (www.yourdomain.com/about/#custom1) for our linked tab we set earlier.</p>\n\n<p>You can get creative a little with the element id for instance custom1-more-info for your doomin would like like this: (www.yourdomain.com/#custom1#more#info) if you notice your dashes (-) are defined as (#) within your linking. </p>\n\n<p>Hope this helps someone, little easier than the above solution. </p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187499", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/30668/" ]
I'm getting started with a project that is making use of Backbone and the WP REST API, but I"m having a little trouble. Using the built in API JS for models and collections allows me to pretty easily update a post title or content. All I have to do is call: ``` this.model.set({title: 'New Title'}); this.model.save(); ``` And everything works really well. But for post meta, there doesn't appear to be an easy way to update an entry to the database. Does anyone know how to go about taking a post model in Backbone, and updating it's meta data?
After having the same issue, I've come up with a basic solution - hopefully it's not too late for you. The Visual Composer "accordion plugin" seems to be a wrapper around the jQuery UI accordion; so the same methods are available. I've written some basic (room for improvement no doubt) code that checks if there is a hash on the end of the URL, and then match that up to an accordion panel (gets an index number for it), and then open it. It just requires you to add an ID to each of the accordion items in the CMS. ``` jQuery(window).load(function() { if(location.hash) { var panelRef = (window.location.hash.substring(1)); jQuery(".wpb_accordion_section").each(function(index) { if(jQuery(this).attr("id") == panelRef) { jQuery('.wpb_accordion_wrapper').accordion("option", "active", index); } }); } }); ``` You could modify it to use numbers instead of hard-coded IDs (remember the panels will be 0 indexed though).
187,500
<p>We have a lot of rogue custom fields. I feel that we can clear significant space in the DB if we remove the blank values. If I query my database with the following:</p> <pre><code>select * from wp_postmeta where meta_value = '' </code></pre> <p>I get 871038 (!)</p> <p>My question is, is it safe to delete these? Are there any potential issues that could arise from doing this?</p>
[ { "answer_id": 187501, "author": "fischi", "author_id": 15680, "author_profile": "https://wordpress.stackexchange.com/users/15680", "pm_score": 4, "selected": true, "text": "<p>You should be fine deleting empty custom fields.</p>\n\n<p>The main reason is, that <code>get_post_meta( $id, 'metakey', true )</code> returns an empty string if the field is not set, so it is the same as having an empty record set.</p>\n\n<p><code>get_post_meta( $id, 'metakey', false )</code>, returns an empty array if no value is set, so you should be fine too.</p>\n\n<p>The only problem you could face is with getting all metadata at once (<code>get_post_meta( $id )</code>), because in the return to this call the empty values are set, but they are not set, if there is no record in the database. This could cause a few <code>PHP_WARNING</code>s, but you should be okay.</p>\n" }, { "answer_id": 342796, "author": "NXPE3", "author_id": 171787, "author_profile": "https://wordpress.stackexchange.com/users/171787", "pm_score": 2, "selected": false, "text": "<p>As @fischi pointed out, it should be safe to delete empty values because <code>get_post_meta()</code> returns the same value for non-existent and empty meta keys, \nunless you somehow rely on the keys being set when fetching all metadata at once. </p>\n\n<p>WP 3.1 introduced the filters <code>add_{$meta_type}_metadata</code> and <code>update_{$meta_type}_metadata</code> that you can use to clean up empty values or even prevent them from being saved in the database: \n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/update_(meta_type)_metadata\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/update_(meta_type)_metadata</a> </p>\n\n<p>For example, you can intercept and delete falsy values for all keys containing 'my_prefix' like this: </p>\n\n<pre><code>add_filter('update_post_metadata', function($check, $object_id, $meta_key, $meta_value, $prev_value) {\n if(strpos($meta_key, 'my_prefix')) {\n if(empty($meta_value)) {\n delete_post_meta($object_id, $meta_key, $prev_value);\n return true; //stop update\n }\n }\n return null; //do update \n}, 10, 5);\n</code></pre>\n\n<p>Note that this won't clean up any already existing records. </p>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187500", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38536/" ]
We have a lot of rogue custom fields. I feel that we can clear significant space in the DB if we remove the blank values. If I query my database with the following: ``` select * from wp_postmeta where meta_value = '' ``` I get 871038 (!) My question is, is it safe to delete these? Are there any potential issues that could arise from doing this?
You should be fine deleting empty custom fields. The main reason is, that `get_post_meta( $id, 'metakey', true )` returns an empty string if the field is not set, so it is the same as having an empty record set. `get_post_meta( $id, 'metakey', false )`, returns an empty array if no value is set, so you should be fine too. The only problem you could face is with getting all metadata at once (`get_post_meta( $id )`), because in the return to this call the empty values are set, but they are not set, if there is no record in the database. This could cause a few `PHP_WARNING`s, but you should be okay.
187,527
<p>Let me explain what Im trying to do. Im creating a plugin that will have a main page like a dashboard that will be used to manage the public facing side of the plugin. Just think like a separate app inside a normal WordPress site.</p> <p>That page needs to be completely separate from user theme as will be totally custom. Admin bar will be used, nothing else.</p> <p>My first thought was to create a page with a custom template (already done that) and second step would be to remove all actions from wp_header + wp_footer and remove all scripts and styles that are not WordPress core.</p> <p>So currently Im stuck on step 2 and before going forward Im wondering if there is another way to do this that Im missing.</p>
[ { "answer_id": 187532, "author": "JoshuaDoshua", "author_id": 45769, "author_profile": "https://wordpress.stackexchange.com/users/45769", "pm_score": 1, "selected": false, "text": "<p>It seems a little odd to only offer the admin bar for a page, but the easiest solution I can think of would be to use conditional functions to deregister scripts/styles and create custom template files for this specific page.\nUnfortunately, you'll have to figure out all the styles/scripts that are loaded</p>\n\n<pre><code>add_action('init', 'remove_all_the_things');\n\nfunction remove_all_the_things() {\n\n if (is_page(123)) {\n wp_dequeue_style('main');\n wp_dequeue_script('jquery');\n // etc\n // remove other actions/filters as well\n }\n}\n</code></pre>\n\n<p>and you can create a custom header/footer with</p>\n\n<p><code>header-empty.php</code> &amp; <code>footer-empty.php</code></p>\n\n<p>calling <code>get_header('empty');</code> &amp; <code>get_footer('empty');</code> in your page template</p>\n\n<p>Reference:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/is_page\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/is_page</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_script\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_dequeue_script</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_style\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_dequeue_style</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_header</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/get_footer\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_footer</a></p>\n" }, { "answer_id": 187674, "author": "chifliiiii", "author_id": 4130, "author_profile": "https://wordpress.stackexchange.com/users/4130", "pm_score": 1, "selected": true, "text": "<p>This is what I´ve done so far, I won't mark as correct answer yet in case there is a better approach that Im not aware.</p>\n\n<pre><code>add_action('wp_enqueue_scripts',array( $this, 'remove_all_actions'), 99);\npublic function remove_all_actions(){\n if( 'custom-template.php' != get_page_template_slug( get_queried_object_id() ))\n return;\n global $wp_scripts, $wp_styles;\n\n $exceptions = array(\n 'admin-bar',\n 'jquery',\n 'query-monitor'\n );\n\n foreach( $wp_scripts-&gt;queue as $handle ){\n if( in_array($handle, $exceptions))\n continue;\n wp_dequeue_script($handle);\n }\n\n foreach( $wp_styles-&gt;queue as $handle ){\n if( in_array($handle, $exceptions) )\n continue;\n wp_dequeue_style($handle);\n }\n\n // Now remove actions\n $action_exceptions = array(\n 'wp_print_footer_scripts',\n 'wp_admin_bar_render',\n\n );\n\n // No core action in header\n remove_all_actions('wp_header');\n\n global $wp_filter;\n foreach( $wp_filter['wp_footer'] as $priority =&gt; $handle ){\n\n if( in_array( key($handle), $action_exceptions ) )\n continue;\n unset( $wp_filter['wp_footer'][$priority] );\n }\n\n }\n</code></pre>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4130/" ]
Let me explain what Im trying to do. Im creating a plugin that will have a main page like a dashboard that will be used to manage the public facing side of the plugin. Just think like a separate app inside a normal WordPress site. That page needs to be completely separate from user theme as will be totally custom. Admin bar will be used, nothing else. My first thought was to create a page with a custom template (already done that) and second step would be to remove all actions from wp\_header + wp\_footer and remove all scripts and styles that are not WordPress core. So currently Im stuck on step 2 and before going forward Im wondering if there is another way to do this that Im missing.
This is what I´ve done so far, I won't mark as correct answer yet in case there is a better approach that Im not aware. ``` add_action('wp_enqueue_scripts',array( $this, 'remove_all_actions'), 99); public function remove_all_actions(){ if( 'custom-template.php' != get_page_template_slug( get_queried_object_id() )) return; global $wp_scripts, $wp_styles; $exceptions = array( 'admin-bar', 'jquery', 'query-monitor' ); foreach( $wp_scripts->queue as $handle ){ if( in_array($handle, $exceptions)) continue; wp_dequeue_script($handle); } foreach( $wp_styles->queue as $handle ){ if( in_array($handle, $exceptions) ) continue; wp_dequeue_style($handle); } // Now remove actions $action_exceptions = array( 'wp_print_footer_scripts', 'wp_admin_bar_render', ); // No core action in header remove_all_actions('wp_header'); global $wp_filter; foreach( $wp_filter['wp_footer'] as $priority => $handle ){ if( in_array( key($handle), $action_exceptions ) ) continue; unset( $wp_filter['wp_footer'][$priority] ); } } ```
187,529
<p>In Advanced Custom Fields, I would like limit the Relationship field (<a href="http://www.advancedcustomfields.com/resources/relationship/" rel="nofollow">http://www.advancedcustomfields.com/resources/relationship/</a>) to specific pages.</p> <p>For various resons, involing Custom Post Types is not a solution for me right now. </p> <p>This is my sitemap: </p> <pre><code>website.com website.com/contact/ website.com/help/ website.com/map/ website.com/hunting-products/ website.com/hunting-products/scopes/ website.com/hunting-products/rifles/ website.com/fishing-products/ website.com/fishing-products/fishing-rods/ website.com/fishing-products/bait/ </code></pre> <p>In the Relationship field, and I would like to filter this so you only can select these products.</p> <pre><code>website.com/hunting-products/scopes/ website.com/hunting-products/rifles/ website.com/fishing-products/fishing-rods/ website.com/fishing-products/bait/ </code></pre>
[ { "answer_id": 187531, "author": "JoshuaDoshua", "author_id": 45769, "author_profile": "https://wordpress.stackexchange.com/users/45769", "pm_score": 0, "selected": false, "text": "<p>In <code>register_taxonomy</code> you can pass <code>page</code> as the associated post type and it will become an option on the edit screen</p>\n\n<p><code>register_taxonomy( 'custom_tax', 'page', $args );</code></p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/register_taxonomy</a></p>\n" }, { "answer_id": 187783, "author": "Liu Kang", "author_id": 71639, "author_profile": "https://wordpress.stackexchange.com/users/71639", "pm_score": 3, "selected": true, "text": "<p>Found a solution that works:</p>\n\n<pre><code>add_filter('acf/fields/relationship/query/name=products', 'exclude_id', 10, 3);\n\nfunction exclude_id ( $args, $field, $post ) {\n\n $args['post__not_in'] = array( $post, 9, 10, 11 );\n\n return $args;\n}\n</code></pre>\n\n<p>Added in functions. This will exclude the pages with id 9, 10 and 11.</p>\n" }, { "answer_id": 358225, "author": "mica", "author_id": 26610, "author_profile": "https://wordpress.stackexchange.com/users/26610", "pm_score": 0, "selected": false, "text": "<p>I had the quite similar issue. I needed to <strong>restrict</strong> Relationship Fields Choices to <strong>posts owned by Current User</strong> but grant a full access to “editor” &amp; “administrator”.</p>\n\n<p>Here is the code inserted in the <code>functions.php</code> file</p>\n\n<pre><code>&lt;?php\nfunction modify_field( $args, $field,$post) {\n if( !check_user_role(array('editor','administrator')) ){\n $args['author'] = get_current_user_id();\n }\n return $args;\n}\n\n add_filter( 'acf/fields/post_object/query/key=field_XXX..XXX', 'modify_field', 10, 3 );\n\n/* @src &amp; @credits https://wp-mix.com/wordpress-check-user-roles/ */\nfunction check_user_role($roles, $user_id = null) {\n if ($user_id) $user = get_userdata($user_id);\n else $user = wp_get_current_user();\n if (empty($user)) return false;\n\n foreach ($user-&gt;roles as $role) {\n if (in_array($role, $roles)) {\n return true;\n }\n }\n return false;\n}\n?&gt;\n</code></pre>\n" } ]
2015/05/06
[ "https://wordpress.stackexchange.com/questions/187529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71639/" ]
In Advanced Custom Fields, I would like limit the Relationship field (<http://www.advancedcustomfields.com/resources/relationship/>) to specific pages. For various resons, involing Custom Post Types is not a solution for me right now. This is my sitemap: ``` website.com website.com/contact/ website.com/help/ website.com/map/ website.com/hunting-products/ website.com/hunting-products/scopes/ website.com/hunting-products/rifles/ website.com/fishing-products/ website.com/fishing-products/fishing-rods/ website.com/fishing-products/bait/ ``` In the Relationship field, and I would like to filter this so you only can select these products. ``` website.com/hunting-products/scopes/ website.com/hunting-products/rifles/ website.com/fishing-products/fishing-rods/ website.com/fishing-products/bait/ ```
Found a solution that works: ``` add_filter('acf/fields/relationship/query/name=products', 'exclude_id', 10, 3); function exclude_id ( $args, $field, $post ) { $args['post__not_in'] = array( $post, 9, 10, 11 ); return $args; } ``` Added in functions. This will exclude the pages with id 9, 10 and 11.
187,543
<p>I made a custom endpoint with <code>wp rest api</code> for</p> <p><code>/wp-json/dn/locations</code></p> <p>which in turn runs the following <code>wpdb</code> query</p> <pre><code>$sql = "SELECT * FROM wp_posts p WHERE p.post_type = 'location' AND p.ID = 133;"; $results = $wpdb-&gt;get_results($sql); </code></pre> <p>Which returns fine but unfortunately my ACF fields aren't showing up in there. There are quite a few in the several queries I'm doing and this is going to turn into a mess quickly if I have to chase every field by hand. Is there an easier way to get posts with all the ACF fields attached? </p>
[ { "answer_id": 187671, "author": "Jacksonkr", "author_id": 13170, "author_profile": "https://wordpress.stackexchange.com/users/13170", "pm_score": 1, "selected": false, "text": "<p>I ended up using $wpdb for my custom tables and went with wp_query for my custom posts with ACF fields</p>\n\n<pre><code> $q = new WP_Query(array(\n 'post_type' =&gt; 'coupon',\n 'post__in' =&gt; $cids\n ));\n\n $coupons = array();\n while($q-&gt;have_posts()) : $q-&gt;the_post();\n $p = get_post();\n $f = get_fields();\n $m = array_merge((array)$p, (array)$f);\n array_push($coupons, $m);\n endwhile;\n</code></pre>\n\n<p>And that's how the cookie crumbles.</p>\n" }, { "answer_id": 247232, "author": "Ihor Vorotnov", "author_id": 47359, "author_profile": "https://wordpress.stackexchange.com/users/47359", "pm_score": 0, "selected": false, "text": "<pre><code>function wpse187543_register_acf() {\n\n $post_types = get_post_types( arrray( 'public' =&gt; true ), 'names' );\n\n foreach ( $post_types as $type ) {\n\n register_api_field( $type, 'acf', array(\n 'get_callback' =&gt; 'wpse187543_get_acf',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n ));\n\n }\n\n}\nadd_action( 'rest_api_init', 'wpse187543_register_acf' );\n\nfunction wpse187543_get_acf( $object, $field_name, $request ) {\n return get_fields( $object['id'] );\n}\n</code></pre>\n\n<p>This appends a key called “acf” to the rest api output for all public post types. You can customize the list of post types, of course. Also, there are some plugins that handle the job.</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187543", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13170/" ]
I made a custom endpoint with `wp rest api` for `/wp-json/dn/locations` which in turn runs the following `wpdb` query ``` $sql = "SELECT * FROM wp_posts p WHERE p.post_type = 'location' AND p.ID = 133;"; $results = $wpdb->get_results($sql); ``` Which returns fine but unfortunately my ACF fields aren't showing up in there. There are quite a few in the several queries I'm doing and this is going to turn into a mess quickly if I have to chase every field by hand. Is there an easier way to get posts with all the ACF fields attached?
I ended up using $wpdb for my custom tables and went with wp\_query for my custom posts with ACF fields ``` $q = new WP_Query(array( 'post_type' => 'coupon', 'post__in' => $cids )); $coupons = array(); while($q->have_posts()) : $q->the_post(); $p = get_post(); $f = get_fields(); $m = array_merge((array)$p, (array)$f); array_push($coupons, $m); endwhile; ``` And that's how the cookie crumbles.
187,597
<p>I have a custom post type named <code>store</code> and I have a custom taxonomy <code>city</code>, I also have a meta box with a field that is stored with <code>update_post_meta( $post_id, 'store_postal_code', $postal_code );</code> it also has a post meta for <code>store_parking</code>.</p> <p>How would I query the database in such a way it returns me rows in such a matter:</p> <pre><code>ID post_title store_postal_code city store_parking 1 Hilton 1234AB Amsterdam YES 2 Bijenkorf 1234AB Rotterdam NO </code></pre> <p>I tried this INCOMPLETE query:</p> <pre><code>$sql = 'SELECT * FROM `' . $wpdb-&gt;prefix . 'posts` WHERE `post_type` = \'store\' AND `post_status` = \'publish\''; foreach( $wpdb-&gt;get_results( $sql ) as $row =&gt; $post ) {} </code></pre>
[ { "answer_id": 187600, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 1, "selected": false, "text": "<p>You need a custom query and loop here, at least that's how I do it.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt;'store',\n 'taxonomy' =&gt; 'city',\n 'term' =&gt; 'your list here'\n 'posts_per_page' =&gt; 5\n );\n\n$loop = new WP_Query($args);\nif($loop-&gt;have_posts()):\n while($loop-&gt;have_posts()):\n do stuff here\n endwhile;\nendif;\n</code></pre>\n\n<p>You will probably want to sort these so add the key/value pairs to your arguments for <code>order</code> and <code>orderby</code>.</p>\n\n<p>The WP Codex is a fantastic reference for these types of questions. The WP_Query class is your focus: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>And specifically the post type parameters: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters</a></p>\n" }, { "answer_id": 187605, "author": "nyan", "author_id": 72720, "author_profile": "https://wordpress.stackexchange.com/users/72720", "pm_score": 3, "selected": true, "text": "<p>I would use a custom query like this:</p>\n\n<pre><code>$amsterdamstore_args = array(\n 'post_type' =&gt; 'store', // This is your custom post type\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'city', // This is your custom taxonomy\n 'terms' =&gt; 'Amsterdam', // The term you search for\n 'field' =&gt; 'name', // Check against the term's name (you might use 'slug', too)\n )\n ),\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'AND', // you could use OR, too - depending on what you want\n array(\n 'key' =&gt; 'store_postal_code', // Here goes your post_meta field's key\n 'value' =&gt; '1234AB', // Here goes your post_meta field's value\n 'compare' =&gt; '=',\n ),\n array(\n 'key' =&gt; 'store_parking', // Here goes your post_meta field's key\n 'value' =&gt; 'SOME_VALUE', // Here goes your post_meta field's value\n 'compare' =&gt; '=',\n ),\n )\n);\n</code></pre>\n\n<p>These are the arguments you need for <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">WP_Query</a> or - if that is of more use to you - <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\">get_posts</a>. - Loop through the results, get_post_meta as you wold do normally and there you go.</p>\n\n<p>BTW: You can combine the meta_query arrays to your liking: Add some, leave some, and you could even nest deeper and do something like AND ( A OR B ) ( C OR D )...</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8757/" ]
I have a custom post type named `store` and I have a custom taxonomy `city`, I also have a meta box with a field that is stored with `update_post_meta( $post_id, 'store_postal_code', $postal_code );` it also has a post meta for `store_parking`. How would I query the database in such a way it returns me rows in such a matter: ``` ID post_title store_postal_code city store_parking 1 Hilton 1234AB Amsterdam YES 2 Bijenkorf 1234AB Rotterdam NO ``` I tried this INCOMPLETE query: ``` $sql = 'SELECT * FROM `' . $wpdb->prefix . 'posts` WHERE `post_type` = \'store\' AND `post_status` = \'publish\''; foreach( $wpdb->get_results( $sql ) as $row => $post ) {} ```
I would use a custom query like this: ``` $amsterdamstore_args = array( 'post_type' => 'store', // This is your custom post type 'tax_query' => array( array( 'taxonomy' => 'city', // This is your custom taxonomy 'terms' => 'Amsterdam', // The term you search for 'field' => 'name', // Check against the term's name (you might use 'slug', too) ) ), 'meta_query' => array( 'relation' => 'AND', // you could use OR, too - depending on what you want array( 'key' => 'store_postal_code', // Here goes your post_meta field's key 'value' => '1234AB', // Here goes your post_meta field's value 'compare' => '=', ), array( 'key' => 'store_parking', // Here goes your post_meta field's key 'value' => 'SOME_VALUE', // Here goes your post_meta field's value 'compare' => '=', ), ) ); ``` These are the arguments you need for [WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query) or - if that is of more use to you - [get\_posts](https://codex.wordpress.org/Template_Tags/get_posts). - Loop through the results, get\_post\_meta as you wold do normally and there you go. BTW: You can combine the meta\_query arrays to your liking: Add some, leave some, and you could even nest deeper and do something like AND ( A OR B ) ( C OR D )...
187,606
<p>I'd like to execute some small piece of code like the following one:</p> <pre><code>global $wpdb; $rows = $wpdb-&gt;query('SELECT DATE(post_date) AS date, COUNT(*) AS count FROM ' . $wpdb-&gt;posts . ' GROUP BY DATE(post_date) ORDER BY DATE(post_date)'); foreach ($rows as $row) { echo $row-&gt;date . ': ' . $row-&gt;count . '&lt;br&gt;'; } </code></pre> <p>But I don't want to write a plugin for this small task. How can I manage it?</p>
[ { "answer_id": 187608, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>Context is everything with a question like this. However, since you are talking about a \"sandbox\" I am going to assume this is thowaway install on a development server and you just want to test bits and pieces of code without much hassle. To do that...</p>\n\n<ol>\n<li>I usually drop code into a mu-plugin file-- create a directory in\n<code>wp-content</code> called <code>mu-plugins</code>. Every file in that directory will\nexecute automatically.</li>\n<li>Or just hack the code into the theme where ever needed. I stress the\nassumption about the \"throwaway\" install. This is for short term\ntesting only-- for example, testing code for these question. I do\nnot expect to keep it, nor deploy it. When WordPress is updated, it\nall gets overwritten. <strong>This kind of piecemeal code testing is the only time I'd advocate hacking Core.</strong> </li>\n</ol>\n" }, { "answer_id": 187609, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 2, "selected": false, "text": "<p>Just edit functions.php file in theme's directory which is active and write this somewhere to the end of the file:</p>\n\n<pre><code>function prefix_my_dump() {\n //paste your code here\n}\nadd_action( 'wp_footer', 'prefix_my_dump' );\n</code></pre>\n\n<p>That hook 'wp_footer' will be echoing the content somewhere to the end of the page. You can use an other action of course. Check this page for some used actions &amp; filters:</p>\n\n<p><a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference\" rel=\"nofollow\">http://codex.wordpress.org/Plugin_API/Filter_Reference</a></p>\n" }, { "answer_id": 187660, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 1, "selected": false, "text": "<p>A relatively safe way to do it on even a production site is to make a new page and set it to <code>private</code> then copy the <code>page.php</code> file in your theme and change the title of that file to <code>page-new_page_id.php</code> (replace new_page_id with the id or name of the new page you created) then put your code into the content area of the new <code>page-new_page_id.php</code> file and access it as a logged in user.</p>\n\n<p>Setting the new page to private will make it visible only to logged in users, so it is \"relatively\" safe to do even on a live site.</p>\n" }, { "answer_id": 187741, "author": "Stanislau Ladutska", "author_id": 24891, "author_profile": "https://wordpress.stackexchange.com/users/24891", "pm_score": 2, "selected": true, "text": "<p>Best way for execute any PHP code during development its Console from <a href=\"https://wordpress.org/plugins/developer/\" rel=\"nofollow\">Developer plugin</a>. You can install <a href=\"https://wordpress.org/plugins/developer/\" rel=\"nofollow\">Developer plugin</a>, and activate console module. \"Debug\" link will appear in top right corner in your admin bar. You can go there, and execute any php code you like.</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187606", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64590/" ]
I'd like to execute some small piece of code like the following one: ``` global $wpdb; $rows = $wpdb->query('SELECT DATE(post_date) AS date, COUNT(*) AS count FROM ' . $wpdb->posts . ' GROUP BY DATE(post_date) ORDER BY DATE(post_date)'); foreach ($rows as $row) { echo $row->date . ': ' . $row->count . '<br>'; } ``` But I don't want to write a plugin for this small task. How can I manage it?
Best way for execute any PHP code during development its Console from [Developer plugin](https://wordpress.org/plugins/developer/). You can install [Developer plugin](https://wordpress.org/plugins/developer/), and activate console module. "Debug" link will appear in top right corner in your admin bar. You can go there, and execute any php code you like.
187,612
<p>We've been noticing really long load times when going to edit a post or page. Using Query Monitor, we found that this WP core query is taking upwards to 15-20s.</p> <pre><code>SELECT meta_key FROM wp_postmeta GROUP BY meta_key HAVING meta_key NOT LIKE '\\_%' ORDER BY meta_key LIMIT 30 caller: meta_form() post_custom_meta_box() do_meta_boxes() </code></pre> <p>We do use a lot of postmeta as one of our post types uses about 20 or so custom fields. I would say maybe we rely too much on postmeta, but this seems like a very inneficient query, seeing that it's not even selecting the ID of the post.</p> <p>Is this a common issue? Is there a way to disable this function through a filter? Thanks for any input.</p>
[ { "answer_id": 187712, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>If you want to test your custom SQL to see how it affects the loading time, you can try this query swapping: </p>\n\n<pre><code>/**\n * Restrict the potential slow query in the meta_form() to the current post ID.\n *\n * @see http://wordpress.stackexchange.com/a/187712/26350\n */\n\nadd_action( 'add_meta_boxes_post', function( $post )\n{\n add_filter( 'query', function( $sql ) use ( $post )\n {\n global $wpdb;\n $find = \"SELECT meta_key\n FROM $wpdb-&gt;postmeta\n GROUP BY meta_key \n HAVING meta_key NOT LIKE '\\\\\\_%'\n ORDER BY meta_key \n LIMIT 30\";\n if( preg_replace( '/\\s+/', ' ', $sql ) === preg_replace( '/\\s+/', ' ', $find )\n &amp;&amp; $post instanceof WP_Post \n ) {\n $post_id = (int) $post-&gt;ID;\n $sql = \"SELECT meta_key\n FROM $wpdb-&gt;postmeta\n WHERE post_id = {$post_id}\n GROUP BY meta_key\n HAVING meta_key NOT LIKE '\\\\\\_%'\n ORDER BY meta_key\n LIMIT 30\";\n }\n return $sql;\n } ); \n} );\n</code></pre>\n\n<p>Here we use the <code>add_meta_boxes_{$post_type}</code> hook, where <code>$post_type = 'post'</code>.</p>\n\n<p>Here we swap the whole query, but we could also have adjusted it to support the dynamic limit. </p>\n\n<p>Hopefully you can adjust this to your needs.</p>\n\n<h2>Update:</h2>\n\n<p>This potentially slow SQL core query, has now been adjusted in WP version 4.3\nfrom</p>\n\n<pre><code>SELECT meta_key \nFROM wp_postmeta \nGROUP BY meta_key \nHAVING meta_key NOT LIKE '\\\\_%' \nORDER BY meta_key \nLIMIT 30\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>SELECT DISTINCT meta_key\nFROM wp_postmeta\nWHERE meta_key NOT BETWEEN '_' AND '_z'\nHAVING meta_key NOT LIKE '\\_%'\nORDER BY meta_key\nLIMIT 30;\n</code></pre>\n\n<p>Check out the core ticket <a href=\"https://core.trac.wordpress.org/ticket/24498\" rel=\"nofollow\">#24498</a> for more info.</p>\n" }, { "answer_id": 232209, "author": "Dan K", "author_id": 98285, "author_profile": "https://wordpress.stackexchange.com/users/98285", "pm_score": 3, "selected": false, "text": "<p>If you browse through the source code of the function you'll find this:</p>\n\n<pre><code>$keys = apply_filters( 'postmeta_form_keys', null, $post );\nif ( null === $keys ) {\n ... \n}\n</code></pre>\n\n<p>Using the <code>postmeta_form_keys</code> hook you can manually specify the keys to avoid calling this inefficient query altogether: </p>\n\n<pre><code>add_filter('postmeta_form_keys', function(){\n return ['your_meta_key'];\n});\n</code></pre>\n" }, { "answer_id": 240751, "author": "prosti", "author_id": 88606, "author_profile": "https://wordpress.stackexchange.com/users/88606", "pm_score": 2, "selected": false, "text": "<p>Can you try this out. This is not a solution, but a temporary workaround.</p>\n\n<pre><code>// disable big slowdown http://wordpress.stackexchange.com/questions/187612/admin-very-slow-edit-page-caused-by-core-meta-query\nfunction dj_limit_postmeta( $string, $post ) {\n return array(null);\n}\nadd_filter( 'postmeta_form_keys', 'dj_limit_postmeta', 10, 3 );\n</code></pre>\n" }, { "answer_id": 405258, "author": "Nic Bug", "author_id": 144969, "author_profile": "https://wordpress.stackexchange.com/users/144969", "pm_score": 2, "selected": false, "text": "<p>had that issue still in the year 2022 because i have over 10.000 posts and each has 30 meta keys/values. so there is an easy and performant workaround if you insert that piece of code in your functions.php:</p>\n<pre><code>function set_postmeta_choice( $string, $post ) {\n $meta_keys = array();\n foreach(has_meta( $post-&gt;ID ) as $meta){\n $meta_keys[] = $meta[&quot;meta_key&quot;];\n }\n return $meta_keys;\n}\nadd_filter( 'postmeta_form_keys', 'set_postmeta_choice', 10, 3 );\n</code></pre>\n<p>this way you still have the meta_key suggestions in the dropdown field</p>\n" }, { "answer_id": 410913, "author": "Bibek Sigdel", "author_id": 200047, "author_profile": "https://wordpress.stackexchange.com/users/200047", "pm_score": -1, "selected": false, "text": "<p>If you need custom fields in your post/order edit page then change the query in wp-admin/includes/template.php\nFROM:</p>\n<pre><code>SELECT DISTINCT meta_key\n FROM $wpdb-&gt;postmeta\n WHERE meta_key NOT BETWEEN '_' AND '_z'\n HAVING meta_key NOT LIKE %s\n ORDER BY meta_key\n LIMIT %d\n</code></pre>\n<p>TO:</p>\n<pre><code>SELECT DISTINCT meta_key\n FROM wp_postmeta\n WHERE meta_key NOT LIKE '\\_%'\n ORDER BY meta_key\n LIMIT 70\n</code></pre>\n<p>Check your post edit page to see if you are able to find the custom field you need, and adjust the LIMIT value according. Lesser the limit, the faster will be your page.</p>\n<p>If you do not need the custom field dropdown at all then replace the code with:</p>\n<pre><code>SELECT DISTINCT meta_key\n FROM wp_postmeta\n WHERE meta_key NOT LIKE '\\_%'\n LIMIT 1\n</code></pre>\n<p>This should speed up your backend pages.</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38536/" ]
We've been noticing really long load times when going to edit a post or page. Using Query Monitor, we found that this WP core query is taking upwards to 15-20s. ``` SELECT meta_key FROM wp_postmeta GROUP BY meta_key HAVING meta_key NOT LIKE '\\_%' ORDER BY meta_key LIMIT 30 caller: meta_form() post_custom_meta_box() do_meta_boxes() ``` We do use a lot of postmeta as one of our post types uses about 20 or so custom fields. I would say maybe we rely too much on postmeta, but this seems like a very inneficient query, seeing that it's not even selecting the ID of the post. Is this a common issue? Is there a way to disable this function through a filter? Thanks for any input.
If you want to test your custom SQL to see how it affects the loading time, you can try this query swapping: ``` /** * Restrict the potential slow query in the meta_form() to the current post ID. * * @see http://wordpress.stackexchange.com/a/187712/26350 */ add_action( 'add_meta_boxes_post', function( $post ) { add_filter( 'query', function( $sql ) use ( $post ) { global $wpdb; $find = "SELECT meta_key FROM $wpdb->postmeta GROUP BY meta_key HAVING meta_key NOT LIKE '\\\_%' ORDER BY meta_key LIMIT 30"; if( preg_replace( '/\s+/', ' ', $sql ) === preg_replace( '/\s+/', ' ', $find ) && $post instanceof WP_Post ) { $post_id = (int) $post->ID; $sql = "SELECT meta_key FROM $wpdb->postmeta WHERE post_id = {$post_id} GROUP BY meta_key HAVING meta_key NOT LIKE '\\\_%' ORDER BY meta_key LIMIT 30"; } return $sql; } ); } ); ``` Here we use the `add_meta_boxes_{$post_type}` hook, where `$post_type = 'post'`. Here we swap the whole query, but we could also have adjusted it to support the dynamic limit. Hopefully you can adjust this to your needs. Update: ------- This potentially slow SQL core query, has now been adjusted in WP version 4.3 from ``` SELECT meta_key FROM wp_postmeta GROUP BY meta_key HAVING meta_key NOT LIKE '\\_%' ORDER BY meta_key LIMIT 30 ``` to: ``` SELECT DISTINCT meta_key FROM wp_postmeta WHERE meta_key NOT BETWEEN '_' AND '_z' HAVING meta_key NOT LIKE '\_%' ORDER BY meta_key LIMIT 30; ``` Check out the core ticket [#24498](https://core.trac.wordpress.org/ticket/24498) for more info.
187,629
<p>Per this question (<a href="https://wordpress.stackexchange.com/questions/29635/how-to-create-an-attachments-archive-with-working-pagination">How to create an attachments archive with working pagination?</a>), I've been using the following function to have archive pages display attachments as well as pages and posts. It was working for the preexisting tag and category archive pages, but it stopped working a few weeks ago (possibly due to a Wordpress update, but I didn't notice at the time). I checked, and the <code>post_tag</code> and <code>category</code> taxonomies are still registered for attachments.</p> <p>This code still works to display attachments in the archive pages of custom taxonomies (<code>topic</code> and <code>training</code> below). Any ideas on what changed, and what to change to get this working again?</p> <pre><code>add_action('parse_query', 'hijack_query'); function hijack_query() { global $wp_query; // When inside a custom taxonomy archive, include attachments AS WELL AS pages and posts. // Note that is_tax() returns false on category archives and tag archives. Use is_category() and is_tag() respectively when checking for category and tag archives. if (is_tax('topic') OR is_tax('training') OR is_tag() OR is_category()) { $wp_query-&gt;query_vars['post_type'] = array( 'attachment', 'page', 'post' ); $wp_query-&gt;query_vars['post_status'] = array( null ); return $wp_query; } } </code></pre>
[ { "answer_id": 187631, "author": "ambroseya", "author_id": 72778, "author_profile": "https://wordpress.stackexchange.com/users/72778", "pm_score": 1, "selected": false, "text": "<p>The WP_Query documentation on the codex specifically says:</p>\n\n<blockquote>\n <p>'attachment' - an attachment. Whilst the default WP_Query post_status\n is 'publish', attachments have a default post_status of 'inherit'.\n This means no attachments will be returned unless you also explicitly\n set post_status to 'inherit' or 'any'.</p>\n</blockquote>\n\n<p>I am not sure why it was working before because this is not a recent change but it looks like post_status would have to be 'inherit' or 'any' rather than null. </p>\n" }, { "answer_id": 188038, "author": "tshynik", "author_id": 65906, "author_profile": "https://wordpress.stackexchange.com/users/65906", "pm_score": 1, "selected": true, "text": "<p>Figured it out! The culprit was the plugin \"Add Categories to Pages\" which one of my editors had added to the site. In addition to registering <code>post_tag</code> and <code>category</code> for the <code>page</code> post type, it <em>also</em> modified the archive.php and tag.php queries to only look in the <code>post</code> and <code>page</code> types---yet another solution for the issue of including posts, pages, and attachments:</p>\n\n<pre><code>// Add Page as a post_type in the archive.php and tag.php \nfunction category_and_tag_archives( $wp_query ) {\n\n $my_post_array = array('post','page');\n\n if ( $wp_query-&gt;get( 'category_name' ) || $wp_query-&gt;get( 'cat' ) )\n $wp_query-&gt;set( 'post_type', $my_post_array );\n\n if ( $wp_query-&gt;get( 'tag' ) )\n $wp_query-&gt;set( 'post_type', $my_post_array );\n }\n</code></pre>\n\n<p>AND ANOTHER THING---make sure to visit the permalink options page (yoursite.com/wp-admin/options-permalink.php) after adding a new taxonomy. Saving, even without making changes, will flush the rewrite rules. Viewing the new taxonomy archive will return a 404 until then.</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65906/" ]
Per this question ([How to create an attachments archive with working pagination?](https://wordpress.stackexchange.com/questions/29635/how-to-create-an-attachments-archive-with-working-pagination)), I've been using the following function to have archive pages display attachments as well as pages and posts. It was working for the preexisting tag and category archive pages, but it stopped working a few weeks ago (possibly due to a Wordpress update, but I didn't notice at the time). I checked, and the `post_tag` and `category` taxonomies are still registered for attachments. This code still works to display attachments in the archive pages of custom taxonomies (`topic` and `training` below). Any ideas on what changed, and what to change to get this working again? ``` add_action('parse_query', 'hijack_query'); function hijack_query() { global $wp_query; // When inside a custom taxonomy archive, include attachments AS WELL AS pages and posts. // Note that is_tax() returns false on category archives and tag archives. Use is_category() and is_tag() respectively when checking for category and tag archives. if (is_tax('topic') OR is_tax('training') OR is_tag() OR is_category()) { $wp_query->query_vars['post_type'] = array( 'attachment', 'page', 'post' ); $wp_query->query_vars['post_status'] = array( null ); return $wp_query; } } ```
Figured it out! The culprit was the plugin "Add Categories to Pages" which one of my editors had added to the site. In addition to registering `post_tag` and `category` for the `page` post type, it *also* modified the archive.php and tag.php queries to only look in the `post` and `page` types---yet another solution for the issue of including posts, pages, and attachments: ``` // Add Page as a post_type in the archive.php and tag.php function category_and_tag_archives( $wp_query ) { $my_post_array = array('post','page'); if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) ) $wp_query->set( 'post_type', $my_post_array ); if ( $wp_query->get( 'tag' ) ) $wp_query->set( 'post_type', $my_post_array ); } ``` AND ANOTHER THING---make sure to visit the permalink options page (yoursite.com/wp-admin/options-permalink.php) after adding a new taxonomy. Saving, even without making changes, will flush the rewrite rules. Viewing the new taxonomy archive will return a 404 until then.
187,644
<p>Many people embed my website's pages in their websites as iframes. I want them to not take my footer, header and a specific division in those iframes. Since, footer, header and mentioned specific division is present in all of my pages.</p> <p>What should I do? Should I add some code in my header or in my <code>functions.php</code> file?</p>
[ { "answer_id": 187663, "author": "Tuan Anh Hoang-Vu", "author_id": 2222, "author_profile": "https://wordpress.stackexchange.com/users/2222", "pm_score": 0, "selected": false, "text": "<p>Why don't you create a <a href=\"http://codex.wordpress.org/Page_Templates#Custom_Page_Template\" rel=\"nofollow\">specific template</a> just for embedding? In your custom template, you could just remove the <code>get_header()</code>, <code>get_footer()</code> and <code>get_sidebar()</code> calls.</p>\n" }, { "answer_id": 236940, "author": "Jelle Wielsma", "author_id": 101549, "author_profile": "https://wordpress.stackexchange.com/users/101549", "pm_score": 1, "selected": false, "text": "<p>You could detect the <code>$_SERVER['HTTP_REFERER']</code> variable to detect whether the page is requested from an external server. If so, then you should load an alternative header and footer using <code>get_header()</code> and <code>get_footer()</code>. You'll need those calls to make sure all scripts and stylesheets are loaded, but you can remove the other content that make up the actual header and footer elements.</p>\n\n<p>For example you could duplicate your current <code>header.php</code> to <code>header-iframe.php</code> and call the header with:</p>\n\n<pre><code>get_header('iframe');\n</code></pre>\n\n<p>The same thing goes for the footer. Create a file called <code>footer-iframe.php</code> and call it using:</p>\n\n<pre><code>get_footer('iframe');\n</code></pre>\n\n<p>Just make sure your <code>header-iframe.php</code> contains everything up to the opening tag, like this:</p>\n\n<pre><code>&lt;html &lt;?php language_attributes(); ?&gt;&gt;\n&lt;head&gt;\n\n &lt;meta charset=\"&lt;?php bloginfo( 'charset' ); ?&gt;\" /&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /&gt;\n &lt;meta name=\"apple-mobile-web-app-capable\" content=\"yes\" /&gt;\n\n &lt;title&gt;&lt;?php wp_title( '|', true, 'right' ); ?&gt;&lt;/title&gt;\n &lt;?php wp_head(); ?&gt;\n\n&lt;/head&gt;\n\n&lt;body &lt;?php body_class('iframe'); ?&gt;&gt;\n</code></pre>\n\n<p>Your <code>footer-iframe.php</code> should be stripped of all excess content, like this:</p>\n\n<pre><code>&lt;?php wp_footer(); ?&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>The above snippets are just an example, but you get the idea. Calling the <code>get_header('iframe');</code> and <code>get_footer('iframe);</code> functions should be conditional based on the <code>$_SERVER['HTTP_REFERER']</code> variable. This could be done using <code>preg_match</code> or any other native PHP comparison function.</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/72782/" ]
Many people embed my website's pages in their websites as iframes. I want them to not take my footer, header and a specific division in those iframes. Since, footer, header and mentioned specific division is present in all of my pages. What should I do? Should I add some code in my header or in my `functions.php` file?
You could detect the `$_SERVER['HTTP_REFERER']` variable to detect whether the page is requested from an external server. If so, then you should load an alternative header and footer using `get_header()` and `get_footer()`. You'll need those calls to make sure all scripts and stylesheets are loaded, but you can remove the other content that make up the actual header and footer elements. For example you could duplicate your current `header.php` to `header-iframe.php` and call the header with: ``` get_header('iframe'); ``` The same thing goes for the footer. Create a file called `footer-iframe.php` and call it using: ``` get_footer('iframe'); ``` Just make sure your `header-iframe.php` contains everything up to the opening tag, like this: ``` <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <?php wp_head(); ?> </head> <body <?php body_class('iframe'); ?>> ``` Your `footer-iframe.php` should be stripped of all excess content, like this: ``` <?php wp_footer(); ?> </body> </html> ``` The above snippets are just an example, but you get the idea. Calling the `get_header('iframe');` and `get_footer('iframe);` functions should be conditional based on the `$_SERVER['HTTP_REFERER']` variable. This could be done using `preg_match` or any other native PHP comparison function.
187,651
<p>Okay so I have been trying to educate myself to create new panels sections and controls dynamically using customizer's JS API.</p> <p>It has been frustrating few days and I was unable to get the exact way to achieve this via JS API. </p> <p>So far, this is some thing I am doing to make it happen but with no success:</p> <pre><code> // for Settings api.create( params.id, params.id, params.default, params.args ); // for controls var controlConstructor = api.controlConstructor[params.type]; var control = new controlConstructor(params.id, { params: params, previewer: api.previewer }); api.control.add( params.id, control ); //for Sections var section = new api.Section(params.id, { params: params }); api.section.add( params.id, section ); api.section('section_id').activate(); </code></pre> <p>None of them seem to work as the section doesn't appear and I have to run <code>api.section('section_id').activate()</code> twice in console to make the section appear, the same is with control.</p>
[ { "answer_id": 189897, "author": "Mohit Aneja", "author_id": 54029, "author_profile": "https://wordpress.stackexchange.com/users/54029", "pm_score": -1, "selected": false, "text": "<p>I'd suggest instead of reinventing the wheel, maybe you will consider this framework as a base for your projects. <a href=\"http://wpshed.com/wordpress-theme-customizer-framework/\" rel=\"nofollow\">http://wpshed.com/wordpress-theme-customizer-framework/</a>.</p>\n\n<p>This one is the best I found while I was learning and looking for frameworks. You can extend this framework with your own custom controls and the below link will help you understand and implement the communication between customizer and customizer-preview via jQuery or javascript.</p>\n\n<p><a href=\"https://conductorplugin.com/developing-wordpress-customizer-part1/\" rel=\"nofollow\">https://conductorplugin.com/developing-wordpress-customizer-part1/</a></p>\n" }, { "answer_id": 223130, "author": "Philip Ingram", "author_id": 82849, "author_profile": "https://wordpress.stackexchange.com/users/82849", "pm_score": 2, "selected": false, "text": "<p>1) Maybe bind to the api.ready state which may fix having to call your section twice</p>\n\n<pre><code>(function($, api){\n api.bind( 'ready', function() {...\n\n }\n})(jQuery);\n</code></pre>\n\n<p>I saw a note in trac that said \"Note that the APIs for dynamically-added controls, and APIs for JS-templated custom Sections and Panels are not yet available as of WordPress 4.2. See #30741.\" Reading that trac ends with \"likely not for 4.5 right now\" so your efforts may be futile =(</p>\n\n<p>2) For reference, the wp_customize JS API can be found <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-admin/js/customize-controls.js\" rel=\"nofollow\">here</a>. This <a href=\"https://make.wordpress.org/core/2014/10/27/toward-a-complete-javascript-api-for-the-customizer/\" rel=\"nofollow\">link</a> may be useful as well.</p>\n\n<p>3) I don't have enough rep for a third link but you might look at Kirki.org which is a helper framework for customizer fields. Kirki is pretty active on Github too.</p>\n\n<p>4) On the PHP side, you can use the \"active_callback\" option on your field array to dynamically present fields.</p>\n\n<pre><code>$wp_customize-&gt;add_control( 'some_single_page_specific_option', array(\n 'label' =&gt; esc_html__( 'Single Page Option' ),\n 'section' =&gt; 'my_page_options',\n 'active_callback' =&gt; 'if_is_singular',\n));\n\nfunction if_is_singular(){\n if( is_singular() ){\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>Good luck.</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187651", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48410/" ]
Okay so I have been trying to educate myself to create new panels sections and controls dynamically using customizer's JS API. It has been frustrating few days and I was unable to get the exact way to achieve this via JS API. So far, this is some thing I am doing to make it happen but with no success: ``` // for Settings api.create( params.id, params.id, params.default, params.args ); // for controls var controlConstructor = api.controlConstructor[params.type]; var control = new controlConstructor(params.id, { params: params, previewer: api.previewer }); api.control.add( params.id, control ); //for Sections var section = new api.Section(params.id, { params: params }); api.section.add( params.id, section ); api.section('section_id').activate(); ``` None of them seem to work as the section doesn't appear and I have to run `api.section('section_id').activate()` twice in console to make the section appear, the same is with control.
1) Maybe bind to the api.ready state which may fix having to call your section twice ``` (function($, api){ api.bind( 'ready', function() {... } })(jQuery); ``` I saw a note in trac that said "Note that the APIs for dynamically-added controls, and APIs for JS-templated custom Sections and Panels are not yet available as of WordPress 4.2. See #30741." Reading that trac ends with "likely not for 4.5 right now" so your efforts may be futile =( 2) For reference, the wp\_customize JS API can be found [here](https://core.trac.wordpress.org/browser/trunk/src/wp-admin/js/customize-controls.js). This [link](https://make.wordpress.org/core/2014/10/27/toward-a-complete-javascript-api-for-the-customizer/) may be useful as well. 3) I don't have enough rep for a third link but you might look at Kirki.org which is a helper framework for customizer fields. Kirki is pretty active on Github too. 4) On the PHP side, you can use the "active\_callback" option on your field array to dynamically present fields. ``` $wp_customize->add_control( 'some_single_page_specific_option', array( 'label' => esc_html__( 'Single Page Option' ), 'section' => 'my_page_options', 'active_callback' => 'if_is_singular', )); function if_is_singular(){ if( is_singular() ){ return true; } else { return false; } } ``` Good luck.
187,665
<p>I am working on listing some working portfolio. I want to list a certain amount and I was reading the post_per_page can do that. </p> <p>I have the following query, just trying to figure out where I can add the post par page code. I'm pretty new at php and wordpress. Any help would be appreciated.</p> <pre><code>&lt;?php $args = array( 'nopaging' =&gt; true, 'post_type' =&gt; 'portfolio', 'orderby' =&gt; array('menu_order' =&gt; 'ASC', 'ID' =&gt; 'ASC') ); $wp_query = new WP_Query($args); while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); get_template_part('loop', 'portfolio'); endwhile; ?&gt; </code></pre>
[ { "answer_id": 189897, "author": "Mohit Aneja", "author_id": 54029, "author_profile": "https://wordpress.stackexchange.com/users/54029", "pm_score": -1, "selected": false, "text": "<p>I'd suggest instead of reinventing the wheel, maybe you will consider this framework as a base for your projects. <a href=\"http://wpshed.com/wordpress-theme-customizer-framework/\" rel=\"nofollow\">http://wpshed.com/wordpress-theme-customizer-framework/</a>.</p>\n\n<p>This one is the best I found while I was learning and looking for frameworks. You can extend this framework with your own custom controls and the below link will help you understand and implement the communication between customizer and customizer-preview via jQuery or javascript.</p>\n\n<p><a href=\"https://conductorplugin.com/developing-wordpress-customizer-part1/\" rel=\"nofollow\">https://conductorplugin.com/developing-wordpress-customizer-part1/</a></p>\n" }, { "answer_id": 223130, "author": "Philip Ingram", "author_id": 82849, "author_profile": "https://wordpress.stackexchange.com/users/82849", "pm_score": 2, "selected": false, "text": "<p>1) Maybe bind to the api.ready state which may fix having to call your section twice</p>\n\n<pre><code>(function($, api){\n api.bind( 'ready', function() {...\n\n }\n})(jQuery);\n</code></pre>\n\n<p>I saw a note in trac that said \"Note that the APIs for dynamically-added controls, and APIs for JS-templated custom Sections and Panels are not yet available as of WordPress 4.2. See #30741.\" Reading that trac ends with \"likely not for 4.5 right now\" so your efforts may be futile =(</p>\n\n<p>2) For reference, the wp_customize JS API can be found <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-admin/js/customize-controls.js\" rel=\"nofollow\">here</a>. This <a href=\"https://make.wordpress.org/core/2014/10/27/toward-a-complete-javascript-api-for-the-customizer/\" rel=\"nofollow\">link</a> may be useful as well.</p>\n\n<p>3) I don't have enough rep for a third link but you might look at Kirki.org which is a helper framework for customizer fields. Kirki is pretty active on Github too.</p>\n\n<p>4) On the PHP side, you can use the \"active_callback\" option on your field array to dynamically present fields.</p>\n\n<pre><code>$wp_customize-&gt;add_control( 'some_single_page_specific_option', array(\n 'label' =&gt; esc_html__( 'Single Page Option' ),\n 'section' =&gt; 'my_page_options',\n 'active_callback' =&gt; 'if_is_singular',\n));\n\nfunction if_is_singular(){\n if( is_singular() ){\n return true;\n } else {\n return false;\n }\n}\n</code></pre>\n\n<p>Good luck.</p>\n" } ]
2015/05/07
[ "https://wordpress.stackexchange.com/questions/187665", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68271/" ]
I am working on listing some working portfolio. I want to list a certain amount and I was reading the post\_per\_page can do that. I have the following query, just trying to figure out where I can add the post par page code. I'm pretty new at php and wordpress. Any help would be appreciated. ``` <?php $args = array( 'nopaging' => true, 'post_type' => 'portfolio', 'orderby' => array('menu_order' => 'ASC', 'ID' => 'ASC') ); $wp_query = new WP_Query($args); while ($wp_query->have_posts()) : $wp_query->the_post(); get_template_part('loop', 'portfolio'); endwhile; ?> ```
1) Maybe bind to the api.ready state which may fix having to call your section twice ``` (function($, api){ api.bind( 'ready', function() {... } })(jQuery); ``` I saw a note in trac that said "Note that the APIs for dynamically-added controls, and APIs for JS-templated custom Sections and Panels are not yet available as of WordPress 4.2. See #30741." Reading that trac ends with "likely not for 4.5 right now" so your efforts may be futile =( 2) For reference, the wp\_customize JS API can be found [here](https://core.trac.wordpress.org/browser/trunk/src/wp-admin/js/customize-controls.js). This [link](https://make.wordpress.org/core/2014/10/27/toward-a-complete-javascript-api-for-the-customizer/) may be useful as well. 3) I don't have enough rep for a third link but you might look at Kirki.org which is a helper framework for customizer fields. Kirki is pretty active on Github too. 4) On the PHP side, you can use the "active\_callback" option on your field array to dynamically present fields. ``` $wp_customize->add_control( 'some_single_page_specific_option', array( 'label' => esc_html__( 'Single Page Option' ), 'section' => 'my_page_options', 'active_callback' => 'if_is_singular', )); function if_is_singular(){ if( is_singular() ){ return true; } else { return false; } } ``` Good luck.
187,705
<p>I've been asked to add a sort of safety mechanism to a site where a user can only access their profile if they have a cookie set after logging in, and they can only have a maximum of 3 cookies. I've made a table in the database to store the cookies, so I can keep count of them.</p> <p>I don't really know how WordPress works, but I've been able to find out that I need to edit the theme's <code>functions.php</code> file and add an action using <code>wp_login</code>. I've edited the <code>functions.php</code> file, added the action, request the user ID, and it returns <code>0</code>. I know that this is how <code>wp_get_current_user</code> is supposed to work, it returns <code>0</code> if there's no one logged in; however the user IS logged in, but it still won't return the ID. Here's the code:</p> <pre><code>add_action( 'wp_login', 'login_cookie' ); function login_cookie() { global $wpdb; $user = wp_get_current_user(); //Get current user $id = $user-&gt;ID; if(!isset($_COOKIE['userCookie'])) { // Query the database to see how many cookies they have used $cookie_count = $wpdb-&gt;get_var("SELECT COUNT(*) FROM wp_cookies WHERE user_id=".$id.""); // If the returned value is bigger or equal to 3 than the user cannot login // they will be logged out, and redirected if($cookie_count &gt;= 3) { wp_logout(); wp_redirect(""); } //Else they can login and they recieve a new cookie, which will get inserted into the database else { $value = password_hash($id,PASSWORD_DEFAULT); setcookie('userCookie', $value, time()+360000*24*100, "", "",false); $wpdb-&gt;insert( "wp_cookies", [ 'user_id'=&gt;$id, 'cookie_value'=&gt;$value ], [ '%d', '%s' ] ); } } } </code></pre> <p>Also this should only affect normal users, not admins. Any ideas for that?</p>
[ { "answer_id": 187710, "author": "Jayson", "author_id": 72813, "author_profile": "https://wordpress.stackexchange.com/users/72813", "pm_score": 4, "selected": true, "text": "<p><code>wp_login</code> hook provides access to two parameters: <code>$user-&gt;user_login</code> (string) and <code>$user</code> ( WP_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add_action() call: </p>\n\n<pre><code>function login_cookie($user_login, $user) {\n global $wpdb;\n\n var_dump($user); // get WP_User object\n\n //Get current user ID\n $id = $user-&gt;ID;\n .....\n}\n\nadd_action( 'wp_login', 'login_cookie', 10, 2 );\n</code></pre>\n" }, { "answer_id": 187711, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 2, "selected": false, "text": "<p>Actually the <code>wp_login</code> hook is passing the user object in its parameter.</p>\n\n<pre><code>function login_cookie( $user_login, $user ) {\n $user_id = $user-&gt;ID; // get user id\n // your next code\n}\nadd_action( 'wp_login', 'login_cookie', 10, 2 );\n</code></pre>\n" } ]
2015/05/08
[ "https://wordpress.stackexchange.com/questions/187705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/72812/" ]
I've been asked to add a sort of safety mechanism to a site where a user can only access their profile if they have a cookie set after logging in, and they can only have a maximum of 3 cookies. I've made a table in the database to store the cookies, so I can keep count of them. I don't really know how WordPress works, but I've been able to find out that I need to edit the theme's `functions.php` file and add an action using `wp_login`. I've edited the `functions.php` file, added the action, request the user ID, and it returns `0`. I know that this is how `wp_get_current_user` is supposed to work, it returns `0` if there's no one logged in; however the user IS logged in, but it still won't return the ID. Here's the code: ``` add_action( 'wp_login', 'login_cookie' ); function login_cookie() { global $wpdb; $user = wp_get_current_user(); //Get current user $id = $user->ID; if(!isset($_COOKIE['userCookie'])) { // Query the database to see how many cookies they have used $cookie_count = $wpdb->get_var("SELECT COUNT(*) FROM wp_cookies WHERE user_id=".$id.""); // If the returned value is bigger or equal to 3 than the user cannot login // they will be logged out, and redirected if($cookie_count >= 3) { wp_logout(); wp_redirect(""); } //Else they can login and they recieve a new cookie, which will get inserted into the database else { $value = password_hash($id,PASSWORD_DEFAULT); setcookie('userCookie', $value, time()+360000*24*100, "", "",false); $wpdb->insert( "wp_cookies", [ 'user_id'=>$id, 'cookie_value'=>$value ], [ '%d', '%s' ] ); } } } ``` Also this should only affect normal users, not admins. Any ideas for that?
`wp_login` hook provides access to two parameters: `$user->user_login` (string) and `$user` ( WP\_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add\_action() call: ``` function login_cookie($user_login, $user) { global $wpdb; var_dump($user); // get WP_User object //Get current user ID $id = $user->ID; ..... } add_action( 'wp_login', 'login_cookie', 10, 2 ); ```
187,731
<p>For example, i include 'wp-load.php' from external file. but if WP is not installed, then while i access that file, it redirects to '/wp-admin/install.php'. How to disable redirection, even if WP not installed, it doesnt matter to me.</p>
[ { "answer_id": 187710, "author": "Jayson", "author_id": 72813, "author_profile": "https://wordpress.stackexchange.com/users/72813", "pm_score": 4, "selected": true, "text": "<p><code>wp_login</code> hook provides access to two parameters: <code>$user-&gt;user_login</code> (string) and <code>$user</code> ( WP_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add_action() call: </p>\n\n<pre><code>function login_cookie($user_login, $user) {\n global $wpdb;\n\n var_dump($user); // get WP_User object\n\n //Get current user ID\n $id = $user-&gt;ID;\n .....\n}\n\nadd_action( 'wp_login', 'login_cookie', 10, 2 );\n</code></pre>\n" }, { "answer_id": 187711, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 2, "selected": false, "text": "<p>Actually the <code>wp_login</code> hook is passing the user object in its parameter.</p>\n\n<pre><code>function login_cookie( $user_login, $user ) {\n $user_id = $user-&gt;ID; // get user id\n // your next code\n}\nadd_action( 'wp_login', 'login_cookie', 10, 2 );\n</code></pre>\n" } ]
2015/05/08
[ "https://wordpress.stackexchange.com/questions/187731", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
For example, i include 'wp-load.php' from external file. but if WP is not installed, then while i access that file, it redirects to '/wp-admin/install.php'. How to disable redirection, even if WP not installed, it doesnt matter to me.
`wp_login` hook provides access to two parameters: `$user->user_login` (string) and `$user` ( WP\_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add\_action() call: ``` function login_cookie($user_login, $user) { global $wpdb; var_dump($user); // get WP_User object //Get current user ID $id = $user->ID; ..... } add_action( 'wp_login', 'login_cookie', 10, 2 ); ```
187,744
<p>I have 2 post types: lets say <code>products</code> and <code>product_variations</code>. I'd like to be able to modify the query via <code>pre_get_posts</code> to get all product with meta_keys <code>"_visible" = "true"</code> and <code>"_available" = "true"</code> AND all product_variations with meta_key <code>"_featured" = "true"</code>. </p> <p>The product_variations don't have the meta_keys <code>"_visible"/"_available"</code> and vice versa, so a straight up <code>AND</code> meta_query returns no results. <code>OR</code> relation isn't quite right either as two fields are <code>AND</code> related for one post type then <code>OR</code> related to the other post type. </p> <p>To make that slightly more visual because I just realized how complex it is to write out:</p> <pre><code>**product** _visible = true _available = true **product_variation** _featured = true </code></pre> <p>Is this possible via query args?<br> Is this possible via <code>posts_where</code>?<br> Do I need to run a separate query and then somehow merge the results?</p>
[ { "answer_id": 187710, "author": "Jayson", "author_id": 72813, "author_profile": "https://wordpress.stackexchange.com/users/72813", "pm_score": 4, "selected": true, "text": "<p><code>wp_login</code> hook provides access to two parameters: <code>$user-&gt;user_login</code> (string) and <code>$user</code> ( WP_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add_action() call: </p>\n\n<pre><code>function login_cookie($user_login, $user) {\n global $wpdb;\n\n var_dump($user); // get WP_User object\n\n //Get current user ID\n $id = $user-&gt;ID;\n .....\n}\n\nadd_action( 'wp_login', 'login_cookie', 10, 2 );\n</code></pre>\n" }, { "answer_id": 187711, "author": "Emetrop", "author_id": 64623, "author_profile": "https://wordpress.stackexchange.com/users/64623", "pm_score": 2, "selected": false, "text": "<p>Actually the <code>wp_login</code> hook is passing the user object in its parameter.</p>\n\n<pre><code>function login_cookie( $user_login, $user ) {\n $user_id = $user-&gt;ID; // get user id\n // your next code\n}\nadd_action( 'wp_login', 'login_cookie', 10, 2 );\n</code></pre>\n" } ]
2015/05/08
[ "https://wordpress.stackexchange.com/questions/187744", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6477/" ]
I have 2 post types: lets say `products` and `product_variations`. I'd like to be able to modify the query via `pre_get_posts` to get all product with meta\_keys `"_visible" = "true"` and `"_available" = "true"` AND all product\_variations with meta\_key `"_featured" = "true"`. The product\_variations don't have the meta\_keys `"_visible"/"_available"` and vice versa, so a straight up `AND` meta\_query returns no results. `OR` relation isn't quite right either as two fields are `AND` related for one post type then `OR` related to the other post type. To make that slightly more visual because I just realized how complex it is to write out: ``` **product** _visible = true _available = true **product_variation** _featured = true ``` Is this possible via query args? Is this possible via `posts_where`? Do I need to run a separate query and then somehow merge the results?
`wp_login` hook provides access to two parameters: `$user->user_login` (string) and `$user` ( WP\_User ). To pass them into your function you will need to add a priority (default is 10) and request 2 arguments from the add\_action() call: ``` function login_cookie($user_login, $user) { global $wpdb; var_dump($user); // get WP_User object //Get current user ID $id = $user->ID; ..... } add_action( 'wp_login', 'login_cookie', 10, 2 ); ```
187,769
<p>I have this query:</p> <pre><code>$cat_array = array(); $args=array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'exclude' =&gt; '187', 'posts_per_page' =&gt; 19, 'caller_get_posts'=&gt; 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); $cat_args=array('orderby' =&gt; 'none'); $cats = wp_get_post_terms( $post-&gt;ID , 'category', $cat_args); foreach($cats as $cat) { $cat_array[$cat-&gt;term_id] = $cat-&gt;term_id; } endwhile; } if ($cat_array) { foreach($cat_array as $cat) { $category = get_term_by('ID',$cat, 'category'); echo '&lt;li&gt;&lt;a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "View latest posts in %s" ), $category-&gt;name ) . '" ' . '&gt;' . $category-&gt;name.'&lt;/a&gt;'.'&lt;/li&gt;'; } } wp_reset_query(); </code></pre> <p>Which is listing the latest updated categories. All good. But I want to exclude a particular category from listing over there. That can be done like I have in the query<code>'exclude' =&gt; '187',</code> BUT the problem is with the following example: I have a post which belongs to two categories, one category is the one I don't want to display, and the other one is a category I do want to display. If I simply exclude it like I said above, none of the categories will display in the list, because it will completely exclude that post. How can I still show the other category, and hide the one I don't want tho show?</p> <p>Any clue? </p> <p>thanks</p>
[ { "answer_id": 187836, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": false, "text": "<p>Just skip the excluded category in your <code>foreach</code>:</p>\n\n<pre><code>foreach ( $cat_array as $cat ) {\n if ( $cat != EXCLUDED_CAT_ID ) {\n // Output\n }\n}\n</code></pre>\n" }, { "answer_id": 188454, "author": "vyperlook", "author_id": 6927, "author_profile": "https://wordpress.stackexchange.com/users/6927", "pm_score": 1, "selected": true, "text": "<p>solved this with</p>\n\n<pre><code> if ($cat_array) {\n foreach($cat_array as $cat) {\n $category = get_term_by('ID',$cat, 'category');\n if($category-&gt;name != 'Excluded category'){\n echo '&lt;div class=\"catspace\"&gt;&lt;a href=\"' . esc_attr(get_term_link($category, 'category')) . '\" title=\"' . sprintf( __( \"latest posts %s\" ), $category-&gt;name ) . '\" ' . '&gt;' . $category-&gt;name.'&lt;/a&gt;'.'&lt;/div&gt;';\n }else{echo '&lt;div class=\"catspace\"&gt;'. '' .'&lt;/div&gt;'; }\n }\n }\n</code></pre>\n" } ]
2015/05/08
[ "https://wordpress.stackexchange.com/questions/187769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6927/" ]
I have this query: ``` $cat_array = array(); $args=array( 'post_type' => 'post', 'post_status' => 'publish', 'exclude' => '187', 'posts_per_page' => 19, 'caller_get_posts'=> 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); $cat_args=array('orderby' => 'none'); $cats = wp_get_post_terms( $post->ID , 'category', $cat_args); foreach($cats as $cat) { $cat_array[$cat->term_id] = $cat->term_id; } endwhile; } if ($cat_array) { foreach($cat_array as $cat) { $category = get_term_by('ID',$cat, 'category'); echo '<li><a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "View latest posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'.'</li>'; } } wp_reset_query(); ``` Which is listing the latest updated categories. All good. But I want to exclude a particular category from listing over there. That can be done like I have in the query`'exclude' => '187',` BUT the problem is with the following example: I have a post which belongs to two categories, one category is the one I don't want to display, and the other one is a category I do want to display. If I simply exclude it like I said above, none of the categories will display in the list, because it will completely exclude that post. How can I still show the other category, and hide the one I don't want tho show? Any clue? thanks
solved this with ``` if ($cat_array) { foreach($cat_array as $cat) { $category = get_term_by('ID',$cat, 'category'); if($category->name != 'Excluded category'){ echo '<div class="catspace"><a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "latest posts %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'.'</div>'; }else{echo '<div class="catspace">'. '' .'</div>'; } } } ```
187,773
<p>I have a client's site where they want to add image title attributes dynamically to images that don't have one already. So if the title attribute is empty, add a title of whatever the post title is. How would I accomplish this?</p> <p>Effectively: <code>&lt;img src=img.jpg title=[wp-post-title-here] /&gt;</code></p>
[ { "answer_id": 188273, "author": "ambroseya", "author_id": 72778, "author_profile": "https://wordpress.stackexchange.com/users/72778", "pm_score": 1, "selected": false, "text": "<p>If we can assume that this is done properly for images that are in templates, and you're only concerned about page/post body content, you could use a filter when saving any post or page ( <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/save_post</a> ) to scan the content </p>\n\n<blockquote>\n <p>Since this action is triggered right after the post has been saved,\n you can easily access this post object by using get_post($post_id)</p>\n</blockquote>\n\n<p>You should then be able to do a search for all image tags <code>&lt;img</code>, and if they do not have the phrase <code>title=\"</code> before the next <code>&gt;</code>, insert right after <code>&lt;img</code> your <code>title=\"post title here\"</code> - don't forget to re \"save\" the post after the whole function runs.</p>\n\n<p>In order to do that, I would split the post string into substrings and then reassemble them again, but it's out of scope here to write all the code for you. </p>\n\n<p>Alternatively you could do a similar scan for the image tags when the code is displayed to the page by filtering on get_content or similar, but it makes more sense to save into the database correctly, in regard to page load for viewers.</p>\n" }, { "answer_id": 188280, "author": "Ewa", "author_id": 59414, "author_profile": "https://wordpress.stackexchange.com/users/59414", "pm_score": 0, "selected": false, "text": "<p>Does the image title attribute actually have to be in the database? If it's only the matter of displaying text, for example in the photo gallery, would't using a jQuery function serve your purpose? Something like:</p>\n\n<pre><code>$(document).ready(function() {\n $('img').each(function() {\n if ($(this).attr('title') === undefined) {\n var title = $('h1').text();\n $(this).attr('title', title);\n }\n });\n});\n</code></pre>\n" }, { "answer_id": 188560, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>You can try the following test plugin, that uses the <a href=\"http://php.net/manual/en/class.domdocument.php\" rel=\"nofollow noreferrer\"><code>domDocument</code></a> class, to see how it works on your HTML.</p>\n\n<p>It assumes PHP 5.4+ with LibXML 2.7.8+.</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Add Missing Image Title Attributes\n * Description: For posts in the main loop (Assumes PHP 5.4+ with LibXML 2.7.8+)\n * Plugin URI: http://wordpress.stackexchange.com/a/188560/26350\n * Author: Birgir Erlendsson (birgire)\n * Version: 0.0.1\n */\n\nnamespace wpse\\birgire;\n\nadd_action( 'init', function()\n{\n $o = new AddMissingImgTitle;\n $o-&gt;activate( new \\domDocument );\n} );\n\nclass AddMissingImgTitle\n{\n private $dom;\n\n public function activate( \\domDocument $dom )\n {\n $this-&gt;dom = $dom;\n add_filter( 'the_content', [ $this, 'the_content' ] );\n }\n\n public function the_content( $html )\n {\n if( ! in_the_loop() )\n return $html;\n\n if( false === strpos( $html, '&lt;img' ) )\n return $html;\n\n return $this-&gt;process( $html );\n } \n\n private function process( $html )\n {\n // Handle utf8 strings\n // See http://php.net/manual/en/domdocument.loadhtml.php#95251\n $html = '&lt;?xml encoding=\"UTF-8\"&gt;' . $html;\n\n // Load without HTML wrapper\n // See https://stackoverflow.com/a/22490902/2078474\n $this-&gt;dom-&gt;loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );\n\n // Fetch all image tags:\n $images = $this-&gt;dom-&gt;getElementsByTagName( 'img' );\n foreach ( $images as $image )\n {\n // Add the title attribute if it's missing (using the post title):\n if( '' === $image-&gt;getAttribute( 'title' ) )\n $image-&gt;setAttribute( 'title', esc_attr( get_the_title() ) );\n }\n return str_replace( '&lt;?xml encoding=\"UTF-8\"&gt;', '', $this-&gt;dom-&gt;saveHTML() );\n }\n\n} // end class\n</code></pre>\n\n<p>For older versions of LibXML, you can check out the answers to <a href=\"https://stackoverflow.com/questions/4879946/how-to-savehtml-of-domdocument-without-html-wrapper\">this question</a> for alternative ways without the <code>LIBXML_HTML_NOIMPLIED</code> and <code>LIBXML_HTML_NODEFDTD</code> options.</p>\n" }, { "answer_id": 188622, "author": "Anand", "author_id": 73187, "author_profile": "https://wordpress.stackexchange.com/users/73187", "pm_score": 0, "selected": false, "text": "<p>It means that you want to load that image on post right... \nplace the below code where you want images</p>\n\n<pre><code>&lt;?php\n$post_id = 75;\n$thumbnail_id = 112;\nif(!empty(get_the_title($thumbnail_id))){\n echo '&lt;img src=\"img.jpg\" title=\"'.get_the_title($thumbnail_id).'\" /&gt;';\n}\nelse{\n echo '&lt;img src=\"img.jpg\" title=\"'.get_the_title($post_id).'\" /&gt;';\n}\n\n?&gt; \n</code></pre>\n\n<p>i hope it will work for you...</p>\n" } ]
2015/05/08
[ "https://wordpress.stackexchange.com/questions/187773", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/30778/" ]
I have a client's site where they want to add image title attributes dynamically to images that don't have one already. So if the title attribute is empty, add a title of whatever the post title is. How would I accomplish this? Effectively: `<img src=img.jpg title=[wp-post-title-here] />`
You can try the following test plugin, that uses the [`domDocument`](http://php.net/manual/en/class.domdocument.php) class, to see how it works on your HTML. It assumes PHP 5.4+ with LibXML 2.7.8+. ``` <?php /** * Plugin Name: Add Missing Image Title Attributes * Description: For posts in the main loop (Assumes PHP 5.4+ with LibXML 2.7.8+) * Plugin URI: http://wordpress.stackexchange.com/a/188560/26350 * Author: Birgir Erlendsson (birgire) * Version: 0.0.1 */ namespace wpse\birgire; add_action( 'init', function() { $o = new AddMissingImgTitle; $o->activate( new \domDocument ); } ); class AddMissingImgTitle { private $dom; public function activate( \domDocument $dom ) { $this->dom = $dom; add_filter( 'the_content', [ $this, 'the_content' ] ); } public function the_content( $html ) { if( ! in_the_loop() ) return $html; if( false === strpos( $html, '<img' ) ) return $html; return $this->process( $html ); } private function process( $html ) { // Handle utf8 strings // See http://php.net/manual/en/domdocument.loadhtml.php#95251 $html = '<?xml encoding="UTF-8">' . $html; // Load without HTML wrapper // See https://stackoverflow.com/a/22490902/2078474 $this->dom->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); // Fetch all image tags: $images = $this->dom->getElementsByTagName( 'img' ); foreach ( $images as $image ) { // Add the title attribute if it's missing (using the post title): if( '' === $image->getAttribute( 'title' ) ) $image->setAttribute( 'title', esc_attr( get_the_title() ) ); } return str_replace( '<?xml encoding="UTF-8">', '', $this->dom->saveHTML() ); } } // end class ``` For older versions of LibXML, you can check out the answers to [this question](https://stackoverflow.com/questions/4879946/how-to-savehtml-of-domdocument-without-html-wrapper) for alternative ways without the `LIBXML_HTML_NOIMPLIED` and `LIBXML_HTML_NODEFDTD` options.