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
232,884
<p>I'm trying to add some custom HTML to specific WooCommerce products for my client. I successfully learned to add this custom HTML to all product pages at once (more specifically to their descriptions, overriding short-description.php) but I only need products A, B and C to contain this HTML bit and the rest to stay with the default content. A, B and C are in the same product category. How would you narrow the products, via category or product by product, that will contain this HTML, please?</p>
[ { "answer_id": 232879, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 4, "selected": true, "text": "<p>First off, it's always good to register shortcode during <code>init</code> versus just in your general <code>functions.php</code> file. At the very least <code>add_shortcode()</code> should be in <code>init</code>. Anyway, let's begin!</p>\n\n<p>Whenever you use <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"noreferrer\"><code>add_shortcode()</code></a> the first parameter is going to be the name of the shortcode and the 2nd will be the callback function. This means that:</p>\n\n<pre><code>[products line=\"prime\"]\n</code></pre>\n\n<p>Should be instead:</p>\n\n<pre><code>[produtos line=\"prime\"]\n</code></pre>\n\n<p>So far we have this:</p>\n\n<pre><code>/**\n * Register all shortcodes\n *\n * @return null\n */\nfunction register_shortcodes() {\n add_shortcode( 'produtos', 'shortcode_mostra_produtos' );\n}\nadd_action( 'init', 'register_shortcodes' );\n\n/**\n * Produtos Shortcode Callback\n * - [produtos]\n * \n * @param Array $atts\n *\n * @return string\n */\nfunction shortcode_mostra_produtos( $atts ) {\n /** Our outline will go here\n}\n</code></pre>\n\n<p>Let's take a look at processing attributes. The way <a href=\"https://codex.wordpress.org/Function_Reference/shortcode_atts\" rel=\"noreferrer\"><code>shortcode_atts()</code></a> works is that it will try to match attributes passed to the shortcode with attributes in the passed array, left side being the key and the right side being the defaults. So we need to change <code>defaults</code> to <code>line</code> instead - if we want to default to a category, this would be the place:</p>\n\n<pre><code>$atts = shortcode_atts( array(\n 'line' =&gt; ''\n), $atts );\n</code></pre>\n\n<p>IF the user adds a attribute to the shortcode <code>line=\"test\"</code> then our array index <code>line</code> will hold <code>test</code>: </p>\n\n<pre><code>echo $atts['line']; // Prints 'test'\n</code></pre>\n\n<p>All other attributes will be ignored unless we add them to the <code>shortcode_atts()</code> array. Finally it's just the WP_Query and printing what you need:</p>\n\n<pre><code>/**\n * Register all shortcodes\n *\n * @return null\n */\nfunction register_shortcodes() {\n add_shortcode( 'produtos', 'shortcode_mostra_produtos' );\n}\nadd_action( 'init', 'register_shortcodes' );\n\n/**\n * Produtos Shortcode Callback\n * \n * @param Array $atts\n *\n * @return string\n */\nfunction shortcode_mostra_produtos( $atts ) {\n global $wp_query,\n $post;\n\n $atts = shortcode_atts( array(\n 'line' =&gt; ''\n ), $atts );\n\n $loop = new WP_Query( array(\n 'posts_per_page' =&gt; 200,\n 'post_type' =&gt; 'produtos',\n 'orderby' =&gt; 'menu_order title',\n 'order' =&gt; 'ASC',\n 'tax_query' =&gt; array( array(\n 'taxonomy' =&gt; 'linhas',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( sanitize_title( $atts['line'] ) )\n ) )\n ) );\n\n if( ! $loop-&gt;have_posts() ) {\n return false;\n }\n\n while( $loop-&gt;have_posts() ) {\n $loop-&gt;the_post();\n echo the_title();\n }\n\n wp_reset_postdata();\n}\n</code></pre>\n" }, { "answer_id": 270652, "author": "Vivek Tamrakar", "author_id": 96956, "author_profile": "https://wordpress.stackexchange.com/users/96956", "pm_score": -1, "selected": false, "text": "<p>**Try this **</p>\n\n<pre><code>function shortcode_bws_quiz_maker($id)\n{\n if($id!='')\n {\n $post_id=$id[0];\n $html='';\n global $wpdb;\n $args=array('post_type'=&gt;'post_type','p'=&gt;$post_id);\n $wp_posts=new WP_Query($args);\n $posts=$wp_posts-&gt;posts;\n $html.=\"What you to get write here\";\n return $html;\n\n }\n else\n {\n return 'Please enter correct shortcode'; \n }\n\n}\nadd_shortcode('bws_quiz_maker','shortcode_bws_quiz_maker');\n</code></pre>\n" }, { "answer_id": 318370, "author": "Pradeep", "author_id": 145348, "author_profile": "https://wordpress.stackexchange.com/users/145348", "pm_score": 0, "selected": false, "text": "<pre><code> add_shortcode( 'product-list','bpo_product_list' );\nfunction bpo_product_list ( $atts ) {\n $atts = shortcode_atts( array(\n 'category' =&gt; ''\n ), $atts );\n $terms = get_terms('product_category');\n wp_reset_query();\n $args = array('post_type' =&gt; 'product',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'product_category',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $atts,\n ),\n ),\n );\n $loop = new WP_Query($args);\n if($loop-&gt;have_posts()) {\n while($loop-&gt;have_posts()) : $loop-&gt;the_post();\n echo ' \"'.get_the_title().'\" ';\n endwhile;\n }\n\n else {\n echo 'Sorry, no posts were found';\n }\n}\n</code></pre>\n\n<p>In above code, I have created product CPT and product_category taxonomy for product CPT. </p>\n\n<p>[product-list category=\"shirts\"]</p>\n\n<p>The above code is perfectly works!</p>\n" } ]
2016/07/21
[ "https://wordpress.stackexchange.com/questions/232884", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98727/" ]
I'm trying to add some custom HTML to specific WooCommerce products for my client. I successfully learned to add this custom HTML to all product pages at once (more specifically to their descriptions, overriding short-description.php) but I only need products A, B and C to contain this HTML bit and the rest to stay with the default content. A, B and C are in the same product category. How would you narrow the products, via category or product by product, that will contain this HTML, please?
First off, it's always good to register shortcode during `init` versus just in your general `functions.php` file. At the very least `add_shortcode()` should be in `init`. Anyway, let's begin! Whenever you use [`add_shortcode()`](https://codex.wordpress.org/Function_Reference/add_shortcode) the first parameter is going to be the name of the shortcode and the 2nd will be the callback function. This means that: ``` [products line="prime"] ``` Should be instead: ``` [produtos line="prime"] ``` So far we have this: ``` /** * Register all shortcodes * * @return null */ function register_shortcodes() { add_shortcode( 'produtos', 'shortcode_mostra_produtos' ); } add_action( 'init', 'register_shortcodes' ); /** * Produtos Shortcode Callback * - [produtos] * * @param Array $atts * * @return string */ function shortcode_mostra_produtos( $atts ) { /** Our outline will go here } ``` Let's take a look at processing attributes. The way [`shortcode_atts()`](https://codex.wordpress.org/Function_Reference/shortcode_atts) works is that it will try to match attributes passed to the shortcode with attributes in the passed array, left side being the key and the right side being the defaults. So we need to change `defaults` to `line` instead - if we want to default to a category, this would be the place: ``` $atts = shortcode_atts( array( 'line' => '' ), $atts ); ``` IF the user adds a attribute to the shortcode `line="test"` then our array index `line` will hold `test`: ``` echo $atts['line']; // Prints 'test' ``` All other attributes will be ignored unless we add them to the `shortcode_atts()` array. Finally it's just the WP\_Query and printing what you need: ``` /** * Register all shortcodes * * @return null */ function register_shortcodes() { add_shortcode( 'produtos', 'shortcode_mostra_produtos' ); } add_action( 'init', 'register_shortcodes' ); /** * Produtos Shortcode Callback * * @param Array $atts * * @return string */ function shortcode_mostra_produtos( $atts ) { global $wp_query, $post; $atts = shortcode_atts( array( 'line' => '' ), $atts ); $loop = new WP_Query( array( 'posts_per_page' => 200, 'post_type' => 'produtos', 'orderby' => 'menu_order title', 'order' => 'ASC', 'tax_query' => array( array( 'taxonomy' => 'linhas', 'field' => 'slug', 'terms' => array( sanitize_title( $atts['line'] ) ) ) ) ) ); if( ! $loop->have_posts() ) { return false; } while( $loop->have_posts() ) { $loop->the_post(); echo the_title(); } wp_reset_postdata(); } ```
232,891
<p>My error log is showing many instances of: PHP Warning: Invalid argument supplied for foreach() in \wp-admin\includes\plugin.php on line 1415</p> <p>How do I go about determining which plugin (and which page/line of that plugin) is causing this? Is there a mechanism in place, or do I have to trial and error it?</p>
[ { "answer_id": 232897, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>In your <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow\"><code>wp-config.php</code></a> make sure to include;</p>\n\n<pre><code>define( 'WP_DEBUG', true );\ndefine( 'WP_DEBUG_DISPLAY', true );\n</code></pre>\n\n<p>Sometimes your environment will do a better job at outputting the stack trace.</p>\n\n<p>If that doesn't work, you can go that line in WP core and add;</p>\n\n<pre><code>$backtrace = debug_backtrace();\n\nprint('&lt;pre&gt;');\nprint_r ( $backtrace );\n</code></pre>\n\n<p>That should give you a lot more information to go off of, for example;</p>\n\n<pre><code>/*\nArray\n(\n [0] =&gt; Array\n (\n [file] =&gt; /site/wp-content/plugins/debug-bar-console/class-debug-bar-console.php\n [line] =&gt; 84\n [function] =&gt; eval\n )\n\n [1] =&gt; Array\n (\n [function] =&gt; ajax\n [class] =&gt; Debug_Bar_Console\n [object] =&gt; Debug_Bar_Console Object\n (\n [_title] =&gt; Console\n [_visible] =&gt; 1\n )\n\n [type] =&gt; -&gt;\n [args] =&gt; Array\n (\n [0] =&gt; \n )\n\n )\n\n [2] =&gt; Array\n (\n [file] =&gt; /site/wp-includes/plugin.php\n [line] =&gt; 525\n [function] =&gt; call_user_func_array\n [args] =&gt; Array\n (\n [0] =&gt; Array\n (\n [0] =&gt; Debug_Bar_Console Object\n (\n [_title] =&gt; Console\n [_visible] =&gt; 1\n )\n\n [1] =&gt; ajax\n )\n\n [1] =&gt; Array\n (\n [0] =&gt; \n )\n\n )\n\n )\n\n [3] =&gt; Array\n (\n [file] =&gt; /site/wp-admin/admin-ajax.php\n [line] =&gt; 89\n [function] =&gt; do_action\n [args] =&gt; Array\n (\n [0] =&gt; wp_ajax_debug_bar_console\n )\n\n )\n\n)\n*/\n</code></pre>\n" }, { "answer_id": 232920, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>Since it is just debugging you could temporarily edit the function in plugins.php which is throwing the error and put in the first line of that function:</p>\n\n<pre><code>echo \"&lt;!--\"; var_dump(func_get_args()); echo \"--&gt;\";\n</code></pre>\n\n<p>Then view the page source it should let you know more and the debug info will be output above the error messages they relate to. And of course remove the line when you are done.</p>\n" } ]
2016/07/21
[ "https://wordpress.stackexchange.com/questions/232891", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98734/" ]
My error log is showing many instances of: PHP Warning: Invalid argument supplied for foreach() in \wp-admin\includes\plugin.php on line 1415 How do I go about determining which plugin (and which page/line of that plugin) is causing this? Is there a mechanism in place, or do I have to trial and error it?
In your [`wp-config.php`](https://codex.wordpress.org/Debugging_in_WordPress) make sure to include; ``` define( 'WP_DEBUG', true ); define( 'WP_DEBUG_DISPLAY', true ); ``` Sometimes your environment will do a better job at outputting the stack trace. If that doesn't work, you can go that line in WP core and add; ``` $backtrace = debug_backtrace(); print('<pre>'); print_r ( $backtrace ); ``` That should give you a lot more information to go off of, for example; ``` /* Array ( [0] => Array ( [file] => /site/wp-content/plugins/debug-bar-console/class-debug-bar-console.php [line] => 84 [function] => eval ) [1] => Array ( [function] => ajax [class] => Debug_Bar_Console [object] => Debug_Bar_Console Object ( [_title] => Console [_visible] => 1 ) [type] => -> [args] => Array ( [0] => ) ) [2] => Array ( [file] => /site/wp-includes/plugin.php [line] => 525 [function] => call_user_func_array [args] => Array ( [0] => Array ( [0] => Debug_Bar_Console Object ( [_title] => Console [_visible] => 1 ) [1] => ajax ) [1] => Array ( [0] => ) ) ) [3] => Array ( [file] => /site/wp-admin/admin-ajax.php [line] => 89 [function] => do_action [args] => Array ( [0] => wp_ajax_debug_bar_console ) ) ) */ ```
232,893
<p>I would like to swap out image URLs upon post submission on both <code>content editor</code> field and a custom field <code>cover_image</code> of a custom post type <code>article</code>.</p> <p>For example, the original content may contain image url such as:</p> <pre><code>&lt;img src="http://original-domain.com/gallery/2016/01/01/filename.jpg"&gt; </code></pre> <p>I would like to swap it to:</p> <pre><code>&lt;img src="http://new-domain.com/album/20160101/filename.jpg"&gt; </code></pre> <p>And have it stored permanently to the database.</p> <p>How to edit the regular expression is not my concern, but where to make the edit to insert the regular expression is what would like to know.</p> <p>Is there some kind of filter that I can use on post submission?</p>
[ { "answer_id": 232896, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/hooks/image_send_to_editor/\" rel=\"nofollow\"><code>image_send_to_editor</code></a> hook will handle when the image is sent to the editor. The problem will be that your editor may not work correctly when you modify the URL -- use with caution.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow\"><code>save_post</code></a> will allow you to modify the <code>$post</code> content on save.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/update_(meta_type)_metadata\" rel=\"nofollow\"><code>update_(meta_type)_metadata</code></a> could be used to intercept when the meta data is saved.</p>\n" }, { "answer_id": 233146, "author": "KDX", "author_id": 92505, "author_profile": "https://wordpress.stackexchange.com/users/92505", "pm_score": 1, "selected": true, "text": "<p><code>save_post</code> didn't work for me.</p>\n\n<p>What works in my situation is using <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/content_save_pre\" rel=\"nofollow\">content_save_pre</a> filter or the content processing before save.</p>\n\n<p>Since I'm using <code>Advanced Custom Field</code> plugin for my <code>cover_image</code> field, and I ended up using <code>acf/save_post</code> filter to process the field.</p>\n" } ]
2016/07/22
[ "https://wordpress.stackexchange.com/questions/232893", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92505/" ]
I would like to swap out image URLs upon post submission on both `content editor` field and a custom field `cover_image` of a custom post type `article`. For example, the original content may contain image url such as: ``` <img src="http://original-domain.com/gallery/2016/01/01/filename.jpg"> ``` I would like to swap it to: ``` <img src="http://new-domain.com/album/20160101/filename.jpg"> ``` And have it stored permanently to the database. How to edit the regular expression is not my concern, but where to make the edit to insert the regular expression is what would like to know. Is there some kind of filter that I can use on post submission?
`save_post` didn't work for me. What works in my situation is using [content\_save\_pre](https://codex.wordpress.org/Plugin_API/Filter_Reference/content_save_pre) filter or the content processing before save. Since I'm using `Advanced Custom Field` plugin for my `cover_image` field, and I ended up using `acf/save_post` filter to process the field.
232,901
<p>Hey WordPress friends,</p> <p>I’m using the Disqus comment system plugin, which is working fine. My homepage is just a collection if recent posts and therefore not having the option to leave a comment (as desired).</p> <p>Unfortunately, I still see that the Disqus plugin is rendering JavaScript output within the homepage and would like to get rid of this.</p> <p>I've Tried the following but without luck. Any help is appreciated! Thanks</p> <pre><code>function block_disqus_count() { if ( is_front_page()) remove_filter('output_count_js', 'dsq_output_count_js'); } add_action( 'block_disqus_count' , 'block_disqus_count'); </code></pre>
[ { "answer_id": 232907, "author": "Kevin Bronsdijk", "author_id": 98737, "author_profile": "https://wordpress.stackexchange.com/users/98737", "pm_score": 0, "selected": false, "text": "<p>Solved it by altering the file disqus.php. First find function</p>\n\n<pre><code>function dsq_output_count_js() {\n</code></pre>\n\n<p>Add the following check before the function tries to output the JS</p>\n\n<pre><code> if ( ! is_front_page() ) { ?&gt; &lt;script type=\"text/javascript\"&gt; \n</code></pre>\n\n<p>I’m using this until Disqus created the option to configure this. Thanks for the help.</p>\n" }, { "answer_id": 312367, "author": "Pbinder", "author_id": 50930, "author_profile": "https://wordpress.stackexchange.com/users/50930", "pm_score": 1, "selected": false, "text": "<p>You should deregister it. Add this function into your functions.php:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'disqus_scripts' );\n\nfunction disqus_scripts() {\n if(is_front_page()) {\n wp_deregister_script('disqus_count');\n }\n}\n</code></pre>\n" } ]
2016/07/22
[ "https://wordpress.stackexchange.com/questions/232901", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98737/" ]
Hey WordPress friends, I’m using the Disqus comment system plugin, which is working fine. My homepage is just a collection if recent posts and therefore not having the option to leave a comment (as desired). Unfortunately, I still see that the Disqus plugin is rendering JavaScript output within the homepage and would like to get rid of this. I've Tried the following but without luck. Any help is appreciated! Thanks ``` function block_disqus_count() { if ( is_front_page()) remove_filter('output_count_js', 'dsq_output_count_js'); } add_action( 'block_disqus_count' , 'block_disqus_count'); ```
You should deregister it. Add this function into your functions.php: ``` add_action( 'wp_enqueue_scripts', 'disqus_scripts' ); function disqus_scripts() { if(is_front_page()) { wp_deregister_script('disqus_count'); } } ```
232,934
<p><strong>Update</strong> i have fix the first problem by changing the strectures in sending datas to database, now my problem is that when i select multiple choices and click submit only one of the choices is updated in database (exactly the first one ordering by id) my new Code is belew my old code, by the way i have add</p> <pre><code>echo $cam; </code></pre> <p>to verfy if its looping correctly and yes it does, the only issue is that in database it dont update all the choices entren only one of it</p> <p><strong>My orginal post</strong></p> <blockquote> <p>I'm trying to update a custom database table for my WordPress plugin. I'm firstly getting the roles from my table, then displaying it using a form. This works fine. When I check the boxes it updates in the database, but when I uncheck them, it doesn't update at all - and I get this error message:</p> <p>Warning: Invalid argument supplied for foreach() in C:\wamp\www\wp_test\wp-content\plugins\Data\settings.php on line 52</p> <p>Here's my code. Where am I going wrong?</p> </blockquote> <pre><code>&lt;?php $roles=get_editable_roles(); global $wpdb; $table_name = $wpdb-&gt;prefix. "Author_detailed_repport"; ?&gt; &lt;h3&gt;Settings Page&lt;/h3&gt; &lt;h4&gt;Add/Remove a role from filter list&lt;/h4&gt; &lt;p&gt;This setting allow you to add/remove roles from the filter&lt;br /&gt; list, here down a list of all the roles existing in your website, all&lt;br /&gt; you have to do is to check/uncheck wich you wanna add/rmove from filter list&lt;/p&gt; &lt;form action="&lt;?php $_REQUEST['PHP_SELF'] ?&gt;" method="post"&gt; &lt;?php require_once('../wp-config.php'); $i=0; foreach($roles as $role) { $rom=$role['name']; $results = $wpdb-&gt;get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" ); if ($results==NULL) {$wpdb-&gt;insert( $table_name, array( 'role' =&gt; $role['name'], 'statut' =&gt; '', 'post_number' =&gt; '', 'activate' =&gt; '' )); }?&gt; &lt;input type="checkbox" name="cat[]" value="&lt;?php echo $i+1 ;?&gt;" &lt;?php checked($results[0]-&gt;statut, $i+1); ?&gt; /&gt; &lt;input type="hidden" name="ww" value="0"&gt; &lt;?php ?&gt; &lt;label&gt; &lt;?php echo $results[0]-&gt;role;?&gt;&lt;/label&gt;&lt;br /&gt; &lt;?php $i++; } ?&gt; &lt;input type="submit" value="save" name="saveme" /&gt; &lt;/form&gt; &lt;?php if(isset($_POST['saveme'])) { $cats=$_POST['cat']; foreach($cats as $cam) { if(isset($cam)) { $wpdb-&gt;update( $table_name, array( 'statut' =&gt; $cam ),array('ADR_id' =&gt; $cam),array('%d'));} else { $wpdb-&gt;update( $table_name, array( 'statut' =&gt; '0' ),array('ADR_id' =&gt; $cam),array('%d')); } } } ?&gt; </code></pre> <p><strong>UPDATE</strong></p> <pre><code>&lt;?php $roles=get_editable_roles(); global $wpdb; $table_name = $wpdb-&gt;prefix. "Author_detailed_repport"; ?&gt; &lt;h3&gt;Settings Page&lt;/h3&gt; &lt;h4&gt;Add/Remove a role from filter list&lt;/h4&gt; &lt;p&gt;This setting allow you to add/remove roles from the filter&lt;br /&gt; list, here down a list of all the roles existing in your website, all&lt;br /&gt; you have to do is to check/uncheck wich you wanna add/rmove from filter list&lt;/p&gt; &lt;form action="&lt;?php $_REQUEST['PHP_SELF'] ?&gt;" method="post"&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;strong&gt;List of activated roles&lt;/strong&gt;&lt;/legend&gt; &lt;ul&gt; &lt;?php require_once('../wp-config.php'); $i=0; foreach($roles as $role) { $rom=$role['name']; $results = $wpdb-&gt;get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" ); if ($results==NULL) {$wpdb-&gt;insert( $table_name, array( 'role' =&gt; $role['name'], 'statut' =&gt; '', 'post_number' =&gt; '', 'activate' =&gt; '' )); }?&gt; &lt;?php if($results[0]-&gt;ADR_id==$results[0]-&gt;statut) {?&gt; &lt;li&gt;&lt;input type="checkbox" value="&lt;?php echo $results[0]-&gt;ADR_id*2; ?&gt;" name="rm[]" /&gt;&lt;label&gt;&lt;?php echo $results[0]-&gt;role;?&gt;&lt;/label&gt;&lt;/li&gt; &lt;?php }} ?&gt; &lt;/ul&gt; &lt;input type="submit" value="remove" name="remove" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;form action="&lt;?php $_REQUEST['PHP_SELF'] ?&gt;" method="post"&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;strong&gt;List of deactivated roles&lt;/strong&gt;&lt;/legend&gt; &lt;ul&gt; &lt;?php require_once('../wp-config.php'); $i=0; foreach($roles as $role) { $rom=$role['name']; $results = $wpdb-&gt;get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" ); if ($results==NULL) {$wpdb-&gt;insert( $table_name, array( 'role' =&gt; $role['name'], 'statut' =&gt; '', 'post_number' =&gt; '', 'activate' =&gt; '' )); }?&gt; &lt;?php if($results[0]-&gt;ADR_id!=$results[0]-&gt;statut) {?&gt; &lt;li&gt;&lt;input type="checkbox" value="&lt;?php echo $results[0]-&gt;ADR_id; ?&gt;" name="ad[]" /&gt;&lt;label&gt;&lt;?php echo $results[0]-&gt;role;?&gt;&lt;/label&gt;&lt;/li&gt; &lt;?php }} ?&gt; &lt;/ul&gt; &lt;input type="submit" value="Add" name="add" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;?php if(isset($_POST['remove'])) { if(isset($_POST['rm'])){ $cam=implode(",",$_POST['rm']); $wpdb-&gt;update( $table_name, array( 'statut' =&gt; $cam ),array('ADR_id' =&gt; $cam/2),array('%d')); echo $cam; } else{ $cam='';exit();} } if(isset($_POST['add'])) { if(isset($_POST['ad'])){ $cam=implode(",",$_POST['ad']); echo $cam; $wpdb-&gt;update( $table_name, array( 'statut' =&gt; $cam ),array('ADR_id' =&gt; $cam),array('%d'));} else{ $cam='';exit(); } } ?&gt; </code></pre>
[ { "answer_id": 232907, "author": "Kevin Bronsdijk", "author_id": 98737, "author_profile": "https://wordpress.stackexchange.com/users/98737", "pm_score": 0, "selected": false, "text": "<p>Solved it by altering the file disqus.php. First find function</p>\n\n<pre><code>function dsq_output_count_js() {\n</code></pre>\n\n<p>Add the following check before the function tries to output the JS</p>\n\n<pre><code> if ( ! is_front_page() ) { ?&gt; &lt;script type=\"text/javascript\"&gt; \n</code></pre>\n\n<p>I’m using this until Disqus created the option to configure this. Thanks for the help.</p>\n" }, { "answer_id": 312367, "author": "Pbinder", "author_id": 50930, "author_profile": "https://wordpress.stackexchange.com/users/50930", "pm_score": 1, "selected": false, "text": "<p>You should deregister it. Add this function into your functions.php:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'disqus_scripts' );\n\nfunction disqus_scripts() {\n if(is_front_page()) {\n wp_deregister_script('disqus_count');\n }\n}\n</code></pre>\n" } ]
2016/07/22
[ "https://wordpress.stackexchange.com/questions/232934", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98757/" ]
**Update** i have fix the first problem by changing the strectures in sending datas to database, now my problem is that when i select multiple choices and click submit only one of the choices is updated in database (exactly the first one ordering by id) my new Code is belew my old code, by the way i have add ``` echo $cam; ``` to verfy if its looping correctly and yes it does, the only issue is that in database it dont update all the choices entren only one of it **My orginal post** > > I'm trying to update a custom database table for my WordPress plugin. > I'm firstly getting the roles from my table, then displaying it using a form. This works fine. When I check the boxes it updates in > the database, but when I uncheck them, it doesn't update at all - and > I get this error message: > > > Warning: Invalid argument supplied for foreach() in > C:\wamp\www\wp\_test\wp-content\plugins\Data\settings.php on line 52 > > > Here's my code. Where am I going wrong? > > > ``` <?php $roles=get_editable_roles(); global $wpdb; $table_name = $wpdb->prefix. "Author_detailed_repport"; ?> <h3>Settings Page</h3> <h4>Add/Remove a role from filter list</h4> <p>This setting allow you to add/remove roles from the filter<br /> list, here down a list of all the roles existing in your website, all<br /> you have to do is to check/uncheck wich you wanna add/rmove from filter list</p> <form action="<?php $_REQUEST['PHP_SELF'] ?>" method="post"> <?php require_once('../wp-config.php'); $i=0; foreach($roles as $role) { $rom=$role['name']; $results = $wpdb->get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" ); if ($results==NULL) {$wpdb->insert( $table_name, array( 'role' => $role['name'], 'statut' => '', 'post_number' => '', 'activate' => '' )); }?> <input type="checkbox" name="cat[]" value="<?php echo $i+1 ;?>" <?php checked($results[0]->statut, $i+1); ?> /> <input type="hidden" name="ww" value="0"> <?php ?> <label> <?php echo $results[0]->role;?></label><br /> <?php $i++; } ?> <input type="submit" value="save" name="saveme" /> </form> <?php if(isset($_POST['saveme'])) { $cats=$_POST['cat']; foreach($cats as $cam) { if(isset($cam)) { $wpdb->update( $table_name, array( 'statut' => $cam ),array('ADR_id' => $cam),array('%d'));} else { $wpdb->update( $table_name, array( 'statut' => '0' ),array('ADR_id' => $cam),array('%d')); } } } ?> ``` **UPDATE** ``` <?php $roles=get_editable_roles(); global $wpdb; $table_name = $wpdb->prefix. "Author_detailed_repport"; ?> <h3>Settings Page</h3> <h4>Add/Remove a role from filter list</h4> <p>This setting allow you to add/remove roles from the filter<br /> list, here down a list of all the roles existing in your website, all<br /> you have to do is to check/uncheck wich you wanna add/rmove from filter list</p> <form action="<?php $_REQUEST['PHP_SELF'] ?>" method="post"> <fieldset> <legend><strong>List of activated roles</strong></legend> <ul> <?php require_once('../wp-config.php'); $i=0; foreach($roles as $role) { $rom=$role['name']; $results = $wpdb->get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" ); if ($results==NULL) {$wpdb->insert( $table_name, array( 'role' => $role['name'], 'statut' => '', 'post_number' => '', 'activate' => '' )); }?> <?php if($results[0]->ADR_id==$results[0]->statut) {?> <li><input type="checkbox" value="<?php echo $results[0]->ADR_id*2; ?>" name="rm[]" /><label><?php echo $results[0]->role;?></label></li> <?php }} ?> </ul> <input type="submit" value="remove" name="remove" /> </fieldset> </form> <form action="<?php $_REQUEST['PHP_SELF'] ?>" method="post"> <fieldset> <legend><strong>List of deactivated roles</strong></legend> <ul> <?php require_once('../wp-config.php'); $i=0; foreach($roles as $role) { $rom=$role['name']; $results = $wpdb->get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" ); if ($results==NULL) {$wpdb->insert( $table_name, array( 'role' => $role['name'], 'statut' => '', 'post_number' => '', 'activate' => '' )); }?> <?php if($results[0]->ADR_id!=$results[0]->statut) {?> <li><input type="checkbox" value="<?php echo $results[0]->ADR_id; ?>" name="ad[]" /><label><?php echo $results[0]->role;?></label></li> <?php }} ?> </ul> <input type="submit" value="Add" name="add" /> </fieldset> </form> <?php if(isset($_POST['remove'])) { if(isset($_POST['rm'])){ $cam=implode(",",$_POST['rm']); $wpdb->update( $table_name, array( 'statut' => $cam ),array('ADR_id' => $cam/2),array('%d')); echo $cam; } else{ $cam='';exit();} } if(isset($_POST['add'])) { if(isset($_POST['ad'])){ $cam=implode(",",$_POST['ad']); echo $cam; $wpdb->update( $table_name, array( 'statut' => $cam ),array('ADR_id' => $cam),array('%d'));} else{ $cam='';exit(); } } ?> ```
You should deregister it. Add this function into your functions.php: ``` add_action( 'wp_enqueue_scripts', 'disqus_scripts' ); function disqus_scripts() { if(is_front_page()) { wp_deregister_script('disqus_count'); } } ```
233,003
<p>I tried to create a table output with the content of a custom post.</p> <p>I can echo my city properly:</p> <pre><code>&lt;span style="font-weight: bold;"&gt;city: &lt;/span&gt; &lt;?php echo get_post_meta($post-&gt;ID, 'ptn_plaats', true);?&gt; </code></pre> <p>But with this next line I get echo me ARRAY instead one of the options !!</p> <pre><code>&lt;span style="font-weight: bold;"&gt;Systeem :&lt;/span&gt; &lt;?php echo get_post_meta($post-&gt;ID, 'ptn_systeem', true);;?&gt; </code></pre> <p>How can I echo the contents of my custom post type?</p>
[ { "answer_id": 233004, "author": "Emran", "author_id": 98806, "author_profile": "https://wordpress.stackexchange.com/users/98806", "pm_score": 2, "selected": true, "text": "<p>You got ARRAY echos because you saved array on post meta,</p>\n\n<p>Just check array values of meta data like:</p>\n\n<pre><code>print_r( get_post_meta($post-&gt;ID, 'ptn_systeem', true) );\n</code></pre>\n\n<p>and echo it like:</p>\n\n<pre><code>foreach( (array) get_post_meta($post-&gt;ID, 'ptn_systeem', true) as $option):\n\n echo $option . \"&lt;br&gt;\";\n\nendforeach;\n</code></pre>\n" }, { "answer_id": 233007, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 0, "selected": false, "text": "<p>Please go through serialize array concept in wp.In your postmeta it is storing data in serialised form if you are getting an array. Either you can loop through the array or to fetch a single record use the array key.</p>\n" } ]
2016/07/23
[ "https://wordpress.stackexchange.com/questions/233003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98731/" ]
I tried to create a table output with the content of a custom post. I can echo my city properly: ``` <span style="font-weight: bold;">city: </span> <?php echo get_post_meta($post->ID, 'ptn_plaats', true);?> ``` But with this next line I get echo me ARRAY instead one of the options !! ``` <span style="font-weight: bold;">Systeem :</span> <?php echo get_post_meta($post->ID, 'ptn_systeem', true);;?> ``` How can I echo the contents of my custom post type?
You got ARRAY echos because you saved array on post meta, Just check array values of meta data like: ``` print_r( get_post_meta($post->ID, 'ptn_systeem', true) ); ``` and echo it like: ``` foreach( (array) get_post_meta($post->ID, 'ptn_systeem', true) as $option): echo $option . "<br>"; endforeach; ```
233,008
<p>I have a problem with a loop that I try to put into a custom Page template. I would like to display posts with conditions, but whatever I put in my WP_query parameters, it is not taking in consideration.</p> <p>Here is all my template code:</p> <pre><code>&lt;?php /* Template Name: Trends */ get_header(); ?&gt; &lt;section id="top"&gt; &lt;?php the_post(); ?&gt; &lt;div class="intro"&gt;&lt;?= get_the_title(); ?&gt;&lt;/div&gt; &lt;?php the_content();?&gt; &lt;?php $args = array( 'posts_per_page' =&gt; 2 ); $latest = new WP_Query( $args ); ?&gt; &lt;?php while( $latest-&gt;have_posts() ) : $latest-&gt;the_post(); ?&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; &lt;/section&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>This code gives me all my posts, and not only the 2 I asked on args. But whatever I put it always gives me the default loop...</p> <p>I've tried everything and I still don't understand.</p> <p>Thanks for your help!</p> <p>** <strong>EDIT</strong> **</p> <p>This code works:</p> <pre><code>$query = new WP_Query(array( 'p' =&gt; 42 )); </code></pre> <p>But this one don't:</p> <pre><code>$query = new WP_Query(array( 'post__in' =&gt; $post_ids, 'post_status' =&gt; 'publish', 'ignore_sticky_posts' =&gt; false, 'orderby' =&gt; 'post__in', 'posts_per_page' =&gt; 2 )); </code></pre> <p>Whatever I put in my array, it doesn't works even if it is a <code>p</code> parameter. The second <code>$query</code> displays all my posts.</p>
[ { "answer_id": 233004, "author": "Emran", "author_id": 98806, "author_profile": "https://wordpress.stackexchange.com/users/98806", "pm_score": 2, "selected": true, "text": "<p>You got ARRAY echos because you saved array on post meta,</p>\n\n<p>Just check array values of meta data like:</p>\n\n<pre><code>print_r( get_post_meta($post-&gt;ID, 'ptn_systeem', true) );\n</code></pre>\n\n<p>and echo it like:</p>\n\n<pre><code>foreach( (array) get_post_meta($post-&gt;ID, 'ptn_systeem', true) as $option):\n\n echo $option . \"&lt;br&gt;\";\n\nendforeach;\n</code></pre>\n" }, { "answer_id": 233007, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 0, "selected": false, "text": "<p>Please go through serialize array concept in wp.In your postmeta it is storing data in serialised form if you are getting an array. Either you can loop through the array or to fetch a single record use the array key.</p>\n" } ]
2016/07/23
[ "https://wordpress.stackexchange.com/questions/233008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98764/" ]
I have a problem with a loop that I try to put into a custom Page template. I would like to display posts with conditions, but whatever I put in my WP\_query parameters, it is not taking in consideration. Here is all my template code: ``` <?php /* Template Name: Trends */ get_header(); ?> <section id="top"> <?php the_post(); ?> <div class="intro"><?= get_the_title(); ?></div> <?php the_content();?> <?php $args = array( 'posts_per_page' => 2 ); $latest = new WP_Query( $args ); ?> <?php while( $latest->have_posts() ) : $latest->the_post(); ?> <h2><?php the_title(); ?></h2> <?php endwhile; wp_reset_postdata(); ?> </section> <?php get_footer(); ?> ``` This code gives me all my posts, and not only the 2 I asked on args. But whatever I put it always gives me the default loop... I've tried everything and I still don't understand. Thanks for your help! \*\* **EDIT** \*\* This code works: ``` $query = new WP_Query(array( 'p' => 42 )); ``` But this one don't: ``` $query = new WP_Query(array( 'post__in' => $post_ids, 'post_status' => 'publish', 'ignore_sticky_posts' => false, 'orderby' => 'post__in', 'posts_per_page' => 2 )); ``` Whatever I put in my array, it doesn't works even if it is a `p` parameter. The second `$query` displays all my posts.
You got ARRAY echos because you saved array on post meta, Just check array values of meta data like: ``` print_r( get_post_meta($post->ID, 'ptn_systeem', true) ); ``` and echo it like: ``` foreach( (array) get_post_meta($post->ID, 'ptn_systeem', true) as $option): echo $option . "<br>"; endforeach; ```
233,035
<p>I have a XML file that consist of product information.</p> <p>Format of XML file : </p> <pre><code>&lt;product&gt; &lt;name&gt;Product-1&lt;/name&gt; &lt;description&gt;this is product 1 description&lt;/description&gt; &lt;category&gt;Category-1&lt;category&gt; &lt;merchant&gt;1234&lt;/merchant&gt; &lt;price&gt;12&lt;/price&gt; &lt;instock&gt;1&lt;instock&gt; &lt;stockstatus&gt;45&lt;/stockstatus&gt; &lt;image&gt;http://www.example.com/1.jpg&lt;/image&gt; &lt;manufacture&gt;987&lt;/manufacture&gt; &lt;/product&gt; </code></pre> <p>I need to write a script that will add these detail as a product. For now I am not using any WP plugin for eCommerce purpose.</p> <p>I am planning to create a custom post type as <strong>wpproduct</strong> that will store these products details.</p> <p>So for now I can use <code>name</code> as <code>post title</code>, <code>description</code> as <code>post content</code> and <code>image</code> as <code>post thumbnail</code>. And for storing the meta data I can store it in <code>postmeta</code> table.</p> <p>So I can create the post by using <code>wp_insert_post</code> and whatever <code>ID</code> it will return, I will use that ID in <code>update_post_meta</code> to update the meta data such as price, stock status , stock quantity, manufacturer etc.</p> <p>Like this it can be done..</p> <h1> Main Concern </h1> <p>So for a single product I need to write 1 <code>wp_insert_post</code> and then 6 <code>update_meta_data</code> query. So 7 query for 1 product. Not exactly 7 query as WP inbuilt function uses many query for validation check.</p> <p>What will happen if my XML file has 1 lakh product. So for adding 1 lakh product 7 lakh mysql query will run.</p> <h1> Assumption</h1> <p>I am just eager to know like can I add custom column in WP wp_posts table so that I can add 1 product in 1 query only. I might use raw mysql query to add it.</p> <p>Please help me and guide the best way to do it.</p> <p>Thanks</p>
[ { "answer_id": 233037, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 1, "selected": false, "text": "<p>I've checked and WordPress does, by default, retrieve &amp; cache all post meta along with the main query's posts, so you're perfectly fine storing a product's additional fields as standard post meta. </p>\n\n<p>You might want to store Brands (merchants? manufacturers?) as a custom taxonomy so that you can take advantage of built-in templates and queries to show all products of a certain brand.</p>\n" }, { "answer_id": 233238, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>Import is inherently heavy operation, because it is <em>bulk</em> operation and writes are inherently very heavy (relative to reads).</p>\n\n<p>If you are not time–constrained for the operation — does it really matter? </p>\n\n<ol>\n<li>Write your import as command line tool.</li>\n<li>Make sure you disable PHP timeout.</li>\n<li>Make sure you can efficiently restart process at certain point, in case something goes wrong.</li>\n</ol>\n\n<p>After that it takes as long as it takes.</p>\n\n<p>If you <em>are</em> time constrained (for example having to run this often/repeatedly) then you would need to approach this as general performance problem. That is you need to <em>profile</em> actual performance and determine what the bottlenecks are in the process.</p>\n\n<p>In case if multiple queries <em>are</em> an issue you could consider staged process — when meta is first stored as single entry on import and then expanded into more convenient form at a later point.</p>\n\n<p>I would recommend to stay away from modifying native tables since there seems to be little <em>functional</em> need to do so in this case.</p>\n" } ]
2016/07/23
[ "https://wordpress.stackexchange.com/questions/233035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64614/" ]
I have a XML file that consist of product information. Format of XML file : ``` <product> <name>Product-1</name> <description>this is product 1 description</description> <category>Category-1<category> <merchant>1234</merchant> <price>12</price> <instock>1<instock> <stockstatus>45</stockstatus> <image>http://www.example.com/1.jpg</image> <manufacture>987</manufacture> </product> ``` I need to write a script that will add these detail as a product. For now I am not using any WP plugin for eCommerce purpose. I am planning to create a custom post type as **wpproduct** that will store these products details. So for now I can use `name` as `post title`, `description` as `post content` and `image` as `post thumbnail`. And for storing the meta data I can store it in `postmeta` table. So I can create the post by using `wp_insert_post` and whatever `ID` it will return, I will use that ID in `update_post_meta` to update the meta data such as price, stock status , stock quantity, manufacturer etc. Like this it can be done.. Main Concern ============= So for a single product I need to write 1 `wp_insert_post` and then 6 `update_meta_data` query. So 7 query for 1 product. Not exactly 7 query as WP inbuilt function uses many query for validation check. What will happen if my XML file has 1 lakh product. So for adding 1 lakh product 7 lakh mysql query will run. Assumption =========== I am just eager to know like can I add custom column in WP wp\_posts table so that I can add 1 product in 1 query only. I might use raw mysql query to add it. Please help me and guide the best way to do it. Thanks
I've checked and WordPress does, by default, retrieve & cache all post meta along with the main query's posts, so you're perfectly fine storing a product's additional fields as standard post meta. You might want to store Brands (merchants? manufacturers?) as a custom taxonomy so that you can take advantage of built-in templates and queries to show all products of a certain brand.
233,065
<p>Normally when you set a custom image size using hard crop - e.g. <code>add_image_size( 'custom-size', 400, 400, true );</code> - you get the following results:</p> <ul> <li>#1 Uploaded image: 600x500 > Thumbnail: 400x400.</li> <li>#2 Uploaded image: 500x300 > Thumbnail: 400x300.</li> <li>#3 Uploaded image: 300x200 > Thumbnail: 300x200.</li> </ul> <p>However what I'd like to do is when the uploaded image is smaller than the set width, or height, or both, of the custom image size, e.g. examples #2 &amp; #3 above - instead of the image just being cropped to fit within those dimensions - it's also cropped to match their aspect ratio (which in this case is 1:1) like so:</p> <ul> <li>#1 Uploaded image: 600x500 > Thumbnail: 400x400.</li> <li>#2 Uploaded image: 500x300 > Thumbnail: <strong>300x300</strong>.</li> <li>#3 Uploaded image: 300x200 > Thumbnail: <strong>200x200</strong>.</li> </ul> <p>I don't believe this is possible using the standard add_image_size options, but is it possible using a different function, or hook that modifies the add_image_size function?</p> <p>Or is there a plugin that adds this functionality?</p> <p>Any information anyone can provide would be greatly appreciated.</p>
[ { "answer_id": 233067, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>You're right that it just doesn't work like that.</p>\n\n<p>If it's OK to think of your question the other way around though, you can get the right outcome in modern browsers using a selection of image sizes and responsive images.</p>\n\n<p>If you use code like this:</p>\n\n<pre><code>add_image_size( 'custom-size-small', 200, 200, true );\nadd_image_size( 'custom-size-medium', 300, 300, true );\nadd_image_size( 'custom-size-large', 400, 400, true );\n</code></pre>\n\n<p>... and in your templates something like:</p>\n\n<pre><code>wp_get_attachment_image( $image_ID, 'custom-size-small' )\n</code></pre>\n\n<p>... then by default (WP 4.4 and later) you will get an image tag with the smallest version from your set as the <code>src</code> and the larger sizes in the <code>srcset</code> attribute, which newer browsers will pick from and display the largest appropriate version.</p>\n\n<p>So then, if a particular image doesn't have a larger version, it doesn't matter. An image that is <code>300x200</code> will have a <code>200x200</code> version made, that version will be the only one in the HTML and all browsers will show it.</p>\n\n<p>I worked this out while tweaking responsive images so that I get good performance on browsers that only support <code>src</code> and not <code>srcset</code>.</p>\n" }, { "answer_id": 238658, "author": "Bryan Willis", "author_id": 38123, "author_profile": "https://wordpress.stackexchange.com/users/38123", "pm_score": 2, "selected": false, "text": "<p>This isn't a really good solution since it's a newer CSS solution and it's only working in <a href=\"http://caniuse.com/#search=object-fit\" rel=\"nofollow\">78.9% of users browsers</a>, but there are a few polyfills that can overcome that <a href=\"https://github.com/bfred-it/object-fit-images/\" rel=\"nofollow\">object-fit-images</a> and <a href=\"https://github.com/jonathantneal/fitie\" rel=\"nofollow\">fitie</a></p>\n\n<pre><code>img {\n display: block;\n overflow: hidden;\n width: 400px;\n height: 400px;\n -o-object-fit: cover;\n object-fit: cover;\n}\n</code></pre>\n\n<p>Ideally it would be better if the smaller images scaled proportionally on upload, but I haven't been able to figure out a solution for that.</p>\n" } ]
2016/07/24
[ "https://wordpress.stackexchange.com/questions/233065", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91352/" ]
Normally when you set a custom image size using hard crop - e.g. `add_image_size( 'custom-size', 400, 400, true );` - you get the following results: * #1 Uploaded image: 600x500 > Thumbnail: 400x400. * #2 Uploaded image: 500x300 > Thumbnail: 400x300. * #3 Uploaded image: 300x200 > Thumbnail: 300x200. However what I'd like to do is when the uploaded image is smaller than the set width, or height, or both, of the custom image size, e.g. examples #2 & #3 above - instead of the image just being cropped to fit within those dimensions - it's also cropped to match their aspect ratio (which in this case is 1:1) like so: * #1 Uploaded image: 600x500 > Thumbnail: 400x400. * #2 Uploaded image: 500x300 > Thumbnail: **300x300**. * #3 Uploaded image: 300x200 > Thumbnail: **200x200**. I don't believe this is possible using the standard add\_image\_size options, but is it possible using a different function, or hook that modifies the add\_image\_size function? Or is there a plugin that adds this functionality? Any information anyone can provide would be greatly appreciated.
You're right that it just doesn't work like that. If it's OK to think of your question the other way around though, you can get the right outcome in modern browsers using a selection of image sizes and responsive images. If you use code like this: ``` add_image_size( 'custom-size-small', 200, 200, true ); add_image_size( 'custom-size-medium', 300, 300, true ); add_image_size( 'custom-size-large', 400, 400, true ); ``` ... and in your templates something like: ``` wp_get_attachment_image( $image_ID, 'custom-size-small' ) ``` ... then by default (WP 4.4 and later) you will get an image tag with the smallest version from your set as the `src` and the larger sizes in the `srcset` attribute, which newer browsers will pick from and display the largest appropriate version. So then, if a particular image doesn't have a larger version, it doesn't matter. An image that is `300x200` will have a `200x200` version made, that version will be the only one in the HTML and all browsers will show it. I worked this out while tweaking responsive images so that I get good performance on browsers that only support `src` and not `srcset`.
233,086
<p>I have custom table like this:</p> <p><strong>useraw</strong></p> <pre><code>1. id (Primary*) 2. user_ip 3. post_id 4. time </code></pre> <p>I am inserting data in the table using </p> <pre><code>$wpdb-&gt;insert($table_name , array('user_ip' =&gt; $user_ip, 'post_id' =&gt; $postID, 'time' =&gt; $visittime),array('%s','%d', '%d') ); </code></pre> <p>There are four rows I inserted using this code:</p> <pre><code>id : 245 user_ip : 245.346.234.22 post_id : 24434 time : 255464 id : 345 user_ip : 245.346.234.22 post_id : 23456 time : 23467 id : 567 user_ip : 245.346.234.22 post_id : 57436 time : 5678 id : 234 user_ip : 245.356.134.22 post_id : 2356 time : 45678 </code></pre> <p>I want to learn how to use MySQL queries in WordPress. So here are my questions:</p> <ol> <li>How to display all the data of table?</li> <li>How to replace data if condition matched. Like I want change the <code>time</code> where <code>user_ip = 245.356.134.22</code></li> </ol> <p>Please let me know if there is something I must need to learn.</p> <p>Thank You</p>
[ { "answer_id": 233089, "author": "hosker", "author_id": 87687, "author_profile": "https://wordpress.stackexchange.com/users/87687", "pm_score": 0, "selected": false, "text": "<p>You indicate MYSQLi in your question, but label and refer to MySQL in your question. If you are using MySQL the following will work for you:</p>\n<p>This is fairly simple, and given the fact that you already have the insert statement constructed, you can just use update like so:</p>\n<pre><code>$wpdb-&gt;update($table_name , array('user_ip' =&gt; $user_ip, 'post_id' =&gt;$postID, 'time' =&gt; $visittime),array('%s','%d', '%d') );\n</code></pre>\n<p>Then all you would have to do is set the values in your query as to what data in the DB you want to change. You can find <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows\" rel=\"nofollow noreferrer\">examples here</a></p>\n<p>As for fetching all of the data you could use the follow:</p>\n<pre><code>$results = $wpdb-&gt;get_results(&quot;SELECT * FROM table_name&quot;); \n</code></pre>\n<p>You can add any WHERE parameters to it or sort it just like and standard SQL query statement. You can just then loop through is with a foreach loop and then you would just echo out your data you retrieved.</p>\n" }, { "answer_id": 233101, "author": "Rishabh", "author_id": 81621, "author_profile": "https://wordpress.stackexchange.com/users/81621", "pm_score": 5, "selected": true, "text": "<p><strong>To fetch data from database table</strong></p>\n<pre><code>$results = $wpdb-&gt;get_results( &quot;SELECT * FROM $table_name&quot;); // Query to fetch data from database table and storing in $results\nif(!empty($results)) // Checking if $results have some values or not\n{ \n echo &quot;&lt;table width='100%' border='0'&gt;&quot;; // Adding &lt;table&gt; and &lt;tbody&gt; tag outside foreach loop so that it wont create again and again\n echo &quot;&lt;tbody&gt;&quot;; \n foreach($results as $row){ \n $userip = $row-&gt;user_ip; //putting the user_ip field value in variable to use it later in update query\n echo &quot;&lt;tr&gt;&quot;; // Adding rows of table inside foreach loop\n echo &quot;&lt;th&gt;ID&lt;/th&gt;&quot; . &quot;&lt;td&gt;&quot; . $row-&gt;id . &quot;&lt;/td&gt;&quot;;\n echo &quot;&lt;/tr&gt;&quot;;\n echo &quot;&lt;td colspan='2'&gt;&lt;hr size='1'&gt;&lt;/td&gt;&quot;;\n echo &quot;&lt;tr&gt;&quot;; \n echo &quot;&lt;th&gt;User IP&lt;/th&gt;&quot; . &quot;&lt;td&gt;&quot; . $row-&gt;user_ip . &quot;&lt;/td&gt;&quot;; //fetching data from user_ip field\n echo &quot;&lt;/tr&gt;&quot;;\n echo &quot;&lt;td colspan='2'&gt;&lt;hr size='1'&gt;&lt;/td&gt;&quot;;\n echo &quot;&lt;tr&gt;&quot;; \n echo &quot;&lt;th&gt;Post ID&lt;/th&gt;&quot; . &quot;&lt;td&gt;&quot; . $row-&gt;post_id . &quot;&lt;/td&gt;&quot;;\n echo &quot;&lt;/tr&gt;&quot;;\n echo &quot;&lt;td colspan='2'&gt;&lt;hr size='1'&gt;&lt;/td&gt;&quot;;\n echo &quot;&lt;tr&gt;&quot;; \n echo &quot;&lt;th&gt;Time&lt;/th&gt;&quot; . &quot;&lt;td&gt;&quot; . $row-&gt;time . &quot;&lt;/td&gt;&quot;;\n echo &quot;&lt;/tr&gt;&quot;;\n echo &quot;&lt;td colspan='2'&gt;&lt;hr size='1'&gt;&lt;/td&gt;&quot;;\n }\n echo &quot;&lt;/tbody&gt;&quot;;\n echo &quot;&lt;/table&gt;&quot;; \n\n}\n</code></pre>\n<p><code>NOTE: Change your data fetching format according to your need (table structure)</code></p>\n<p><strong>To update time field on if condition</strong></p>\n<pre><code> if($userip==245.356.134.22){ //Checking if user_ip field have following value\n$wpdb-&gt;update( \n$table_name, \narray( \n 'time' =&gt; 'YOUR NEW TIME' // Entring the new value for time field\n), \narray('%d') // Specify the datatype of time field\n);\n}\n</code></pre>\n<p><strong>Update</strong></p>\n<p>If you want to check if the IP you are going to insert in database is already exist or not then check it like this</p>\n<pre><code>global $wpdb,$ip;\n$results = $wpdb-&gt;get_results( &quot;SELECT user_ip FROM $table_name&quot;); //query to fetch record only from user_ip field\n\n$new_ip = 245.356.134.22; //New Ip address storing in variable\n\nif(!empty($results)) \n{ \n foreach($results as $row){ \n $old_ip = $row-&gt;user_ip; // putting the value of user_ip field in variable\n if($new_ip==$old_ip){ // comparing new ip address with old ip addresses\n $ip = 'Already Exist'; // if ip already exist in database then assigning some string to variable\n }\n }\n\n}\nif($ip = 'Already Exist'){ // Checking if variable have some string (It has some string only when if IP already exist in database as checked in if condition by comparing old ips with new ip)\n//Insert query according to Ip already exist in database\n}else{\n//Insert query according to Ip doesn't exist in database\n}\n</code></pre>\n" }, { "answer_id": 233314, "author": "Ganesh", "author_id": 62275, "author_profile": "https://wordpress.stackexchange.com/users/62275", "pm_score": 2, "selected": false, "text": "<pre><code>//For fetching data use\nglobal $wpdb;\n$results = $wpdb-&gt;get_results(\"SLECT * FROM table_name\"); \n//and for update use below code \n$wpdb-&gt;update( \n $table_name, \n array( \n 'time' =&gt; time(), // string\n ), \n array( 'user_ip' =&gt; '245.356.134.22' ), \n array('%s'), \n array( '%d' )\n);\n</code></pre>\n" } ]
2016/07/24
[ "https://wordpress.stackexchange.com/questions/233086", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68328/" ]
I have custom table like this: **useraw** ``` 1. id (Primary*) 2. user_ip 3. post_id 4. time ``` I am inserting data in the table using ``` $wpdb->insert($table_name , array('user_ip' => $user_ip, 'post_id' => $postID, 'time' => $visittime),array('%s','%d', '%d') ); ``` There are four rows I inserted using this code: ``` id : 245 user_ip : 245.346.234.22 post_id : 24434 time : 255464 id : 345 user_ip : 245.346.234.22 post_id : 23456 time : 23467 id : 567 user_ip : 245.346.234.22 post_id : 57436 time : 5678 id : 234 user_ip : 245.356.134.22 post_id : 2356 time : 45678 ``` I want to learn how to use MySQL queries in WordPress. So here are my questions: 1. How to display all the data of table? 2. How to replace data if condition matched. Like I want change the `time` where `user_ip = 245.356.134.22` Please let me know if there is something I must need to learn. Thank You
**To fetch data from database table** ``` $results = $wpdb->get_results( "SELECT * FROM $table_name"); // Query to fetch data from database table and storing in $results if(!empty($results)) // Checking if $results have some values or not { echo "<table width='100%' border='0'>"; // Adding <table> and <tbody> tag outside foreach loop so that it wont create again and again echo "<tbody>"; foreach($results as $row){ $userip = $row->user_ip; //putting the user_ip field value in variable to use it later in update query echo "<tr>"; // Adding rows of table inside foreach loop echo "<th>ID</th>" . "<td>" . $row->id . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>User IP</th>" . "<td>" . $row->user_ip . "</td>"; //fetching data from user_ip field echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>Post ID</th>" . "<td>" . $row->post_id . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>Time</th>" . "<td>" . $row->time . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; } echo "</tbody>"; echo "</table>"; } ``` `NOTE: Change your data fetching format according to your need (table structure)` **To update time field on if condition** ``` if($userip==245.356.134.22){ //Checking if user_ip field have following value $wpdb->update( $table_name, array( 'time' => 'YOUR NEW TIME' // Entring the new value for time field ), array('%d') // Specify the datatype of time field ); } ``` **Update** If you want to check if the IP you are going to insert in database is already exist or not then check it like this ``` global $wpdb,$ip; $results = $wpdb->get_results( "SELECT user_ip FROM $table_name"); //query to fetch record only from user_ip field $new_ip = 245.356.134.22; //New Ip address storing in variable if(!empty($results)) { foreach($results as $row){ $old_ip = $row->user_ip; // putting the value of user_ip field in variable if($new_ip==$old_ip){ // comparing new ip address with old ip addresses $ip = 'Already Exist'; // if ip already exist in database then assigning some string to variable } } } if($ip = 'Already Exist'){ // Checking if variable have some string (It has some string only when if IP already exist in database as checked in if condition by comparing old ips with new ip) //Insert query according to Ip already exist in database }else{ //Insert query according to Ip doesn't exist in database } ```
233,093
<p><strong>Fail #1:</strong> The hook, <code>genesis_after_content</code>, allows me to add content directly after the <code>&lt;main&gt;</code> tag and before the <code>&lt;aside&gt;</code> tag. So in a content first, sidebar second configuration, it would look like this:</p> <pre><code>&lt;div class="content-sidebar-wrap"&gt; &lt;main&gt;&lt;/main&gt; &lt;div class="custom-content"&gt;&lt;/div&gt; &lt;aside&gt;&lt;/aside&gt; &lt;/div&gt; </code></pre> <p><strong>Fail #2:</strong> The hook, <code>genesis_after_content_sidebar_wrap</code>, allows me to insert content on the outside of the parent container of <code>&lt;main&gt;</code> and <code>&lt;aside&gt;</code>. So with the same content sidebar configuration, would look like this:</p> <pre><code>&lt;div class="content-sidebar-wrap"&gt; &lt;main&gt;&lt;/main&gt; &lt;aside&gt;&lt;/aside&gt; &lt;/div&gt; &lt;div class="custom-content"&gt;&lt;/div&gt; </code></pre> <p><strong>Fail #3:</strong> Using the, `genesis_after_sidebar_widget_area' wont work either and results in this configuration:</p> <pre><code>&lt;div class="content-sidebar-wrap"&gt; &lt;main&gt;&lt;/main&gt; &lt;aside&gt; &lt;div class="custom-content"&gt;&lt;/div&gt; &lt;/aside&gt; &lt;/div&gt; </code></pre> <p><strong>Summary:</strong> I cannot find the hook that would allow me to add content before the closing <code>content-sidebar-wrap</code> tag, and after the closing <code>&lt;aside&gt;</code> tag. How would I go about accomplishing this?:</p> <pre><code>&lt;div class="content-sidebar-wrap"&gt; &lt;main&gt;&lt;/main&gt; &lt;aside&gt;&lt;/aside&gt; &lt;div class="custom-content"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 235040, "author": "GaryJ", "author_id": 44505, "author_profile": "https://wordpress.stackexchange.com/users/44505", "pm_score": 2, "selected": true, "text": "<p>If you look in <code>lib/structure/layout.php</code>, towards the bottom, you'll see:</p>\n\n<pre><code>add_action( 'genesis_after_content', 'genesis_get_sidebar' );\n/**\n * Output the sidebar.php file if layout allows for it.\n *\n * @since 0.2.0\n *\n * @uses genesis_site_layout() Return the site layout for different contexts.\n */\nfunction genesis_get_sidebar() {\n $site_layout = genesis_site_layout();\n //* Don't load sidebar on pages that don't need it\n if ( 'full-width-content' === $site_layout )\n return;\n get_sidebar();\n}\n</code></pre>\n\n<p>This adds the sidebar, at the default priority 10, to <code>genesis_after_content</code>.</p>\n\n<p>As such, if you want to come after the sidebar, but but before the closing tag of the content-sidebar-wrap, hook your code into a later priority e.g.</p>\n\n<pre><code>add_action( 'genesis_after_content', 'gmj_add_custom_div', 15 );\n/**\n * Output a custom section, after primary sidebar, but still inside the content-sidebar-wrap.\n *\n * @link http://wordpress.stackexchange.com/questions/233093/genesis-how-to-add-content-after-aside-and-before-the-content-sidebar-wrap\n */\nfunction gmj_add_custom_div() {\n ?&gt;\n &lt;div class=\"custom-content\"&gt;&lt;/div&gt;\n &lt;?php\n}\n</code></pre>\n\n<p>The important difference between this, and your Fail #1, is the priority of 15.</p>\n" }, { "answer_id": 346394, "author": "Michael Neely", "author_id": 147995, "author_profile": "https://wordpress.stackexchange.com/users/147995", "pm_score": 0, "selected": false, "text": "<p>I found this post in a search to see how I could accomplish this for a client project I am working on. Here is the solution that worked for me, and then use CSS to position the sidebar :</p>\n\n<pre><code>// Adds the sidebar inside the main content area\nadd_action('genesis_before', 'mn_sidebar_entry_content');\nfunction mn_sidebar_entry_content() {\n remove_action('genesis_sidebar', 'genesis_do_sidebar');\n add_action('genesis_entry_content', 'genesis_do_sidebar');\n}`\n</code></pre>\n\n<p>However, if your are just looking to match the background and keep the sidebar on the side this will work:</p>\n\n<pre><code> .site-inner .wrap{ background-color: #fff; }\n</code></pre>\n" } ]
2016/07/25
[ "https://wordpress.stackexchange.com/questions/233093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64943/" ]
**Fail #1:** The hook, `genesis_after_content`, allows me to add content directly after the `<main>` tag and before the `<aside>` tag. So in a content first, sidebar second configuration, it would look like this: ``` <div class="content-sidebar-wrap"> <main></main> <div class="custom-content"></div> <aside></aside> </div> ``` **Fail #2:** The hook, `genesis_after_content_sidebar_wrap`, allows me to insert content on the outside of the parent container of `<main>` and `<aside>`. So with the same content sidebar configuration, would look like this: ``` <div class="content-sidebar-wrap"> <main></main> <aside></aside> </div> <div class="custom-content"></div> ``` **Fail #3:** Using the, `genesis\_after\_sidebar\_widget\_area' wont work either and results in this configuration: ``` <div class="content-sidebar-wrap"> <main></main> <aside> <div class="custom-content"></div> </aside> </div> ``` **Summary:** I cannot find the hook that would allow me to add content before the closing `content-sidebar-wrap` tag, and after the closing `<aside>` tag. How would I go about accomplishing this?: ``` <div class="content-sidebar-wrap"> <main></main> <aside></aside> <div class="custom-content"></div> </div> ```
If you look in `lib/structure/layout.php`, towards the bottom, you'll see: ``` add_action( 'genesis_after_content', 'genesis_get_sidebar' ); /** * Output the sidebar.php file if layout allows for it. * * @since 0.2.0 * * @uses genesis_site_layout() Return the site layout for different contexts. */ function genesis_get_sidebar() { $site_layout = genesis_site_layout(); //* Don't load sidebar on pages that don't need it if ( 'full-width-content' === $site_layout ) return; get_sidebar(); } ``` This adds the sidebar, at the default priority 10, to `genesis_after_content`. As such, if you want to come after the sidebar, but but before the closing tag of the content-sidebar-wrap, hook your code into a later priority e.g. ``` add_action( 'genesis_after_content', 'gmj_add_custom_div', 15 ); /** * Output a custom section, after primary sidebar, but still inside the content-sidebar-wrap. * * @link http://wordpress.stackexchange.com/questions/233093/genesis-how-to-add-content-after-aside-and-before-the-content-sidebar-wrap */ function gmj_add_custom_div() { ?> <div class="custom-content"></div> <?php } ``` The important difference between this, and your Fail #1, is the priority of 15.
233,109
<p>I have a meta key which I would like to use to get all post meta data for a post where that one meta key matches a specific value, in one go.</p> <p>Example: <code>Post 1</code> has a <code>meta_key</code> called <code>unique_number</code>. I want to query for all the occurences where <code>unique_number</code> is a specific value, and then get all the meta data for the posts where <code>unique numner</code> is that value.</p> <p>The way I found to do it now, is this way:</p> <pre><code>$args = array( 'meta_key' =&gt; 'unique_number', 'meta_value' =&gt; '12345' ); $posts = get_posts( $args ); ...then I have to loop through the result and use get_post_meta to fetch the meta data. </code></pre> <p>Is it possible to do this in one query, except many, with built in Wordpress functions, or do I have to write my own custom mysql query?</p>
[ { "answer_id": 233110, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>When you call get_posts WP will also retrieve and cache all the post meta, so your later calls to get the meta data shouldn't cause any more database queries. </p>\n" }, { "answer_id": 388102, "author": "Edward", "author_id": 206327, "author_profile": "https://wordpress.stackexchange.com/users/206327", "pm_score": 0, "selected": false, "text": "<p>You should not query for post meta values. The post meta value field is of type TEXT and has no index so queries are very slow as soon as your post meta table gets bigger. Use post meta only for cosmetic data. If you have custom values that you want to query always use custom tables which can easily be integrated into WP_Query args or write your own sql query for direct access of those values. More details to that topic can be found in this article which compares performance of post metas vs custom tables and gives some code examples too.</p>\n" } ]
2016/07/25
[ "https://wordpress.stackexchange.com/questions/233109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43933/" ]
I have a meta key which I would like to use to get all post meta data for a post where that one meta key matches a specific value, in one go. Example: `Post 1` has a `meta_key` called `unique_number`. I want to query for all the occurences where `unique_number` is a specific value, and then get all the meta data for the posts where `unique numner` is that value. The way I found to do it now, is this way: ``` $args = array( 'meta_key' => 'unique_number', 'meta_value' => '12345' ); $posts = get_posts( $args ); ...then I have to loop through the result and use get_post_meta to fetch the meta data. ``` Is it possible to do this in one query, except many, with built in Wordpress functions, or do I have to write my own custom mysql query?
When you call get\_posts WP will also retrieve and cache all the post meta, so your later calls to get the meta data shouldn't cause any more database queries.
233,111
<p>In my loop, I have ten posts with the following categories (slug): group-a, group-a-first and group-b. The loop/query looks like this:</p> <ul> <li>Post (group-a)</li> <li>Post (group-b)</li> <li>Post (group-a-first)</li> </ul> <p>What's the best way to check if those posts has a specific category?</p> <p>I've tried <code>&lt;?php if(in_category('group-a')) ;?&gt;</code>, it does work but it checks every post so I three results: yes, no, no, etc.</p> <p>What I'm looking for if any post in the loop has a specific category, it outputs either a yes or no.</p> <p>My query has multiple loops so this the code I'm using:</p> <pre><code>&lt;?php $args = array('tax_query' =&gt; array(array('taxonomy' =&gt; 'post-status','field' =&gt; 'slug','terms' =&gt; array ('post-status-published')))); $query = new WP_Query( $args );?&gt; &lt;?php if ( $query-&gt;have_posts() ) : $duplicates = []; while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if ( in_category( 'first-major' ) ) : ?&gt; &lt;div class="major"&gt;&lt;div class="major-first"&gt; major and first - &lt;?php the_title();?&gt;&lt;br&gt; &lt;?php $duplicates[] = get_the_ID(); ?&gt; &lt;/div&gt; &lt;?php endif; endwhile; ?&gt; &lt;?php $query-&gt;rewind_posts(); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if (( in_category( 'major' ) ) &amp;&amp; (!in_category( 'first-major'))) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?&gt; major - &lt;?php the_title(); ?&gt;&lt;br&gt; &lt;?php $duplicates[] = get_the_ID(); ?&gt; &lt;?php endif;?&gt; &lt;?php endwhile; ?&gt;&lt;/div&gt; &lt;?php $query-&gt;rewind_posts(); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if (( in_category( 'major' ) ) &amp;&amp; (!in_category( 'first-major'))) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?&gt; major - &lt;?php the_title(); ?&gt;&lt;br&gt; &lt;?php $duplicates[] = get_the_ID(); ?&gt; &lt;?php endif;?&gt; &lt;?php endwhile; ?&gt;&lt;/div&gt; &lt;?php $query-&gt;rewind_posts(); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if ( in_category('group-a')) :?&gt; yes &lt;?php else :?&gt; no &lt;?php endif;?&gt; &lt;?php if ( in_category( 'group-a-first' ) ) : ?&gt; group a and first - &lt;?php the_title(); ?&gt;&lt;br&gt; &lt;?php $duplicates[] = get_the_ID(); ?&gt; &lt;?php endif;?&gt; &lt;?php endwhile; ?&gt; &lt;?php $query-&gt;rewind_posts(); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if (( in_category( 'group-a' ) ) &amp;&amp; (!in_category( 'group-a-first'))) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?&gt; group a - &lt;?php the_title(); ?&gt;&lt;br&gt; &lt;?php $duplicates[] = get_the_ID(); ?&gt; &lt;?php endif;?&gt; &lt;?php endwhile; ?&gt; &lt;?php $query-&gt;rewind_posts(); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if ( in_category( 'group-b-first' ) ) : ?&gt; group b and first - &lt;?php the_title(); ?&gt;&lt;br&gt; &lt;?php $duplicates[] = get_the_ID(); ?&gt; &lt;?php endif;?&gt; &lt;?php endwhile; ?&gt; &lt;?php $query-&gt;rewind_posts(); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?&gt; &lt;?php the_title();?&gt;&lt;br&gt; &lt;?php endwhile; wp_reset_postdata(); endif; ?&gt; &lt;/section&gt; </code></pre> <p>Thanks, </p>
[ { "answer_id": 233121, "author": "Muhammad Junaid Bhatti", "author_id": 98900, "author_profile": "https://wordpress.stackexchange.com/users/98900", "pm_score": -1, "selected": false, "text": "<p><code>is_category()</code> tests to see if you are displaying a category archive, but you are displaying a single post, so this will always return false</p>\n\n<p><code>in_category()</code> tests to see if a given post has a category in that specific category and must be used in <code>The Loop</code>, but you are trying to figure out what the category is, before you get to the loop.</p>\n\n<hr>\n\n<pre><code>if ( is_single() ) {\n $cats = wp_get_post_categories($posts[0]-&gt;ID);\n $first_cat = '';\n if ($cats) {\n $first_cat = $cats[0];\n }\n if ($first_cat == 7 ) {\n include 'wp-loop2.php';\n } else {\n include 'wp-loop.php';\n }\n}\n</code></pre>\n" }, { "answer_id": 233124, "author": "Fencer04", "author_id": 98527, "author_profile": "https://wordpress.stackexchange.com/users/98527", "pm_score": 1, "selected": false, "text": "<p>You can create a separate function to check your array of posts contains a post with that category. It will basically do what you are now but it will allow you to call the function once instead of each time through the loop. You would put this code in your functions.php file:</p>\n\n<pre><code>function does_array_contain_category( $categories, $posts ){\n foreach( $posts as $post) {\n if( in_category( $categories, $post ) ){\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>You could then call this function in your loop by doing this:</p>\n\n<pre><code>&lt;?php \n //$in_group_a will be true or false for use wherever you need it.\n $in_group_a = does_array_contain_category( array( 'group_a' ), $query-&gt;get_posts() ); \n while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n&lt;?php $query-&gt;rewind_posts(); ?&gt;\n</code></pre>\n" }, { "answer_id": 233125, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>You can just run through the loop and set a flag:</p>\n\n<pre><code>if ( $query-&gt;have_posts() ) : \n\n $any_in_cat = false; \n\n while ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n\n if ( in_category( 'first-major' ) ) :\n $any_in_cat = true;\n endif; \n\n endwhile;\n\n$query-&gt;rewind_posts();\n\n/* if $any_in_cat == true at this point then at least one \n of the posts has the category 'first-major'\n*/\n\nif( true == $any_in_cat ) {\n echo 'true';\n} else { \n echo 'false';\n}\n</code></pre>\n\n<p>I've added your conditional check. Note that it is all PHP, so you don't want the opening and closing tags where you have them in your comment. I prefer the brace notation myself as it suits every case of nested conditionals and is really clear to read. Lastly you need the double-equals sign to test equality. <code>=</code> is the assignment operator, so when you say <code>if ( $any_in_cat = true )</code> then you are setting <code>$any_in_cat</code> to <code>true</code> and also the condition will always be <code>true</code>. Even <code>if ( $any_in_cat = false )</code> is <code>true</code> because you are testing the success of the assignment. It's a slip we all make and is easier to debug if you get in the habit of writing the condition as <code>if( true == $any_in_cat )</code> Then if you slip and use a single <code>=</code> you'll get an error message as you can't make an assignment to <code>true</code>.</p>\n\n<p>You're re-running your loop several times, so it might be possible to simplify your code somewhat too, but that's another question and not directly WP related.</p>\n" } ]
2016/07/25
[ "https://wordpress.stackexchange.com/questions/233111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
In my loop, I have ten posts with the following categories (slug): group-a, group-a-first and group-b. The loop/query looks like this: * Post (group-a) * Post (group-b) * Post (group-a-first) What's the best way to check if those posts has a specific category? I've tried `<?php if(in_category('group-a')) ;?>`, it does work but it checks every post so I three results: yes, no, no, etc. What I'm looking for if any post in the loop has a specific category, it outputs either a yes or no. My query has multiple loops so this the code I'm using: ``` <?php $args = array('tax_query' => array(array('taxonomy' => 'post-status','field' => 'slug','terms' => array ('post-status-published')))); $query = new WP_Query( $args );?> <?php if ( $query->have_posts() ) : $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?> <?php if ( in_category( 'first-major' ) ) : ?> <div class="major"><div class="major-first"> major and first - <?php the_title();?><br> <?php $duplicates[] = get_the_ID(); ?> </div> <?php endif; endwhile; ?> <?php $query->rewind_posts(); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if (( in_category( 'major' ) ) && (!in_category( 'first-major'))) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?> major - <?php the_title(); ?><br> <?php $duplicates[] = get_the_ID(); ?> <?php endif;?> <?php endwhile; ?></div> <?php $query->rewind_posts(); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if (( in_category( 'major' ) ) && (!in_category( 'first-major'))) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?> major - <?php the_title(); ?><br> <?php $duplicates[] = get_the_ID(); ?> <?php endif;?> <?php endwhile; ?></div> <?php $query->rewind_posts(); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if ( in_category('group-a')) :?> yes <?php else :?> no <?php endif;?> <?php if ( in_category( 'group-a-first' ) ) : ?> group a and first - <?php the_title(); ?><br> <?php $duplicates[] = get_the_ID(); ?> <?php endif;?> <?php endwhile; ?> <?php $query->rewind_posts(); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if (( in_category( 'group-a' ) ) && (!in_category( 'group-a-first'))) : if ( in_array( get_the_ID(), $duplicates ) ) continue; ?> group a - <?php the_title(); ?><br> <?php $duplicates[] = get_the_ID(); ?> <?php endif;?> <?php endwhile; ?> <?php $query->rewind_posts(); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if ( in_category( 'group-b-first' ) ) : ?> group b and first - <?php the_title(); ?><br> <?php $duplicates[] = get_the_ID(); ?> <?php endif;?> <?php endwhile; ?> <?php $query->rewind_posts(); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?> <?php the_title();?><br> <?php endwhile; wp_reset_postdata(); endif; ?> </section> ``` Thanks,
You can just run through the loop and set a flag: ``` if ( $query->have_posts() ) : $any_in_cat = false; while ( $query->have_posts() ) : $query->the_post(); if ( in_category( 'first-major' ) ) : $any_in_cat = true; endif; endwhile; $query->rewind_posts(); /* if $any_in_cat == true at this point then at least one of the posts has the category 'first-major' */ if( true == $any_in_cat ) { echo 'true'; } else { echo 'false'; } ``` I've added your conditional check. Note that it is all PHP, so you don't want the opening and closing tags where you have them in your comment. I prefer the brace notation myself as it suits every case of nested conditionals and is really clear to read. Lastly you need the double-equals sign to test equality. `=` is the assignment operator, so when you say `if ( $any_in_cat = true )` then you are setting `$any_in_cat` to `true` and also the condition will always be `true`. Even `if ( $any_in_cat = false )` is `true` because you are testing the success of the assignment. It's a slip we all make and is easier to debug if you get in the habit of writing the condition as `if( true == $any_in_cat )` Then if you slip and use a single `=` you'll get an error message as you can't make an assignment to `true`. You're re-running your loop several times, so it might be possible to simplify your code somewhat too, but that's another question and not directly WP related.
233,127
<p>I would like to change the priority/menu order of the "Media" admin page. Is there a way to change that via apply_filter?</p> <p>Is there a way to change only "Media" page priority without having to list all pages within menu_order?</p> <p>Thanks</p>
[ { "answer_id": 233129, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 4, "selected": true, "text": "<p>There's a combination of two filters, <code>menu_order</code> does the job, but you also use <code>custom_menu_order</code> to enable <code>menu_order</code>.</p>\n\n<pre><code>function wpse_233129_custom_menu_order() {\n return array( 'index.php', 'upload.php' );\n}\n\nadd_filter( 'custom_menu_order', '__return_true' );\nadd_filter( 'menu_order', 'wpse_233129_custom_menu_order' );\n</code></pre>\n\n<p>This will put upload.php (the Media screen) just after the Dashboard and then the other top-level menu items will follow.</p>\n\n<p>If you want to put Media elsewhere then just list all the other screens that should precede it in the array.</p>\n\n<p>Alternatively you could directly address WP's global $menu array:</p>\n\n<pre><code>function wpse_233129_admin_menu_items() {\n global $menu;\n\n foreach ( $menu as $key =&gt; $value ) {\n if ( 'upload.php' == $value[2] ) {\n $oldkey = $key;\n }\n }\n\n $newkey = 26; // use whatever index gets you the position you want\n // if this key is in use you will write over a menu item!\n $menu[$newkey]=$menu[$oldkey];\n $menu[$oldkey]=array();\n\n}\nadd_action('admin_menu', 'wpse_233129_admin_menu_items');\n</code></pre>\n\n<p>Note the comment on the possibility of overwriting another menu item. Coding in a search for an array index that doesn't collide is left as an exercise for the reader. This isn't an issue if you use the first method, of course.</p>\n\n<p>There's something about fiddling with WP's globals like this that makes me feel dirty. Changes to WP's inner workings can mess things up for you. Use the abstractions provided by hooks and APIs when you can.</p>\n" }, { "answer_id": 233130, "author": "Stephen", "author_id": 85776, "author_profile": "https://wordpress.stackexchange.com/users/85776", "pm_score": 1, "selected": false, "text": "<p>A quick <a href=\"https://www.google.co.uk/?ion=1&amp;espv=2#q=change%20media%20priority%20on%20wordpress%20admin%20menu\" rel=\"nofollow\">Google Search</a> gave me several results and I managed to find an easy solution.</p>\n\n<p>The code below is from <a href=\"http://easywebdesigntutorials.com/reorder-left-admin-menu-and-add-a-custom-user-role/\" rel=\"nofollow\">Easy Web Design Tutorial</a> website but I will paste it below in case that link ever breaks.</p>\n\n<pre><code>function reorder_admin_menu( $__return_true ) {\n return array(\n 'index.php', // Dashboard\n 'edit.php?post_type=page', // Pages\n 'edit.php', // Posts\n 'upload.php', // Media\n 'themes.php', // Appearance\n 'separator1', // --Space--\n 'edit-comments.php', // Comments\n 'users.php', // Users\n 'separator2', // --Space--\n 'plugins.php', // Plugins\n 'tools.php', // Tools\n 'options-general.php', // Settings\n );\n}\nadd_filter( 'custom_menu_order', 'reorder_admin_menu' );\nadd_filter( 'menu_order', 'reorder_admin_menu' );\n</code></pre>\n\n<p>You can re-order the menu by simply moving <code>media.php</code> where you would like it to be displayed</p>\n\n<p>As you can see the code above is well commented and shows you which <code>.php</code> files is what link :)</p>\n" }, { "answer_id": 298759, "author": "Slam", "author_id": 82256, "author_profile": "https://wordpress.stackexchange.com/users/82256", "pm_score": -1, "selected": false, "text": "<p>After getting repeat PHP errors with the above code I went with a plugin,<br>\n<a href=\"https://wordpress.org/plugins/admin-menu-editor/\" rel=\"nofollow noreferrer\">Admin Menu Editor</a>. Not only can I reorder menus it also lets me hide or move menus added by plugins. </p>\n" } ]
2016/07/25
[ "https://wordpress.stackexchange.com/questions/233127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/46037/" ]
I would like to change the priority/menu order of the "Media" admin page. Is there a way to change that via apply\_filter? Is there a way to change only "Media" page priority without having to list all pages within menu\_order? Thanks
There's a combination of two filters, `menu_order` does the job, but you also use `custom_menu_order` to enable `menu_order`. ``` function wpse_233129_custom_menu_order() { return array( 'index.php', 'upload.php' ); } add_filter( 'custom_menu_order', '__return_true' ); add_filter( 'menu_order', 'wpse_233129_custom_menu_order' ); ``` This will put upload.php (the Media screen) just after the Dashboard and then the other top-level menu items will follow. If you want to put Media elsewhere then just list all the other screens that should precede it in the array. Alternatively you could directly address WP's global $menu array: ``` function wpse_233129_admin_menu_items() { global $menu; foreach ( $menu as $key => $value ) { if ( 'upload.php' == $value[2] ) { $oldkey = $key; } } $newkey = 26; // use whatever index gets you the position you want // if this key is in use you will write over a menu item! $menu[$newkey]=$menu[$oldkey]; $menu[$oldkey]=array(); } add_action('admin_menu', 'wpse_233129_admin_menu_items'); ``` Note the comment on the possibility of overwriting another menu item. Coding in a search for an array index that doesn't collide is left as an exercise for the reader. This isn't an issue if you use the first method, of course. There's something about fiddling with WP's globals like this that makes me feel dirty. Changes to WP's inner workings can mess things up for you. Use the abstractions provided by hooks and APIs when you can.
233,140
<p>I'm creating a plugin and I want to get the list of all scripts and CSS used by other plugins.</p> <p>This is my function:</p> <pre><code>function crunchify_print_scripts_styles() { $result = []; $result['scripts'] = []; $result['styles'] = []; // Print all loaded Scripts global $wp_scripts; foreach( $wp_scripts-&gt;queue as $script ) : $result['scripts'][] = $wp_scripts-&gt;registered[$script]-&gt;src . ";"; endforeach; // Print all loaded Styles (CSS) global $wp_styles; foreach( $wp_styles-&gt;queue as $style ) : $result['styles'][] = $wp_styles-&gt;registered[$style]-&gt;src . ";"; endforeach; return $result; } add_action( 'wp_enqueue_scripts', 'crunchify_print_scripts_styles'); </code></pre> <p>I want to get the returned value inside a variable.</p> <p>I tried this:</p> <pre><code>$toto = do_action( 'crunchify_print_scripts_styles' ); var_dump( $toto ); </code></pre> <p>And this is my result:</p> <pre><code>NULL </code></pre> <p>If I write <code>echo</code> inside every <code>foreach</code> loop, I get the correct results, but how to store these values inside a variable?</p> <p>[edit]</p> <p>My code inside a pluginm which is not working too</p> <pre><code>/** * Get all scripts and styles from Wordpress */ function print_scripts_styles() { $result = []; $result['scripts'] = []; $result['styles'] = []; // Print all loaded Scripts global $wp_scripts; foreach( $wp_scripts-&gt;queue as $script ) : $result['scripts'][] = $wp_scripts-&gt;registered[$script]-&gt;src . ";"; endforeach; // Print all loaded Styles (CSS) global $wp_styles; foreach( $wp_styles-&gt;queue as $style ) : $result['styles'][] = $wp_styles-&gt;registered[$style]-&gt;src . ";"; endforeach; return $result; } add_action( 'wp_head', 'wp_rest_assets_init'); /** * Init JSON REST API Assets routes. * * @since 1.0.0 */ function wp_rest_assets_init() { $all_the_scripts_and_styles = print_scripts_styles(); if ( ! defined( 'JSON_API_VERSION' ) &amp;&amp; ! in_array( 'json-rest-api/plugin.php', get_option( 'active_plugins' ) ) ) { $class = new WP_REST_Assets(); $class::$scriptsAndStyles = $all_the_scripts_and_styles; add_filter( 'rest_api_init', array( $class, 'register_routes' ) ); } else { $class = new WP_JSON_Menus(); add_filter( 'json_endpoints', array( $class, 'register_routes' ) ); } } add_action( 'init', 'wp_rest_assets_init' ); </code></pre>
[ { "answer_id": 233142, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 5, "selected": true, "text": "<p><code>do_action</code> doesn't quite work like that. When you call <code>do_action('crunchify_print_scripts_styles')</code> WP looks at its list of registered actions and filters for any that are attached to a hook called <code>crunchify_print_scripts_styles</code> and then runs those functions.</p>\n\n<p>And you probably want to remove this:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'crunchify_print_scripts_styles');\n</code></pre>\n\n<p>... because you aren't able to get the return result of your function.</p>\n\n<p>Also when you use this particular hook you can't guarantee that other functions don't enqueue more scripts or styles <em>after</em> you've generated your list. Use a hook that fires after all scripts and styles have been enqueued, such as wp_head, for convenience, or better still just call your function within your theme when you want to display the result.</p>\n\n<p>Reworking your code like this should work...</p>\n\n<pre><code>function crunchify_print_scripts_styles() {\n\n $result = [];\n $result['scripts'] = [];\n $result['styles'] = [];\n\n // Print all loaded Scripts\n global $wp_scripts;\n foreach( $wp_scripts-&gt;queue as $script ) :\n $result['scripts'][] = $wp_scripts-&gt;registered[$script]-&gt;src . \";\";\n endforeach;\n\n // Print all loaded Styles (CSS)\n global $wp_styles;\n foreach( $wp_styles-&gt;queue as $style ) :\n $result['styles'][] = $wp_styles-&gt;registered[$style]-&gt;src . \";\";\n endforeach;\n\n return $result;\n}\n</code></pre>\n\n<p>Then within your theme:</p>\n\n<pre><code>print_r( crunchify_print_scripts_styles() );\n</code></pre>\n\n<p>... will show you the results for debugging, or of course...</p>\n\n<pre><code>$all_the_scripts_and_styles = crunchify_print_scripts_styles();\n</code></pre>\n\n<p>... will give you the list to manipulate.</p>\n\n<p>Calling it in the theme makes sure you call it after all scripts and styles are enqueued.</p>\n\n<p>To call it from your plugin, attach it to any hook that runs later than wp_enqueue_scripts, like wp_head as I mentioned above:</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_233142_process_list');\n\nfunction wpse_233142_process_list() {\n\n $all_the_scripts_and_styles = crunchify_print_scripts_styles();\n // process your array here\n\n}\n</code></pre>\n" }, { "answer_id": 233152, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": false, "text": "<p>You could use <a href=\"https://developer.wordpress.org/reference/hooks/wp_print_scripts/\" rel=\"noreferrer\"><code>wp_print_scripts</code></a> and <a href=\"https://developer.wordpress.org/reference/hooks/wp_print_styles/\" rel=\"noreferrer\"><code>wp_print_styles</code></a> actions to <strong>timely and properly</strong> access to enqueued scripts and styles, as these actions are the last events before scripts and styles are included in the document and, because of that, the last event where modifications on <code>$wp_styles</code> or <code>$wp_scripts</code> could have effect on styles and scripts included in the document.</p>\n\n<p>So, they are the events where you can be more confident that <code>$wp_styles</code> and <code>$wp_scripts</code> contain the scripts and styles effectively included in the document.</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'cyb_list_scripts' );\nfunction cyb_list_scripts() {\n global $wp_scripts;\n $enqueued_scripts = array();\n foreach( $wp_scripts-&gt;queue as $handle ) {\n $enqueued_scripts[] = $wp_scripts-&gt;registered[$handle]-&gt;src;\n }\n}\nadd_action( 'wp_print_styles', 'cyb_list_styles' );\nfunction cyb_list_styles() {\n global $wp_styles;\n $enqueued_styles = array();\n foreach( $wp_styles-&gt;queue as $handle ) {\n $enqueued_styles[] = $wp_styles-&gt;registered[$handle]-&gt;src;\n }\n}\n</code></pre>\n\n<p>If you declare <code>$enqueued_scripts</code> adn <code>$enqueued_styles</code> as global variables (or any other valid scope, for example you could store it in a method's property), you could access to the list of script and styles in a later action.</p>\n\n<p>For example (just a quick example):</p>\n\n<pre><code>global $enqueued_scripts;\nglobal $enqueued_styles;\n\nadd_action( 'wp_print_scripts', 'cyb_list_scripts' );\nfunction cyb_list_scripts() {\n global $wp_scripts;\n global $enqueued_scripts;\n $enqueued_scripts = array();\n foreach( $wp_scripts-&gt;queue as $handle ) {\n $enqueued_scripts[] = $wp_scripts-&gt;registered[$handle]-&gt;src;\n }\n}\nadd_action( 'wp_print_styles', 'cyb_list_styles' );\nfunction cyb_list_styles() {\n global $wp_styles;\n global $enqueued_styles;\n $enqueued_styles = array();\n foreach( $wp_styles-&gt;queue as $handle ) {\n $enqueued_styles[] = $wp_styles-&gt;registered[$handle]-&gt;src;\n }\n}\n\nadd_action( 'wp_head', function() {\n global $enqueued_scripts;\n var_dump( $enqueued_scripts );\n global $enqueued_styles;\n var_dump( $enqueued_styles );\n} );\n</code></pre>\n" }, { "answer_id": 325973, "author": "theuberdog", "author_id": 157377, "author_profile": "https://wordpress.stackexchange.com/users/157377", "pm_score": 0, "selected": false, "text": "<p>If you truly want to get a list of <strong>all</strong> styles, you can use the new <em>'script_loader_tag'</em> filter (Since Version 4.1). </p>\n\n<p>The \"wp_print_scripts\" is: </p>\n\n<blockquote>\n <p>Called by admin-header.php and ‘wp_head’ hook.</p>\n</blockquote>\n\n<p>i.e it doesn't show scripts in the footer.</p>\n\n<p><strong>References:</strong></p>\n\n<p><a href=\"https://matthewhorne.me/defer-async-wordpress-scripts/\" rel=\"nofollow noreferrer\">Add Defer &amp; Async Attributes to WordPress Scripts</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_print_scripts/\" rel=\"nofollow noreferrer\">wp_print_scripts</a></p>\n" }, { "answer_id": 363627, "author": "Stoian Delev", "author_id": 185752, "author_profile": "https://wordpress.stackexchange.com/users/185752", "pm_score": 2, "selected": false, "text": "<p>my solution for this is :</p>\n<ul>\n<li>make an option field in db</li>\n<li>activate sessions and secure them</li>\n</ul>\n<p>Functions I used</p>\n<p>I've start whit two functions from user cybmeta :\njust add a handle to result.</p>\n<pre><code>function theme_list_scripts() {\n\n global $wp_scripts;\n global $enqueued_scripts;\n $enqueued_scripts = array();\n foreach( $wp_scripts-&gt;queue as $handle ) {\n $enqueued_scripts[] = $handle.&quot; | &quot;.$wp_scripts-&gt;registered[$handle]-&gt;src;\n }\n return $enqueued_scripts;\n\n\n}\n\nfunction theme_list_styles() {\n\n global $wp_styles;\n global $enqueued_styles;\n $enqueued_styles = array();\n foreach( $wp_styles-&gt;queue as $handle ) {\n $enqueued_styles[] = $handle.&quot; | &quot;.$wp_styles-&gt;registered[$handle]-&gt;src;\n }\n return $enqueued_styles;\n\n}\n\nadd_action( 'wp_print_scripts', 'wpcustom_inspect_scripts_and_styles' );\n\nfunction wpcustom_inspect_scripts_and_styles(){\n\n $loadet_list = array();\n\n $loadet_list[&quot;style&quot;] = implode( &quot; ; &quot;,theme_list_styles() );\n\n $loadet_list[&quot;script&quot;] = implode( &quot; ; &quot;,theme_list_scripts() );\n\n $_SESSION[&quot;front-end-list&quot;] = implode(&quot;{}&quot;,$loadet_list); \n\n\n}\n\nfunction front_loadet_files_list(){\n\n update_option( 'front_incl_list', $_SESSION[&quot;front-end-list&quot;] );\n\n} \n</code></pre>\n<p>in header file call after wp_head() befor colosing head tag :</p>\n<pre><code>front_loadet_files_list(); \n</code></pre>\n<p>in admin side in the file template where you wanna display :</p>\n<p>get the data from option field in db</p>\n<pre><code>$loadet_list = prep_front_list(&quot;front-end-list&quot;);\n</code></pre>\n<p>call it for displaying</p>\n<pre><code>display_front_list($loadet_list[&quot;styles&quot;]);\n\ndisplay_front_list($loadet_list[&quot;scripts&quot;]);\n</code></pre>\n<p>the result<a href=\"https://i.stack.imgur.com/SV8eS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SV8eS.png\" alt=\"result view\" /></a></p>\n" }, { "answer_id": 396339, "author": "Geza Gog", "author_id": 143893, "author_profile": "https://wordpress.stackexchange.com/users/143893", "pm_score": 0, "selected": false, "text": "<p>to get registered scripts you need function wp_scripts() and to get all enqueued styles you can use the function wp_styles().\nAdding proper priority is also an important aspect to make sure to list the scripts after all of them were registered</p>\n<p>something like this:</p>\n<pre><code>&lt;?php\n\n/*\nPlugin name: My Plugin to list scripts and styles\n*/\n\n\nadd_action( 'wp_enqueue_scripts', 'my_plugin_print_styles', PHP_INT_MAX );\n\nfunction my_plugin_print_styles(){\n $wp_scripts = wp_scripts();\n $wp_styles = wp_styles();\n var_dump($wp_scripts);\n var_dump($wp_styles);\n}\n</code></pre>\n" } ]
2016/07/25
[ "https://wordpress.stackexchange.com/questions/233140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51540/" ]
I'm creating a plugin and I want to get the list of all scripts and CSS used by other plugins. This is my function: ``` function crunchify_print_scripts_styles() { $result = []; $result['scripts'] = []; $result['styles'] = []; // Print all loaded Scripts global $wp_scripts; foreach( $wp_scripts->queue as $script ) : $result['scripts'][] = $wp_scripts->registered[$script]->src . ";"; endforeach; // Print all loaded Styles (CSS) global $wp_styles; foreach( $wp_styles->queue as $style ) : $result['styles'][] = $wp_styles->registered[$style]->src . ";"; endforeach; return $result; } add_action( 'wp_enqueue_scripts', 'crunchify_print_scripts_styles'); ``` I want to get the returned value inside a variable. I tried this: ``` $toto = do_action( 'crunchify_print_scripts_styles' ); var_dump( $toto ); ``` And this is my result: ``` NULL ``` If I write `echo` inside every `foreach` loop, I get the correct results, but how to store these values inside a variable? [edit] My code inside a pluginm which is not working too ``` /** * Get all scripts and styles from Wordpress */ function print_scripts_styles() { $result = []; $result['scripts'] = []; $result['styles'] = []; // Print all loaded Scripts global $wp_scripts; foreach( $wp_scripts->queue as $script ) : $result['scripts'][] = $wp_scripts->registered[$script]->src . ";"; endforeach; // Print all loaded Styles (CSS) global $wp_styles; foreach( $wp_styles->queue as $style ) : $result['styles'][] = $wp_styles->registered[$style]->src . ";"; endforeach; return $result; } add_action( 'wp_head', 'wp_rest_assets_init'); /** * Init JSON REST API Assets routes. * * @since 1.0.0 */ function wp_rest_assets_init() { $all_the_scripts_and_styles = print_scripts_styles(); if ( ! defined( 'JSON_API_VERSION' ) && ! in_array( 'json-rest-api/plugin.php', get_option( 'active_plugins' ) ) ) { $class = new WP_REST_Assets(); $class::$scriptsAndStyles = $all_the_scripts_and_styles; add_filter( 'rest_api_init', array( $class, 'register_routes' ) ); } else { $class = new WP_JSON_Menus(); add_filter( 'json_endpoints', array( $class, 'register_routes' ) ); } } add_action( 'init', 'wp_rest_assets_init' ); ```
`do_action` doesn't quite work like that. When you call `do_action('crunchify_print_scripts_styles')` WP looks at its list of registered actions and filters for any that are attached to a hook called `crunchify_print_scripts_styles` and then runs those functions. And you probably want to remove this: ``` add_action( 'wp_enqueue_scripts', 'crunchify_print_scripts_styles'); ``` ... because you aren't able to get the return result of your function. Also when you use this particular hook you can't guarantee that other functions don't enqueue more scripts or styles *after* you've generated your list. Use a hook that fires after all scripts and styles have been enqueued, such as wp\_head, for convenience, or better still just call your function within your theme when you want to display the result. Reworking your code like this should work... ``` function crunchify_print_scripts_styles() { $result = []; $result['scripts'] = []; $result['styles'] = []; // Print all loaded Scripts global $wp_scripts; foreach( $wp_scripts->queue as $script ) : $result['scripts'][] = $wp_scripts->registered[$script]->src . ";"; endforeach; // Print all loaded Styles (CSS) global $wp_styles; foreach( $wp_styles->queue as $style ) : $result['styles'][] = $wp_styles->registered[$style]->src . ";"; endforeach; return $result; } ``` Then within your theme: ``` print_r( crunchify_print_scripts_styles() ); ``` ... will show you the results for debugging, or of course... ``` $all_the_scripts_and_styles = crunchify_print_scripts_styles(); ``` ... will give you the list to manipulate. Calling it in the theme makes sure you call it after all scripts and styles are enqueued. To call it from your plugin, attach it to any hook that runs later than wp\_enqueue\_scripts, like wp\_head as I mentioned above: ``` add_action( 'wp_head', 'wpse_233142_process_list'); function wpse_233142_process_list() { $all_the_scripts_and_styles = crunchify_print_scripts_styles(); // process your array here } ```
233,151
<p>I'm using this technique: <a href="https://stackoverflow.com/questions/27323460/how-to-label-payments-in-gravity-forms-paypal-pro">https://stackoverflow.com/questions/27323460/how-to-label-payments-in-gravity-forms-paypal-pro</a></p> <p>To add comments to the paypal comments field from a gravity form. However, it's a multisite configuration. I'd like to modify it so the filter only triggers on blog_id 2</p> <p>What's the proper method to make this conditional?</p> <p>Much thanks.</p>
[ { "answer_id": 233142, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 5, "selected": true, "text": "<p><code>do_action</code> doesn't quite work like that. When you call <code>do_action('crunchify_print_scripts_styles')</code> WP looks at its list of registered actions and filters for any that are attached to a hook called <code>crunchify_print_scripts_styles</code> and then runs those functions.</p>\n\n<p>And you probably want to remove this:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'crunchify_print_scripts_styles');\n</code></pre>\n\n<p>... because you aren't able to get the return result of your function.</p>\n\n<p>Also when you use this particular hook you can't guarantee that other functions don't enqueue more scripts or styles <em>after</em> you've generated your list. Use a hook that fires after all scripts and styles have been enqueued, such as wp_head, for convenience, or better still just call your function within your theme when you want to display the result.</p>\n\n<p>Reworking your code like this should work...</p>\n\n<pre><code>function crunchify_print_scripts_styles() {\n\n $result = [];\n $result['scripts'] = [];\n $result['styles'] = [];\n\n // Print all loaded Scripts\n global $wp_scripts;\n foreach( $wp_scripts-&gt;queue as $script ) :\n $result['scripts'][] = $wp_scripts-&gt;registered[$script]-&gt;src . \";\";\n endforeach;\n\n // Print all loaded Styles (CSS)\n global $wp_styles;\n foreach( $wp_styles-&gt;queue as $style ) :\n $result['styles'][] = $wp_styles-&gt;registered[$style]-&gt;src . \";\";\n endforeach;\n\n return $result;\n}\n</code></pre>\n\n<p>Then within your theme:</p>\n\n<pre><code>print_r( crunchify_print_scripts_styles() );\n</code></pre>\n\n<p>... will show you the results for debugging, or of course...</p>\n\n<pre><code>$all_the_scripts_and_styles = crunchify_print_scripts_styles();\n</code></pre>\n\n<p>... will give you the list to manipulate.</p>\n\n<p>Calling it in the theme makes sure you call it after all scripts and styles are enqueued.</p>\n\n<p>To call it from your plugin, attach it to any hook that runs later than wp_enqueue_scripts, like wp_head as I mentioned above:</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_233142_process_list');\n\nfunction wpse_233142_process_list() {\n\n $all_the_scripts_and_styles = crunchify_print_scripts_styles();\n // process your array here\n\n}\n</code></pre>\n" }, { "answer_id": 233152, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": false, "text": "<p>You could use <a href=\"https://developer.wordpress.org/reference/hooks/wp_print_scripts/\" rel=\"noreferrer\"><code>wp_print_scripts</code></a> and <a href=\"https://developer.wordpress.org/reference/hooks/wp_print_styles/\" rel=\"noreferrer\"><code>wp_print_styles</code></a> actions to <strong>timely and properly</strong> access to enqueued scripts and styles, as these actions are the last events before scripts and styles are included in the document and, because of that, the last event where modifications on <code>$wp_styles</code> or <code>$wp_scripts</code> could have effect on styles and scripts included in the document.</p>\n\n<p>So, they are the events where you can be more confident that <code>$wp_styles</code> and <code>$wp_scripts</code> contain the scripts and styles effectively included in the document.</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'cyb_list_scripts' );\nfunction cyb_list_scripts() {\n global $wp_scripts;\n $enqueued_scripts = array();\n foreach( $wp_scripts-&gt;queue as $handle ) {\n $enqueued_scripts[] = $wp_scripts-&gt;registered[$handle]-&gt;src;\n }\n}\nadd_action( 'wp_print_styles', 'cyb_list_styles' );\nfunction cyb_list_styles() {\n global $wp_styles;\n $enqueued_styles = array();\n foreach( $wp_styles-&gt;queue as $handle ) {\n $enqueued_styles[] = $wp_styles-&gt;registered[$handle]-&gt;src;\n }\n}\n</code></pre>\n\n<p>If you declare <code>$enqueued_scripts</code> adn <code>$enqueued_styles</code> as global variables (or any other valid scope, for example you could store it in a method's property), you could access to the list of script and styles in a later action.</p>\n\n<p>For example (just a quick example):</p>\n\n<pre><code>global $enqueued_scripts;\nglobal $enqueued_styles;\n\nadd_action( 'wp_print_scripts', 'cyb_list_scripts' );\nfunction cyb_list_scripts() {\n global $wp_scripts;\n global $enqueued_scripts;\n $enqueued_scripts = array();\n foreach( $wp_scripts-&gt;queue as $handle ) {\n $enqueued_scripts[] = $wp_scripts-&gt;registered[$handle]-&gt;src;\n }\n}\nadd_action( 'wp_print_styles', 'cyb_list_styles' );\nfunction cyb_list_styles() {\n global $wp_styles;\n global $enqueued_styles;\n $enqueued_styles = array();\n foreach( $wp_styles-&gt;queue as $handle ) {\n $enqueued_styles[] = $wp_styles-&gt;registered[$handle]-&gt;src;\n }\n}\n\nadd_action( 'wp_head', function() {\n global $enqueued_scripts;\n var_dump( $enqueued_scripts );\n global $enqueued_styles;\n var_dump( $enqueued_styles );\n} );\n</code></pre>\n" }, { "answer_id": 325973, "author": "theuberdog", "author_id": 157377, "author_profile": "https://wordpress.stackexchange.com/users/157377", "pm_score": 0, "selected": false, "text": "<p>If you truly want to get a list of <strong>all</strong> styles, you can use the new <em>'script_loader_tag'</em> filter (Since Version 4.1). </p>\n\n<p>The \"wp_print_scripts\" is: </p>\n\n<blockquote>\n <p>Called by admin-header.php and ‘wp_head’ hook.</p>\n</blockquote>\n\n<p>i.e it doesn't show scripts in the footer.</p>\n\n<p><strong>References:</strong></p>\n\n<p><a href=\"https://matthewhorne.me/defer-async-wordpress-scripts/\" rel=\"nofollow noreferrer\">Add Defer &amp; Async Attributes to WordPress Scripts</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_print_scripts/\" rel=\"nofollow noreferrer\">wp_print_scripts</a></p>\n" }, { "answer_id": 363627, "author": "Stoian Delev", "author_id": 185752, "author_profile": "https://wordpress.stackexchange.com/users/185752", "pm_score": 2, "selected": false, "text": "<p>my solution for this is :</p>\n<ul>\n<li>make an option field in db</li>\n<li>activate sessions and secure them</li>\n</ul>\n<p>Functions I used</p>\n<p>I've start whit two functions from user cybmeta :\njust add a handle to result.</p>\n<pre><code>function theme_list_scripts() {\n\n global $wp_scripts;\n global $enqueued_scripts;\n $enqueued_scripts = array();\n foreach( $wp_scripts-&gt;queue as $handle ) {\n $enqueued_scripts[] = $handle.&quot; | &quot;.$wp_scripts-&gt;registered[$handle]-&gt;src;\n }\n return $enqueued_scripts;\n\n\n}\n\nfunction theme_list_styles() {\n\n global $wp_styles;\n global $enqueued_styles;\n $enqueued_styles = array();\n foreach( $wp_styles-&gt;queue as $handle ) {\n $enqueued_styles[] = $handle.&quot; | &quot;.$wp_styles-&gt;registered[$handle]-&gt;src;\n }\n return $enqueued_styles;\n\n}\n\nadd_action( 'wp_print_scripts', 'wpcustom_inspect_scripts_and_styles' );\n\nfunction wpcustom_inspect_scripts_and_styles(){\n\n $loadet_list = array();\n\n $loadet_list[&quot;style&quot;] = implode( &quot; ; &quot;,theme_list_styles() );\n\n $loadet_list[&quot;script&quot;] = implode( &quot; ; &quot;,theme_list_scripts() );\n\n $_SESSION[&quot;front-end-list&quot;] = implode(&quot;{}&quot;,$loadet_list); \n\n\n}\n\nfunction front_loadet_files_list(){\n\n update_option( 'front_incl_list', $_SESSION[&quot;front-end-list&quot;] );\n\n} \n</code></pre>\n<p>in header file call after wp_head() befor colosing head tag :</p>\n<pre><code>front_loadet_files_list(); \n</code></pre>\n<p>in admin side in the file template where you wanna display :</p>\n<p>get the data from option field in db</p>\n<pre><code>$loadet_list = prep_front_list(&quot;front-end-list&quot;);\n</code></pre>\n<p>call it for displaying</p>\n<pre><code>display_front_list($loadet_list[&quot;styles&quot;]);\n\ndisplay_front_list($loadet_list[&quot;scripts&quot;]);\n</code></pre>\n<p>the result<a href=\"https://i.stack.imgur.com/SV8eS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SV8eS.png\" alt=\"result view\" /></a></p>\n" }, { "answer_id": 396339, "author": "Geza Gog", "author_id": 143893, "author_profile": "https://wordpress.stackexchange.com/users/143893", "pm_score": 0, "selected": false, "text": "<p>to get registered scripts you need function wp_scripts() and to get all enqueued styles you can use the function wp_styles().\nAdding proper priority is also an important aspect to make sure to list the scripts after all of them were registered</p>\n<p>something like this:</p>\n<pre><code>&lt;?php\n\n/*\nPlugin name: My Plugin to list scripts and styles\n*/\n\n\nadd_action( 'wp_enqueue_scripts', 'my_plugin_print_styles', PHP_INT_MAX );\n\nfunction my_plugin_print_styles(){\n $wp_scripts = wp_scripts();\n $wp_styles = wp_styles();\n var_dump($wp_scripts);\n var_dump($wp_styles);\n}\n</code></pre>\n" } ]
2016/07/25
[ "https://wordpress.stackexchange.com/questions/233151", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78660/" ]
I'm using this technique: <https://stackoverflow.com/questions/27323460/how-to-label-payments-in-gravity-forms-paypal-pro> To add comments to the paypal comments field from a gravity form. However, it's a multisite configuration. I'd like to modify it so the filter only triggers on blog\_id 2 What's the proper method to make this conditional? Much thanks.
`do_action` doesn't quite work like that. When you call `do_action('crunchify_print_scripts_styles')` WP looks at its list of registered actions and filters for any that are attached to a hook called `crunchify_print_scripts_styles` and then runs those functions. And you probably want to remove this: ``` add_action( 'wp_enqueue_scripts', 'crunchify_print_scripts_styles'); ``` ... because you aren't able to get the return result of your function. Also when you use this particular hook you can't guarantee that other functions don't enqueue more scripts or styles *after* you've generated your list. Use a hook that fires after all scripts and styles have been enqueued, such as wp\_head, for convenience, or better still just call your function within your theme when you want to display the result. Reworking your code like this should work... ``` function crunchify_print_scripts_styles() { $result = []; $result['scripts'] = []; $result['styles'] = []; // Print all loaded Scripts global $wp_scripts; foreach( $wp_scripts->queue as $script ) : $result['scripts'][] = $wp_scripts->registered[$script]->src . ";"; endforeach; // Print all loaded Styles (CSS) global $wp_styles; foreach( $wp_styles->queue as $style ) : $result['styles'][] = $wp_styles->registered[$style]->src . ";"; endforeach; return $result; } ``` Then within your theme: ``` print_r( crunchify_print_scripts_styles() ); ``` ... will show you the results for debugging, or of course... ``` $all_the_scripts_and_styles = crunchify_print_scripts_styles(); ``` ... will give you the list to manipulate. Calling it in the theme makes sure you call it after all scripts and styles are enqueued. To call it from your plugin, attach it to any hook that runs later than wp\_enqueue\_scripts, like wp\_head as I mentioned above: ``` add_action( 'wp_head', 'wpse_233142_process_list'); function wpse_233142_process_list() { $all_the_scripts_and_styles = crunchify_print_scripts_styles(); // process your array here } ```
233,170
<p>I'm having an issue saving post meta on all post types, both default and custom. I'm hooking in to <strong>save_post</strong> to run my function, and what's happening is that the post meta gets added, but then immediately deleted. This is what I have right now:</p> <pre><code>function saveSidebarMeta($postId) { $toAdd = $_POST['collection-topics']; foreach ($toAdd as $topic) { add_post_meta($postId, 'collection-topic', $topic); } } add_action('save_post', 'saveSidebarMeta', 100); </code></pre> <p>Right now, I have the priority set at 100, and that does save the post meta, but then if the page is saved again the post meta gets deleted unless the correct info is added and I don't want it to be deleting and adding the data every time someone saves a post.</p> <p>If the priority is set to the default 10, the data does get saved, but then immediately deleted. I know this because 1.) <strong>add_post_meta()</strong> returns the meta_key, which is then absent from the database and 2.) if I put a <strong>die()</strong> statement right after <strong>add_post_meta()</strong>, the meta data shows in the table.</p> <p>I have other functions saving post meta just fine. Am I missing something really simple here? I've been looking through this issue for a while and have run out of places to look or directions to go in for a solution. Any help would be appreciated. Thanks!</p>
[ { "answer_id": 233174, "author": "stoi2m1", "author_id": 10907, "author_profile": "https://wordpress.stackexchange.com/users/10907", "pm_score": 1, "selected": false, "text": "<p>Are you outputting the saved data to the edit post page before saving the post? If not you may be getting a empty $_POST['collection-topics'] data and then saving empty or null data.</p>\n\n<p>I would do a check before doing <code>add_post_meta()</code></p>\n\n<pre><code>if ( empty($_POST['collection-topics']) ) return;\n</code></pre>\n" }, { "answer_id": 233197, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>Here's a start, but we also need to see the code that generates the form.</p>\n\n<p>One possibility is that auto-save is messing you up, so try this variation on your code.</p>\n\n<pre><code>add_action('save_post', 'saveSidebarMeta', 100);\n\nfunction saveSidebarMeta( $postId ) {\n\n if ( defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) {\n return $post_id;\n } else { \n\n $toAdd = $_POST['collection-topics'];\n foreach ($toAdd as $topic) {\n add_post_meta($postId, 'collection-topic', $topic);\n }\n }\n\n}\n</code></pre>\n\n<p>But if we can see your form generating code too I might be able to expand this further.</p>\n" } ]
2016/07/25
[ "https://wordpress.stackexchange.com/questions/233170", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/34129/" ]
I'm having an issue saving post meta on all post types, both default and custom. I'm hooking in to **save\_post** to run my function, and what's happening is that the post meta gets added, but then immediately deleted. This is what I have right now: ``` function saveSidebarMeta($postId) { $toAdd = $_POST['collection-topics']; foreach ($toAdd as $topic) { add_post_meta($postId, 'collection-topic', $topic); } } add_action('save_post', 'saveSidebarMeta', 100); ``` Right now, I have the priority set at 100, and that does save the post meta, but then if the page is saved again the post meta gets deleted unless the correct info is added and I don't want it to be deleting and adding the data every time someone saves a post. If the priority is set to the default 10, the data does get saved, but then immediately deleted. I know this because 1.) **add\_post\_meta()** returns the meta\_key, which is then absent from the database and 2.) if I put a **die()** statement right after **add\_post\_meta()**, the meta data shows in the table. I have other functions saving post meta just fine. Am I missing something really simple here? I've been looking through this issue for a while and have run out of places to look or directions to go in for a solution. Any help would be appreciated. Thanks!
Are you outputting the saved data to the edit post page before saving the post? If not you may be getting a empty $\_POST['collection-topics'] data and then saving empty or null data. I would do a check before doing `add_post_meta()` ``` if ( empty($_POST['collection-topics']) ) return; ```
233,184
<p>I know this question has been asked many times. I even spent the entire day yesterday getting things to work but to no avail. I am pretty sure I am missing out on something small//silly but I am unable to figure it out.</p> <p>So, here is my question: I have purchased the Identity-vcard theme from Envato and I want to make some modifications to the child theme without disturbing the parent theme. But the style.css of the child theme is not loading/overriding the parent’s. I am using this in the functions.php</p> <pre><code>function my_theme_enqueue_styles() { $parent_style = ‘Identity-vcard-style’; wp_enqueue_style( $parent_style, get_template_directory_uri() . ‘/style.css’ ); wp_enqueue_style( ‘Identity-vcard-child-style’, get_stylesheet_uri() . ‘/style.css’, array( $parent_style ) ); } add_action( ‘wp_enqueue_scripts’, ‘my_theme_enqueue_styles’ ); </code></pre> <p>Can you please help me with this?</p> <p>Thanks!</p>
[ { "answer_id": 233185, "author": "ngearing", "author_id": 50184, "author_profile": "https://wordpress.stackexchange.com/users/50184", "pm_score": 2, "selected": false, "text": "<p>You are using <code>get_stylesheet_uri()</code> which links directly to your stylesheet, then your adding /style.css which is resulting in an invalid url.</p>\n\n<p>So you need to remove the <code>/style.css</code>.</p>\n\n<p>Or use <code>get_stylesheet_directory_uri()</code> and leave the <code>/style.css</code> on there.</p>\n" }, { "answer_id": 233186, "author": "user3498047", "author_id": 98955, "author_profile": "https://wordpress.stackexchange.com/users/98955", "pm_score": 0, "selected": false, "text": "<p>Make sure you use get_stylesheet_directory_uri() in child theme and make sure that the parent theme is using get_template_directory_uri().</p>\n\n<p>If the parent theme is not using get_template_directory_uri() you'll have to unregister the main style and register it again in your child theme.</p>\n\n<p>Cheers!</p>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233184", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98954/" ]
I know this question has been asked many times. I even spent the entire day yesterday getting things to work but to no avail. I am pretty sure I am missing out on something small//silly but I am unable to figure it out. So, here is my question: I have purchased the Identity-vcard theme from Envato and I want to make some modifications to the child theme without disturbing the parent theme. But the style.css of the child theme is not loading/overriding the parent’s. I am using this in the functions.php ``` function my_theme_enqueue_styles() { $parent_style = ‘Identity-vcard-style’; wp_enqueue_style( $parent_style, get_template_directory_uri() . ‘/style.css’ ); wp_enqueue_style( ‘Identity-vcard-child-style’, get_stylesheet_uri() . ‘/style.css’, array( $parent_style ) ); } add_action( ‘wp_enqueue_scripts’, ‘my_theme_enqueue_styles’ ); ``` Can you please help me with this? Thanks!
You are using `get_stylesheet_uri()` which links directly to your stylesheet, then your adding /style.css which is resulting in an invalid url. So you need to remove the `/style.css`. Or use `get_stylesheet_directory_uri()` and leave the `/style.css` on there.
233,193
<p>My site has recently been compromised. If I restore the full database, google says there is hacked content on my site. The hacker has created many new garbage posts in my site - which already got listed on google SERP. </p> <p>Is there a way how I can restore only my actual posts one by one on the freshly installed WordPress database or cleanup the database and restore fully? </p> <p>I have the backup of the compromised database. I have to build the site again from scratch if I can't restore my posts.</p>
[ { "answer_id": 233201, "author": "johncarter", "author_id": 26536, "author_profile": "https://wordpress.stackexchange.com/users/26536", "pm_score": -1, "selected": false, "text": "<p>You can restore the <strong>full database</strong> and use <a href=\"https://en-gb.wordpress.org/plugins/bulk-delete/\" rel=\"nofollow\">Bulk Delete</a> to delete the unwanted posts.</p>\n\n<p>Use the plugin filters to detect the spam posts by <em>age</em>, <em>category</em> or <em>author</em>. </p>\n\n<p>I would also recommend you temporarily install <a href=\"https://en-gb.wordpress.org/plugins/wordfence/\" rel=\"nofollow\">WordFence Security</a> and run a scan to make sure you are all clear.</p>\n" }, { "answer_id": 233228, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>Take a copy of your data file and store it safely just in case you mess up - it's easily done. Make sure it is labelled as hacked so you can't accidentally use it anywhere.</p>\n\n<p>Look in your SQL for a section starting with:</p>\n\n<pre><code>INSERT INTO `wp_posts` VALUES\n</code></pre>\n\n<p>and eventually ending with a semicolon.</p>\n\n<p>This is all of your post data. Hopefully you have one line for each post otherwise this will be very hard. <strong>This does not include any categories, tags or custom fields.</strong></p>\n\n<p>You will hopefully see lines starting something like this:</p>\n\n<pre><code>INSERT INTO `wp_posts` VALUES (1,1,'2015-03-03 11:42:37','20\n(2,1,'2015-03-03 11:42:37','2015-03-03 11:42:37','what is th\n(3,1,'2015-03-03 11:51:21','0000-00-00 00:00:00','','Auto Dr\n(5,1,'2015-03-03 11:54:41','2015-03-03 11:54:41','','Berry a\n(6,1,'2015-03-03 11:55:16','2015-03-03 11:55:16','what is th\n(7,1,'2015-03-03 11:55:21','0000-00-00 00:00:00','','Auto Dr\n(8,1,'2015-03-03 12:00:01','2015-03-03 12:00:01','We are a n\n(9,1,'2015-03-03 12:00:01','2015-03-03 12:00:01','We are a n\n(10,1,'2015-03-03 12:01:30','2015-03-03 12:01:30','Due to th\n(11,1,'2015-03-03 12:01:30','2015-03-03 12:01:30','Due to th\n(12,1,'2015-03-03 12:01:43','2015-03-03 12:01:43','Applicati\n(13,1,'2015-03-03 12:01:43','2015-03-03 12:01:43','Applicati\n(14,1,'2015-03-03 12:02:06','2015-03-03 12:02:06','Participa\n(15,1,'2015-03-03 12:02:06','2015-03-03 12:02:06','Participa\n(16,1,'2015-03-03 12:03:16','2015-03-03 12:03:16','Walk for \n(17,1,'2015-03-03 12:03:13','2015-03-03 12:03:13','','461569\n</code></pre>\n\n<p>You \"simply\" (and this can be slow, careful work) want to delete the lines which have hacked data in. Any line that doesn't look like your original post can go.</p>\n\n<p>Examining one of those lines in detail and formatting it to see what's what:</p>\n\n<pre><code>INSERT INTO `wp_posts` VALUES (\n1, -- this is the Post ID\n1, -- this is the author ID\n'2015-03-03 11:42:37', -- post date\n'2015-03-03 11:42:37', -- post date in GMT\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>'Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!',\n</code></pre>\n\n<p>That field is your post content. If that looks like you don't want it in your database then delete the <em>whole line</em> from <code>(</code> up to <code>),</code></p>\n\n<pre><code>'Hello world!', -- Post title\n'', -- Excerpt\n'publish', -- status - all live posts will have \"publish\" here\n\n-- and so on\n'open','open','','hello-world','','',\n'2015-03-03 11:42:37','2015-03-03 11:42:37',\n'',0,'http://testsite.localhost/?p=1',0,'post','',1),\n</code></pre>\n\n<p>If any fields have something in that isn't plain English (if English your posts are) or clearly a simple value, date or URL related to your site then get rid of the line.</p>\n\n<p>While doing this manually can be done, if there are many posts I would really consider getting someone who knows their way around WP &amp; MySQL to clean the data for you. (Not me at the moment, I should add!!)</p>\n\n<p>Backup your clean site before trying to import records just in case.</p>\n\n<p>Good luck!</p>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233193", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67533/" ]
My site has recently been compromised. If I restore the full database, google says there is hacked content on my site. The hacker has created many new garbage posts in my site - which already got listed on google SERP. Is there a way how I can restore only my actual posts one by one on the freshly installed WordPress database or cleanup the database and restore fully? I have the backup of the compromised database. I have to build the site again from scratch if I can't restore my posts.
Take a copy of your data file and store it safely just in case you mess up - it's easily done. Make sure it is labelled as hacked so you can't accidentally use it anywhere. Look in your SQL for a section starting with: ``` INSERT INTO `wp_posts` VALUES ``` and eventually ending with a semicolon. This is all of your post data. Hopefully you have one line for each post otherwise this will be very hard. **This does not include any categories, tags or custom fields.** You will hopefully see lines starting something like this: ``` INSERT INTO `wp_posts` VALUES (1,1,'2015-03-03 11:42:37','20 (2,1,'2015-03-03 11:42:37','2015-03-03 11:42:37','what is th (3,1,'2015-03-03 11:51:21','0000-00-00 00:00:00','','Auto Dr (5,1,'2015-03-03 11:54:41','2015-03-03 11:54:41','','Berry a (6,1,'2015-03-03 11:55:16','2015-03-03 11:55:16','what is th (7,1,'2015-03-03 11:55:21','0000-00-00 00:00:00','','Auto Dr (8,1,'2015-03-03 12:00:01','2015-03-03 12:00:01','We are a n (9,1,'2015-03-03 12:00:01','2015-03-03 12:00:01','We are a n (10,1,'2015-03-03 12:01:30','2015-03-03 12:01:30','Due to th (11,1,'2015-03-03 12:01:30','2015-03-03 12:01:30','Due to th (12,1,'2015-03-03 12:01:43','2015-03-03 12:01:43','Applicati (13,1,'2015-03-03 12:01:43','2015-03-03 12:01:43','Applicati (14,1,'2015-03-03 12:02:06','2015-03-03 12:02:06','Participa (15,1,'2015-03-03 12:02:06','2015-03-03 12:02:06','Participa (16,1,'2015-03-03 12:03:16','2015-03-03 12:03:16','Walk for (17,1,'2015-03-03 12:03:13','2015-03-03 12:03:13','','461569 ``` You "simply" (and this can be slow, careful work) want to delete the lines which have hacked data in. Any line that doesn't look like your original post can go. Examining one of those lines in detail and formatting it to see what's what: ``` INSERT INTO `wp_posts` VALUES ( 1, -- this is the Post ID 1, -- this is the author ID '2015-03-03 11:42:37', -- post date '2015-03-03 11:42:37', -- post date in GMT ``` and then: ``` 'Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!', ``` That field is your post content. If that looks like you don't want it in your database then delete the *whole line* from `(` up to `),` ``` 'Hello world!', -- Post title '', -- Excerpt 'publish', -- status - all live posts will have "publish" here -- and so on 'open','open','','hello-world','','', '2015-03-03 11:42:37','2015-03-03 11:42:37', '',0,'http://testsite.localhost/?p=1',0,'post','',1), ``` If any fields have something in that isn't plain English (if English your posts are) or clearly a simple value, date or URL related to your site then get rid of the line. While doing this manually can be done, if there are many posts I would really consider getting someone who knows their way around WP & MySQL to clean the data for you. (Not me at the moment, I should add!!) Backup your clean site before trying to import records just in case. Good luck!
233,199
<p>I've created a custom field in user profile where upload a profile image. It's very simple.</p> <p>To create fields I've used:</p> <pre><code>add_action( 'show_user_profile', 'cover_image_function' ); add_action( 'edit_user_profile', 'cover_image_function' ); function cover_image_function( $user ) { &lt;h3&gt;Cover Image&lt;/h3&gt; &lt;style type="text/css"&gt; .fh-profile-upload-options th, .fh-profile-upload-options td, .fh-profile-upload-options input { vertical-align: top; } .user-preview-image { display: block; height: auto; width: 300px; } &lt;/style&gt; &lt;table class="form-table fh-profile-upload-options"&gt; &lt;tr&gt; &lt;th&gt; &lt;label for="image"&gt;Cover Image&lt;/label&gt; &lt;/th&gt; &lt;td&gt; &lt;img class="user-preview-image" src="&lt;?php echo esc_attr( get_the_author_meta( 'mycoverimage', $user-&gt;ID ) ); ?&gt;"&gt; &lt;input type="text" name="mycoverimage" id="mycoverimage" value="&lt;?php echo esc_attr( get_the_author_meta( 'mycoverimage', $user-&gt;ID ) ); ?&gt;" class="regular-text" /&gt; &lt;input type='button' class="button-primary" value="Upload Image" id="coverimage"/&gt;&lt;br /&gt; &lt;span class="description"&gt;Please upload your cover image.&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;script type="text/javascript"&gt; (function( $ ) { $( 'input#coverimage' ).on('click', function() { tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true'); window.send_to_editor = function( html ) { imgurl = $( 'img', html ).attr( 'src' ); $( '#mycoverimage' ).val(imgurl); tb_remove(); } return false; }); })(jQuery); &lt;/script&gt; } </code></pre> <p>To save my image:</p> <pre><code>add_action( 'personal_options_update', 'save_cover_image' ); add_action( 'edit_user_profile_update', 'save_cover_image' ); function save_cover_image( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] ); } </code></pre> <p>Everything works fine but I can't retrieve the <code>attachment ID</code> for generating the <strong>thumbnails and smaller sizes</strong>. For now I can just get the url like:</p> <pre><code>echo esc_attr( get_the_author_meta( 'mycoverimage', $user-&gt;ID ) ); </code></pre> <p>I've even used the known method like in other questions:</p> <pre><code>function get_attachment_id($image_url) { global $wpdb; $attachment = $wpdb-&gt;get_col($wpdb-&gt;prepare("SELECT ID FROM $wpdb-&gt;posts WHERE guid='%s';", $image_url )); return $attachment[0]; } </code></pre> <p>But It doesn't work. Is it possible that the image doesn't generate any attachment metadata, while uploading? And how Can I do it? Even suggestions, articles or questions already answered would be appreciated. Everything but a plugin, I want build a custom code. Thanks!</p>
[ { "answer_id": 233202, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>Not sure it will make a difference, but as you just want one value you can get <code>get_var</code> instead of <code>get_col</code>. I tweaked the query slightly to what I know works:</p>\n\n<pre><code>function get_attachment_id($image_url) {\n global $wpdb;\n $attachment = $wpdb-&gt;get_var($wpdb-&gt;prepare(\"SELECT ID FROM \".$wpdb-&gt;prefix.\"posts WHERE post_type='attachment' AND guid='%s'\", $image_url )); \n return $attachment; \n}\n</code></pre>\n\n<p>And making use you are not doing <code>esc_attr</code> on the URL value before sending it to the function or it won't match to it.</p>\n\n<p><strong>EDIT</strong> You could try this to (less strictly) just match the URL path to the <code>guid</code> instead of the full URL:</p>\n\n<pre><code>function get_attachment_id($image_url) {\n $parseurl = parse_url($image_url);\n $path = $parseurl['path'];\n\n global $wpdb;\n $attachments = $wpdb-&gt;get_results(\"SELECT ID,guid FROM \".$wpdb-&gt;prefix.\"posts WHERE post_type='attachment'\");\n foreach ($attachments as $attachment) {\n if (strstr($attachment-&gt;guid,$path)) {return $attachment-&gt;ID;}\n }\n echo \"&lt;!-- All Attachments \"; print_r($attachments); echo \"--&gt;\"; // debug output\n}\n</code></pre>\n" }, { "answer_id": 233207, "author": "middlelady", "author_id": 93927, "author_profile": "https://wordpress.stackexchange.com/users/93927", "pm_score": 3, "selected": true, "text": "<p>I've finally solved! The problem was that simply using</p>\n\n<pre><code>update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] );\n</code></pre>\n\n<p>The image was saved without generating attachment metadata. In fact, checking my table, it got only <code>usermeta id</code> which is not the attachment id. So I had to change a bit my uploading function according to <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_attachment\" rel=\"nofollow\">codex</a> with the use of <code>wp_insert_attachment</code> like:</p>\n\n<pre><code>add_action( 'personal_options_update', 'save_cover_image' );\nadd_action( 'edit_user_profile_update', 'save_cover_image' );\nfunction save_cover_image( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) )\n {\n return false;\n }\n $filename = $_POST['mycoverimage'];\n $parent_post_id = 0;\n $filetype = wp_check_filetype( basename( $filename ), null );\n $wp_upload_dir = wp_upload_dir();\n $attachment = array(\n 'guid' =&gt; $wp_upload_dir['url'] . '/' . basename( $filename ), \n 'post_mime_type' =&gt; $filetype['type'],\n 'post_title' =&gt; preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' =&gt; '',\n 'post_status' =&gt; 'inherit',\n 'post_author' =&gt; $uid\n );\n $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );\n wp_update_attachment_metadata( $attach_id, $attach_data );\n update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] );\n}\n</code></pre>\n\n<p>At this point I have a <code>usermeta id</code> and an <code>attachment id</code> which I can easily retrieve for thumbs and other operations. Thanks to @majick anyway.</p>\n" }, { "answer_id": 233212, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>I suggest you to use the more newer media manager dialog; WordPress will hanlde all the image upload stuff, including generating intermediate sizes and attachement metadata.</p>\n\n<p>Here a working example (it is a quick example built from a previous code, it may needs some tweaks to be used on production):</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'load_wp_media_files' );\nfunction load_wp_media_files( $page ) {\n if( $page == 'profile.php' || $page == 'user-edit.php' ) {\n wp_enqueue_media();\n wp_enqueue_script( 'my_custom_script', plugins_url( '/js/myscript.js' , __FILE__ ), array('jquery'), '0.1' );\n }\n}\n\nadd_action( 'show_user_profile', 'cover_image_function' );\nadd_action( 'edit_user_profile', 'cover_image_function' );\nfunction cover_image_function( $user ) \n{\n $image_id = get_user_meta( $user-&gt;ID, 'mycoverimage', true );\n if( intval( $image_id ) &gt; 0 ) {\n // Change with the image size you want to use\n $image = wp_get_attachment_image( $image_id, 'medium', false, array( 'id' =&gt; 'user-preview-image' ) );\n } else {\n $image = '&lt;img id=\"user-preview-image\" src=\"https://some.default.image.jpg\" /&gt;';\n }\n ?&gt;\n &lt;h3&gt;Cover Image&lt;/h3&gt;\n &lt;style type=\"text/css\"&gt;\n .fh-profile-upload-options th,\n .fh-profile-upload-options td,\n .fh-profile-upload-options input {\n vertical-align: top;\n }\n .user-preview-image {\n display: block;\n height: auto;\n width: 300px;\n }\n &lt;/style&gt;\n &lt;table class=\"form-table fh-profile-upload-options\"&gt;\n &lt;tr&gt;\n &lt;th&gt;\n &lt;label for=\"image\"&gt;Cover Image&lt;/label&gt;\n &lt;/th&gt;\n &lt;td&gt;\n &lt;?php echo $image; ?&gt;\n &lt;input type=\"hidden\" name=\"mycoverimage\" id=\"mycoverimage\" value=\"&lt;?php echo esc_attr( get_the_author_meta( 'mycoverimage', $user-&gt;ID ) ); ?&gt;\" class=\"regular-text\" /&gt;\n &lt;input type='button' class=\"button-primary\" value=\"Upload Image\" id=\"coverimage\"/&gt;&lt;br /&gt;\n &lt;span class=\"description\"&gt;Please upload your cover image.&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;?php\n}\n\nadd_action( 'personal_options_update', 'save_cover_image' );\nadd_action( 'edit_user_profile_update', 'save_cover_image' );\nfunction save_cover_image( $user_id ) {\n if ( ! current_user_can( 'edit_user', $user_id ) )\n {\n return false;\n }\n\n update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] );\n} \n\n\n// Ajax action to refresh the user image\nadd_action( 'wp_ajax_cyb_get_image_url', 'cyb_get_image_url' );\nfunction cyb_get_image_url() {\n if(isset($_GET['id']) ){\n $image = wp_get_attachment_image( filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT ), 'medium', false, array( 'id' =&gt; 'user-preview-image' ) );\n $data = array(\n 'image' =&gt; $image,\n );\n wp_send_json_success( $data );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n\n<p>And myscript.js file:</p>\n\n<pre><code>jQuery(document).ready( function($) {\n\n jQuery('input#coverimage').click(function(e) {\n\n e.preventDefault();\n var image_frame;\n if(image_frame){\n image_frame.open();\n }\n image_frame = wp.media({\n title: 'Select Media',\n multiple : false,\n library : {\n type : 'image',\n }\n });\n\n image_frame.on('close',function() {\n // get selections and save to hidden input plus other AJAX stuff etc.\n var selection = image_frame.state().get('selection');\n var gallery_ids = new Array();\n var my_index = 0;\n selection.each(function(attachment) {\n gallery_ids[my_index] = attachment['id'];\n my_index++;\n });\n var ids = gallery_ids.join(\",\");\n jQuery('input#mycoverimage').val(ids);\n Refresh_Image(ids);\n });\n\n image_frame.on('open',function() {\n var selection = image_frame.state().get('selection');\n ids = jQuery('input#mycoverimage').val().split(',');\n ids.forEach(function(id) {\n attachment = wp.media.attachment(id);\n attachment.fetch();\n selection.add( attachment ? [ attachment ] : [] );\n });\n\n });\n\n image_frame.on('toolbar:create:select',function() {\n\n image_frame.state().set('filterable', 'uploaded');\n\n });\n\n image_frame.open();\n });\n\n});\n\nfunction Refresh_Image(the_id){\n var data = {\n action: 'cyb_get_image_url',\n id: the_id\n };\n\n jQuery.get(ajaxurl, data, function(response) {\n\n if(response.success === true) {\n jQuery('#user-preview-image').replaceWith( response.data.image );\n }\n });\n}\n</code></pre>\n\n<p>Note that <strong>this code stores image id on user meta field</strong> instead of full size image url as you was doing before, so you can get any image size form the user meta field:</p>\n\n<pre><code>$image_id = get_user_meta( $user-&gt;ID, 'mycoverimage', true );\n$fulle_user_image = wp_get_attachment_image( $image_id, 'full' );\n</code></pre>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233199", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93927/" ]
I've created a custom field in user profile where upload a profile image. It's very simple. To create fields I've used: ``` add_action( 'show_user_profile', 'cover_image_function' ); add_action( 'edit_user_profile', 'cover_image_function' ); function cover_image_function( $user ) { <h3>Cover Image</h3> <style type="text/css"> .fh-profile-upload-options th, .fh-profile-upload-options td, .fh-profile-upload-options input { vertical-align: top; } .user-preview-image { display: block; height: auto; width: 300px; } </style> <table class="form-table fh-profile-upload-options"> <tr> <th> <label for="image">Cover Image</label> </th> <td> <img class="user-preview-image" src="<?php echo esc_attr( get_the_author_meta( 'mycoverimage', $user->ID ) ); ?>"> <input type="text" name="mycoverimage" id="mycoverimage" value="<?php echo esc_attr( get_the_author_meta( 'mycoverimage', $user->ID ) ); ?>" class="regular-text" /> <input type='button' class="button-primary" value="Upload Image" id="coverimage"/><br /> <span class="description">Please upload your cover image.</span> </td> </tr> </table> <script type="text/javascript"> (function( $ ) { $( 'input#coverimage' ).on('click', function() { tb_show('', 'media-upload.php?type=image&TB_iframe=true'); window.send_to_editor = function( html ) { imgurl = $( 'img', html ).attr( 'src' ); $( '#mycoverimage' ).val(imgurl); tb_remove(); } return false; }); })(jQuery); </script> } ``` To save my image: ``` add_action( 'personal_options_update', 'save_cover_image' ); add_action( 'edit_user_profile_update', 'save_cover_image' ); function save_cover_image( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] ); } ``` Everything works fine but I can't retrieve the `attachment ID` for generating the **thumbnails and smaller sizes**. For now I can just get the url like: ``` echo esc_attr( get_the_author_meta( 'mycoverimage', $user->ID ) ); ``` I've even used the known method like in other questions: ``` function get_attachment_id($image_url) { global $wpdb; $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); return $attachment[0]; } ``` But It doesn't work. Is it possible that the image doesn't generate any attachment metadata, while uploading? And how Can I do it? Even suggestions, articles or questions already answered would be appreciated. Everything but a plugin, I want build a custom code. Thanks!
I've finally solved! The problem was that simply using ``` update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] ); ``` The image was saved without generating attachment metadata. In fact, checking my table, it got only `usermeta id` which is not the attachment id. So I had to change a bit my uploading function according to [codex](https://codex.wordpress.org/Function_Reference/wp_insert_attachment) with the use of `wp_insert_attachment` like: ``` add_action( 'personal_options_update', 'save_cover_image' ); add_action( 'edit_user_profile_update', 'save_cover_image' ); function save_cover_image( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } $filename = $_POST['mycoverimage']; $parent_post_id = 0; $filetype = wp_check_filetype( basename( $filename ), null ); $wp_upload_dir = wp_upload_dir(); $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), 'post_content' => '', 'post_status' => 'inherit', 'post_author' => $uid ); $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] ); } ``` At this point I have a `usermeta id` and an `attachment id` which I can easily retrieve for thumbs and other operations. Thanks to @majick anyway.
233,256
<p>I want to create a code snippet for expiration of post after x days from the post published date, I tried with this code but I always displays the true condition, what am I doing wrong?</p> <pre><code>$pfx_date = get_the_date('d/m/Y'); $datacorrente = date('d/m/Y', strtotime("-5 days")); if ( $pfx_date &lt;= $datacorrente ) { echo 'post expired'; } else { echo 'post open'; } </code></pre> <p>"-5 days" is the x days variable after the post is expired.</p>
[ { "answer_id": 233258, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>You're comparing strings. For dates this will only ever work out if you use a yyyymmdd format or similar. </p>\n" }, { "answer_id": 233303, "author": "Ismail", "author_id": 70833, "author_profile": "https://wordpress.stackexchange.com/users/70833", "pm_score": 1, "selected": false, "text": "<p>Up-voting Andy's answer, you should be comparing integers to get this working. <a href=\"http://php.net/manual/en/function.strtotime.php\" rel=\"nofollow\"><code>strtotime()</code></a> can turn any string to the time integer, which will be compared later to tell the difference and how many seconds passed until now ( <code>time()</code> ). Something like follows:</p>\n\n<pre><code>$expired = ( ( time() - strtotime(get_the_date('Y-m-d H:i:s')) ) / DAY_IN_SECONDS ) &gt;= 5;\nif ( $expired ) { \n echo 'post expired'; \n} else { \n echo 'post open'; \n}\n</code></pre>\n\n<p>Hope that helps.</p>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233256", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86112/" ]
I want to create a code snippet for expiration of post after x days from the post published date, I tried with this code but I always displays the true condition, what am I doing wrong? ``` $pfx_date = get_the_date('d/m/Y'); $datacorrente = date('d/m/Y', strtotime("-5 days")); if ( $pfx_date <= $datacorrente ) { echo 'post expired'; } else { echo 'post open'; } ``` "-5 days" is the x days variable after the post is expired.
You're comparing strings. For dates this will only ever work out if you use a yyyymmdd format or similar.
233,269
<p>I'm trying to add a local variable to my URL. </p> <p>As an example I have this URL:</p> <pre><code>mysite.com/my-page-name/ </code></pre> <p>And I want to add 'en' variable into it and leave the page working properly:</p> <pre><code>mysite.com/en/my-page-name/ </code></pre> <p>I tried to deal with it using <code>add_rewrite_tag()</code> and <code>add_rewrite_rule()</code> but it isn't working so what am I doing wrong?</p> <pre><code>add_rewrite_tag('%locale%', '^([a-z]{2})'); add_rewrite_rule('^([a-z]{2})/(.+)[/$]', 'index.php?pagename=$matches[2]', 'top'); </code></pre>
[ { "answer_id": 233258, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>You're comparing strings. For dates this will only ever work out if you use a yyyymmdd format or similar. </p>\n" }, { "answer_id": 233303, "author": "Ismail", "author_id": 70833, "author_profile": "https://wordpress.stackexchange.com/users/70833", "pm_score": 1, "selected": false, "text": "<p>Up-voting Andy's answer, you should be comparing integers to get this working. <a href=\"http://php.net/manual/en/function.strtotime.php\" rel=\"nofollow\"><code>strtotime()</code></a> can turn any string to the time integer, which will be compared later to tell the difference and how many seconds passed until now ( <code>time()</code> ). Something like follows:</p>\n\n<pre><code>$expired = ( ( time() - strtotime(get_the_date('Y-m-d H:i:s')) ) / DAY_IN_SECONDS ) &gt;= 5;\nif ( $expired ) { \n echo 'post expired'; \n} else { \n echo 'post open'; \n}\n</code></pre>\n\n<p>Hope that helps.</p>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24891/" ]
I'm trying to add a local variable to my URL. As an example I have this URL: ``` mysite.com/my-page-name/ ``` And I want to add 'en' variable into it and leave the page working properly: ``` mysite.com/en/my-page-name/ ``` I tried to deal with it using `add_rewrite_tag()` and `add_rewrite_rule()` but it isn't working so what am I doing wrong? ``` add_rewrite_tag('%locale%', '^([a-z]{2})'); add_rewrite_rule('^([a-z]{2})/(.+)[/$]', 'index.php?pagename=$matches[2]', 'top'); ```
You're comparing strings. For dates this will only ever work out if you use a yyyymmdd format or similar.
233,283
<p>I'm using a Using modal window with + form to change the profile avatar. Like the following (functions.php):</p> <pre><code>add_action('change_avatar', 'edit_avatar_function'); function edit_avatar_function($uid, $pid) { $av = get_user_meta($uid, 'avatar_' . 'project', true); $avatar = wp_get_attachment_image_src( $av, 'thumb300' ); ?&gt; &lt;div id="avatar-modal" class="modal fade" role="dialog"&gt; &lt;div class="modal-dialog browse-panel"&gt; &lt;div class="box_title"&gt; &lt;?php _e('Edit your Avatar', 'KleeiaDev') ?&gt; &lt;/div&gt; &lt;div class="box_content top-15 text-center" id="my-media"&gt; &lt;form id="change-avatar" action="#" method="post" enctype="multipart/form-data"&gt; &lt;p class="top-20"&gt; &lt;input id="input-avatar" data-buttonText="&lt;?php _e('Upload an image (300x300px)','KleeiaDev'); ?&gt;" type="file" name="avatar" style="display:inline-block!important" class="filestyle avatar" data-icon="false" data-input="false"/&gt; &lt;input id="pid" type="hidden" name="pid" value="&lt;?php echo $pid ?&gt;"/&gt; &lt;input id="uid" type="hidden" name="uid" value="&lt;?php echo $uid ?&gt;"/&gt; &lt;/p&gt; &lt;/form&gt; &lt;p class="top-20"&gt; &lt;button id="upload-avatar" type="button" class="submit_light full_width"&gt;&lt;?php _e('Update Cover image','KleeiaDev') ?&gt;&lt;/button&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I call this modal with <code>&lt;?php do_action('change_avatar', $myuid ); ?&gt;</code> in my page and I send the infos through AJAX, enqueuing the action like this (functions.php)</p> <pre><code>add_action('wp_ajax_update_avatar_function', 'update_avatar_function', 10, 2 ); function update_avatar_function(){ $pid = $_POST['pid']; $uid = $_POST['uid']; $avatar = $_POST['avatar']; //perform update user meta and other stuff //send me back uid and pid to check if they're correct $response = array('uid'=&gt;$uid,'pid'=&gt;$pid); echo json_encode($response); die(); } add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 10, 2 ); function add_frontend_ajax_javascript_file() { wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) ); } </code></pre> <p>At the latest I use this jQuery/AJAX:</p> <pre><code>var updatebuttonav = $('#upload-avatar'); updatebuttonav.on('click', function() { event.preventDefault(); update_avatar(); }); function update_avatar() { var form_data = new FormData($('form#change-avatar')[0]); form_data.append('pid', $('#pid').val()), //no sending value form_data.append('uid', $('#uid').val()), //no sending value form_data.append('avatar', $('#input-avatar')[0].files[0]), //no sending file form_data.append('action', 'update_avatar_function'), console.log(form_data); //here is printing No Properties jQuery.ajax({ method: 'post', url : ajaxurl, dataType: 'json', data: form_data, processData: false, beforeSend:function(data){ //other functions }, success:function(data) { alert(data.uid + data.pid); }, error: function(data){ console.log(data); } }); //alert("a"); } </code></pre> <p>Well, with this I see in my <code>console.log</code> that <strong>No Object Properties</strong> and values are sent. Furthermore the <strong>json response is Nan</strong>. I use this method with other section of my website and I can't see why here It's not working. Is that possible that through <code>do_action</code> the form is not seen? Am I missing something? Any suggestion would be more than appreciated!</p> <p>Note: I'm not using the <code>wp_ajax_nopriv</code> because users I need it when I'm logged of course.</p>
[ { "answer_id": 233285, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 0, "selected": false, "text": "<p>First, I would make sure the <code>update_avatar()</code> function can read the form data. Maybe the function needs to accept an object? Like the form or even the event...</p>\n\n<p>Second, I think you need to specify in your data an \"action\". This is the name of the ajax function that processes the data being sent. In other words, the target of the ajax call. In your case, it would be: </p>\n\n<p><code>action: 'update_avatar_function'</code></p>\n\n<p>See <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">the Codex</a> for more information.</p>\n\n<p>(You could hard-code sample data to make sure the ajax is working properly, then work on sending the form data.)</p>\n" }, { "answer_id": 233291, "author": "czerspalace", "author_id": 47406, "author_profile": "https://wordpress.stackexchange.com/users/47406", "pm_score": 2, "selected": true, "text": "<p>You can try to use <code>new FormData()</code> instead of <code>new FormData($('form#change-avatar')[0])</code>. Also, after <code>processData:false</code> you should add <code>contentType: false</code> since jQuery will set it <a href=\"https://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax/5976031#5976031\">incorrectly otherwise</a>, and for url, instead of <code>ajaxurl</code> you should use<code>ajaxobject.ajaxurl</code>, since with <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\">wp_localize_script</a>, the second parameter is the javascript object name</p>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233283", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93927/" ]
I'm using a Using modal window with + form to change the profile avatar. Like the following (functions.php): ``` add_action('change_avatar', 'edit_avatar_function'); function edit_avatar_function($uid, $pid) { $av = get_user_meta($uid, 'avatar_' . 'project', true); $avatar = wp_get_attachment_image_src( $av, 'thumb300' ); ?> <div id="avatar-modal" class="modal fade" role="dialog"> <div class="modal-dialog browse-panel"> <div class="box_title"> <?php _e('Edit your Avatar', 'KleeiaDev') ?> </div> <div class="box_content top-15 text-center" id="my-media"> <form id="change-avatar" action="#" method="post" enctype="multipart/form-data"> <p class="top-20"> <input id="input-avatar" data-buttonText="<?php _e('Upload an image (300x300px)','KleeiaDev'); ?>" type="file" name="avatar" style="display:inline-block!important" class="filestyle avatar" data-icon="false" data-input="false"/> <input id="pid" type="hidden" name="pid" value="<?php echo $pid ?>"/> <input id="uid" type="hidden" name="uid" value="<?php echo $uid ?>"/> </p> </form> <p class="top-20"> <button id="upload-avatar" type="button" class="submit_light full_width"><?php _e('Update Cover image','KleeiaDev') ?></button> </p> </div> </div> </div> ``` I call this modal with `<?php do_action('change_avatar', $myuid ); ?>` in my page and I send the infos through AJAX, enqueuing the action like this (functions.php) ``` add_action('wp_ajax_update_avatar_function', 'update_avatar_function', 10, 2 ); function update_avatar_function(){ $pid = $_POST['pid']; $uid = $_POST['uid']; $avatar = $_POST['avatar']; //perform update user meta and other stuff //send me back uid and pid to check if they're correct $response = array('uid'=>$uid,'pid'=>$pid); echo json_encode($response); die(); } add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 10, 2 ); function add_frontend_ajax_javascript_file() { wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } ``` At the latest I use this jQuery/AJAX: ``` var updatebuttonav = $('#upload-avatar'); updatebuttonav.on('click', function() { event.preventDefault(); update_avatar(); }); function update_avatar() { var form_data = new FormData($('form#change-avatar')[0]); form_data.append('pid', $('#pid').val()), //no sending value form_data.append('uid', $('#uid').val()), //no sending value form_data.append('avatar', $('#input-avatar')[0].files[0]), //no sending file form_data.append('action', 'update_avatar_function'), console.log(form_data); //here is printing No Properties jQuery.ajax({ method: 'post', url : ajaxurl, dataType: 'json', data: form_data, processData: false, beforeSend:function(data){ //other functions }, success:function(data) { alert(data.uid + data.pid); }, error: function(data){ console.log(data); } }); //alert("a"); } ``` Well, with this I see in my `console.log` that **No Object Properties** and values are sent. Furthermore the **json response is Nan**. I use this method with other section of my website and I can't see why here It's not working. Is that possible that through `do_action` the form is not seen? Am I missing something? Any suggestion would be more than appreciated! Note: I'm not using the `wp_ajax_nopriv` because users I need it when I'm logged of course.
You can try to use `new FormData()` instead of `new FormData($('form#change-avatar')[0])`. Also, after `processData:false` you should add `contentType: false` since jQuery will set it [incorrectly otherwise](https://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax/5976031#5976031), and for url, instead of `ajaxurl` you should use`ajaxobject.ajaxurl`, since with [wp\_localize\_script](https://developer.wordpress.org/reference/functions/wp_localize_script/), the second parameter is the javascript object name
233,284
<p>crafting a theme from finished html/css markup and wonder how to wrap <code>a</code> tags in my custom class? With <code>ul</code> wrapper this is works:</p> <pre><code> wp_nav_menu( array('menu' =&gt; 'menu-header', 'menu_class' =&gt; 'list',) ); </code></pre> <p>but how to deal with menu items, and with currently selected menu item? I need <code>ul</code> to be with <code>.class</code> selector and <code>li</code> with <code>.item</code> selector as well</p>
[ { "answer_id": 233285, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 0, "selected": false, "text": "<p>First, I would make sure the <code>update_avatar()</code> function can read the form data. Maybe the function needs to accept an object? Like the form or even the event...</p>\n\n<p>Second, I think you need to specify in your data an \"action\". This is the name of the ajax function that processes the data being sent. In other words, the target of the ajax call. In your case, it would be: </p>\n\n<p><code>action: 'update_avatar_function'</code></p>\n\n<p>See <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">the Codex</a> for more information.</p>\n\n<p>(You could hard-code sample data to make sure the ajax is working properly, then work on sending the form data.)</p>\n" }, { "answer_id": 233291, "author": "czerspalace", "author_id": 47406, "author_profile": "https://wordpress.stackexchange.com/users/47406", "pm_score": 2, "selected": true, "text": "<p>You can try to use <code>new FormData()</code> instead of <code>new FormData($('form#change-avatar')[0])</code>. Also, after <code>processData:false</code> you should add <code>contentType: false</code> since jQuery will set it <a href=\"https://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax/5976031#5976031\">incorrectly otherwise</a>, and for url, instead of <code>ajaxurl</code> you should use<code>ajaxobject.ajaxurl</code>, since with <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\">wp_localize_script</a>, the second parameter is the javascript object name</p>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233284", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98996/" ]
crafting a theme from finished html/css markup and wonder how to wrap `a` tags in my custom class? With `ul` wrapper this is works: ``` wp_nav_menu( array('menu' => 'menu-header', 'menu_class' => 'list',) ); ``` but how to deal with menu items, and with currently selected menu item? I need `ul` to be with `.class` selector and `li` with `.item` selector as well
You can try to use `new FormData()` instead of `new FormData($('form#change-avatar')[0])`. Also, after `processData:false` you should add `contentType: false` since jQuery will set it [incorrectly otherwise](https://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax/5976031#5976031), and for url, instead of `ajaxurl` you should use`ajaxobject.ajaxurl`, since with [wp\_localize\_script](https://developer.wordpress.org/reference/functions/wp_localize_script/), the second parameter is the javascript object name
233,292
<p>I am trying to filter the loop to find posts that have a <code>meta_key</code> with a specific <code>meta_value</code>. I've looked at the Codex, and I've tried the following with no luck:</p> <pre><code>// No results $args = array( 'post_type' =&gt; 'cqpp_interventions', 'posts_per_page' =&gt; '-1', 'meta_query' =&gt; array( 'relation' =&gt; 'OR', array( 'meta_key' =&gt; 'priority', /* Tried this too 'meta_value' =&gt; '80', 'compare' =&gt; '=' */ 'meta_value' =&gt; array('80'), 'compare' =&gt; 'IN' ) ) ); // No results $args = array( 'post_type' =&gt; 'cqpp_interventions', 'posts_per_page' =&gt; '-1', 'meta_key' =&gt; 'priority', 'meta_value' =&gt; 80 ); // This list me all cqpp_interventions and I can confirm that I have some with meta_value set to 80 $args = array( 'post_type' =&gt; 'cqpp_interventions', 'posts_per_page' =&gt; '-1', 'meta_key' =&gt; 'priority' ); $cqpp_posts = get_posts( $args ); </code></pre> <p>Here is how I verify inside the loop:</p> <pre><code>$priority = get_post_meta( get_the_ID(), 'priority'); echo '&lt;pre&gt;'; var_dump($priority); echo '&lt;/pre&gt;'; </code></pre> <p>which results in: </p> <pre><code>search.php:16: array (size=1) 0 =&gt; array (size=1) 0 =&gt; string '80' (length=2) search.php:16: array (size=1) 0 =&gt; array (size=2) 0 =&gt; string '80' (length=2) 1 =&gt; string '91' (length=2) </code></pre> <p>What can I do to fix this?</p>
[ { "answer_id": 233294, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 0, "selected": false, "text": "<p>From the reference of your first $args</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'cqpp_interventions',\n 'posts_per_page' =&gt; '-1',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'meta_key' =&gt; 'priority',\n /* Tried this too\n 'meta_value' =&gt; '80',\n 'compare' =&gt; '='\n */\n 'meta_value' =&gt; array('80'),\n 'compare' =&gt; 'IN' )\n )\n);\n</code></pre>\n\n<p>You have added <code>'relation' =&gt; 'OR'</code>, which is not needed. The <code>relation</code> needs to be added if you have multiple meta-value to be queried. Also compare is not needed if you want a specific value, as by default is uses <code>=</code>.</p>\n\n<p>The updated $args will be</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'cqpp_interventions',\n 'posts_per_page' =&gt; '-1',\n 'meta_query' =&gt; array(\n array(\n 'meta_key' =&gt; 'priority',\n 'meta_value' =&gt; '80', // since 80 is string\n )\n )\n);\n\n// try either of below.\n$myPost = new WP_Query( $args ); // fetch post and managed in objects\n$myPost = get_posts( $args ); // fetch post and store in array\n</code></pre>\n\n<p>Hope this will help you out.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 273788, "author": "Chin Leung", "author_id": 104711, "author_profile": "https://wordpress.stackexchange.com/users/104711", "pm_score": 2, "selected": false, "text": "<p>You could try this:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'cqpp_interventions',\n 'posts_per_page' =&gt; '-1',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'priority',\n 'value' =&gt; '80'\n )\n )\n);\n</code></pre>\n\n<p>The real issue with your query is because you are passing <code>meta_key</code> and <code>meta_value</code>. However, the arrays in your <code>meta_query</code> argument should have the keys <code>key</code> and <code>value</code> instead.</p>\n\n<p>This would also work:</p>\n\n<pre><code>'key' =&gt; 'priority',\n'value' =&gt; array('80')\n</code></pre>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233292", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10501/" ]
I am trying to filter the loop to find posts that have a `meta_key` with a specific `meta_value`. I've looked at the Codex, and I've tried the following with no luck: ``` // No results $args = array( 'post_type' => 'cqpp_interventions', 'posts_per_page' => '-1', 'meta_query' => array( 'relation' => 'OR', array( 'meta_key' => 'priority', /* Tried this too 'meta_value' => '80', 'compare' => '=' */ 'meta_value' => array('80'), 'compare' => 'IN' ) ) ); // No results $args = array( 'post_type' => 'cqpp_interventions', 'posts_per_page' => '-1', 'meta_key' => 'priority', 'meta_value' => 80 ); // This list me all cqpp_interventions and I can confirm that I have some with meta_value set to 80 $args = array( 'post_type' => 'cqpp_interventions', 'posts_per_page' => '-1', 'meta_key' => 'priority' ); $cqpp_posts = get_posts( $args ); ``` Here is how I verify inside the loop: ``` $priority = get_post_meta( get_the_ID(), 'priority'); echo '<pre>'; var_dump($priority); echo '</pre>'; ``` which results in: ``` search.php:16: array (size=1) 0 => array (size=1) 0 => string '80' (length=2) search.php:16: array (size=1) 0 => array (size=2) 0 => string '80' (length=2) 1 => string '91' (length=2) ``` What can I do to fix this?
You could try this: ``` $args = array( 'post_type' => 'cqpp_interventions', 'posts_per_page' => '-1', 'meta_query' => array( array( 'key' => 'priority', 'value' => '80' ) ) ); ``` The real issue with your query is because you are passing `meta_key` and `meta_value`. However, the arrays in your `meta_query` argument should have the keys `key` and `value` instead. This would also work: ``` 'key' => 'priority', 'value' => array('80') ```
233,293
<p>So wp_get_themes() returns an array of objects :</p> <pre><code>Array ( [WpAngular] =&gt; WP_Theme Object ( [update] =&gt; [theme_root:WP_Theme:private] =&gt; /home/love/Web/web/app/themes [headers:WP_Theme:private] =&gt; Array ( [Name] =&gt; WpAngular [ThemeURI] =&gt; http://www.someurl.com [Description] =&gt; blak blak. [Author] =&gt; Joy division [AuthorURI] =&gt; http://www.someurl.com [Version] =&gt; 6.0 [Template] =&gt; [Status] =&gt; [Tags] =&gt; WordPress [TextDomain] =&gt; [DomainPath] =&gt; ) [headers_sanitized:WP_Theme:private] =&gt; Array ( [Name] =&gt; WpAngular ) [name_translated:WP_Theme:private] =&gt; [errors:WP_Theme:private] =&gt; [stylesheet:WP_Theme:private] =&gt; Angular-Wordpress [template:WP_Theme:private] =&gt; Angular-Wordpress [parent:WP_Theme:private] =&gt; [theme_root_uri:WP_Theme:private] =&gt; [textdomain_loaded:WP_Theme:private] =&gt; [cache_hash:WP_Theme:private] =&gt; 03dc86f794762ab23bab120e9b121326 ) [Some Theme] =&gt; WP_Theme Object ( [update] =&gt; [theme_root:WP_Theme:private] =&gt; /home/love6/Web/web/app/themes [headers:WP_Theme:private] =&gt; Array ( [Name] =&gt; Some Theme [ThemeURI] =&gt; http://www.someurl.com [Description] =&gt; Blak Blak. [Author] =&gt; Some dude [AuthorURI] =&gt; http://www.someurl.com [Version] =&gt; 2.0 [Template] =&gt; [Status] =&gt; [Tags] =&gt; [TextDomain] =&gt; [DomainPath] =&gt; ) [headers_sanitized:WP_Theme:private] =&gt; Array ( [Name] =&gt; Some Theme ) [name_translated:WP_Theme:private] =&gt; [errors:WP_Theme:private] =&gt; [stylesheet:WP_Theme:private] =&gt; some-theme [template:WP_Theme:private] =&gt; some-theme [parent:WP_Theme:private] =&gt; [theme_root_uri:WP_Theme:private] =&gt; [textdomain_loaded:WP_Theme:private] =&gt; [cache_hash:WP_Theme:private] =&gt; a1a2613543a81b28b06ac802adb785fc ) ) </code></pre> <p>I'm trying to build function that returns an array of the theme names from the objects. </p> <pre><code>function my_get_allowed_themes() { $theme_args = array( 'errors' =&gt; false , 'allowed' =&gt; 'site' ); $allowed_themes = wp_get_themes($theme_args); $allowed_themes = null; $demos = array(); $allowed_theme_names = array(); // loop over themes and grab the theme name foreach ( $allowed_themes as $allowed_theme ) { $allowed_theme_names[] = $allowed_theme['Name']; } return $allowed_theme_names; } </code></pre> <p>However, this is just returning an empty array. What am I missing?</p>
[ { "answer_id": 233295, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": -1, "selected": false, "text": "<p>Here theme names that are displayed from <code>wp_get_themes()</code> stores private information, as you can see </p>\n\n<p><code>[headers:WP_Theme:private]</code></p>\n\n<p>So you can't access the private variable directly.\nFor accessing the private variable you need to inherit the parent class.</p>\n\n<h1>Update</h1>\n\n<pre><code>$get_theme = wp_get_themes();\n$all_theme = array_keys( $get_theme ) );\nprint_r( $all_theme ); //will return all theme \n</code></pre>\n" }, { "answer_id": 255772, "author": "Thamaraiselvam", "author_id": 67717, "author_profile": "https://wordpress.stackexchange.com/users/67717", "pm_score": 0, "selected": false, "text": "<p>you can access <code>WP_Theme</code> object like below</p>\n\n<pre><code> $theme = wp_get_theme();\n $name = $theme-&gt;{'Name'};\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$theme-&gt;get( 'Name' );\n</code></pre>\n" }, { "answer_id": 276905, "author": "Austin Ginder", "author_id": 5256, "author_profile": "https://wordpress.stackexchange.com/users/5256", "pm_score": 3, "selected": true, "text": "<p>Correct the <code>wp_get_themes()</code> function has most of the information inaccessible to the public which requires you to pull the info out using the <code>$theme-&gt;get( 'Name' );</code> format. You can build a simple array like so.</p>\n\n<pre><code>// Build new empty Array to store the themes\n$themes = array();\n\n// Loads theme data\n$all_themes = wp_get_themes();\n\n// Loads theme names into themes array\nforeach ($all_themes as $theme) {\n $themes[] = $theme-&gt;get('Name');\n}\n\n// Prints the theme names\nprint_r( $themes );\n</code></pre>\n\n<p>Which will output</p>\n\n<pre><code>Array (\n [0] =&gt; Anchor Blank\n [1] =&gt; Swell - Anchor Hosting\n [2] =&gt; Swell\n)\n</code></pre>\n\n<p>Taking this one step future you can build an array with all of the theme data like so.</p>\n\n<pre><code>// Build new empty Array to store the themes\n$themes = array();\n\n// Loads theme data\n$all_themes = wp_get_themes();\n\n// Build theme data manually\nforeach ($all_themes as $theme) {\n $themes{ $theme-&gt;stylesheet } = array(\n 'Name' =&gt; $theme-&gt;get('Name'),\n 'Description' =&gt; $theme-&gt;get('Description'),\n 'Author' =&gt; $theme-&gt;get('Author'),\n 'AuthorURI' =&gt; $theme-&gt;get('AuthorURI'),\n 'Version' =&gt; $theme-&gt;get('Version'),\n 'Template' =&gt; $theme-&gt;get('Template'),\n 'Status' =&gt; $theme-&gt;get('Status'),\n 'Tags' =&gt; $theme-&gt;get('Tags'),\n 'TextDomain' =&gt; $theme-&gt;get('TextDomain'),\n 'DomainPath' =&gt; $theme-&gt;get('DomainPath')\n );\n}\n\n// Prints the themes\nprint_r( $themes );\n</code></pre>\n\n<p>This will output an array which looks like the following</p>\n\n<pre><code>Array (\n[anchor-blank] =&gt; Array\n (\n [Name] =&gt; Anchor Blank\n [Description] =&gt; Anchor Hosting blank theme\n [Author] =&gt; Anchor Hosting\n [AuthorURI] =&gt; https://anchor.host\n [Version] =&gt; 1.1\n [Template] =&gt;\n [Status] =&gt; publish\n [Tags] =&gt; Array\n (\n )\n\n [TextDomain] =&gt; anchor-blank\n [DomainPath] =&gt; /languages/\n )\n\n[swell-anchorhost] =&gt; Array\n (\n [Name] =&gt; Swell - Anchor Hosting\n [Description] =&gt; Child theme for Anchor Hosting\n [Author] =&gt; Anchor Hosting\n [AuthorURI] =&gt; https://anchor.host\n [Version] =&gt; 1.1.0\n [Template] =&gt; swell\n [Status] =&gt; publish\n [Tags] =&gt; Array\n (\n )\n\n [TextDomain] =&gt; swell\n [DomainPath] =&gt; /languages/\n )\n\n[swell] =&gt; Array\n (\n [Name] =&gt; Swell\n [Description] =&gt; Swell is a one-column, typography-focused, video Wordpress theme.\n [Author] =&gt; ThemeTrust.com\n [AuthorURI] =&gt; http://themetrust.com\n [Version] =&gt; 1.2.6\n [Template] =&gt;\n [Status] =&gt; publish\n [Tags] =&gt; Array\n (\n )\n\n [TextDomain] =&gt; swell\n [DomainPath] =&gt; /languages/\n )\n)\n</code></pre>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86684/" ]
So wp\_get\_themes() returns an array of objects : ``` Array ( [WpAngular] => WP_Theme Object ( [update] => [theme_root:WP_Theme:private] => /home/love/Web/web/app/themes [headers:WP_Theme:private] => Array ( [Name] => WpAngular [ThemeURI] => http://www.someurl.com [Description] => blak blak. [Author] => Joy division [AuthorURI] => http://www.someurl.com [Version] => 6.0 [Template] => [Status] => [Tags] => WordPress [TextDomain] => [DomainPath] => ) [headers_sanitized:WP_Theme:private] => Array ( [Name] => WpAngular ) [name_translated:WP_Theme:private] => [errors:WP_Theme:private] => [stylesheet:WP_Theme:private] => Angular-Wordpress [template:WP_Theme:private] => Angular-Wordpress [parent:WP_Theme:private] => [theme_root_uri:WP_Theme:private] => [textdomain_loaded:WP_Theme:private] => [cache_hash:WP_Theme:private] => 03dc86f794762ab23bab120e9b121326 ) [Some Theme] => WP_Theme Object ( [update] => [theme_root:WP_Theme:private] => /home/love6/Web/web/app/themes [headers:WP_Theme:private] => Array ( [Name] => Some Theme [ThemeURI] => http://www.someurl.com [Description] => Blak Blak. [Author] => Some dude [AuthorURI] => http://www.someurl.com [Version] => 2.0 [Template] => [Status] => [Tags] => [TextDomain] => [DomainPath] => ) [headers_sanitized:WP_Theme:private] => Array ( [Name] => Some Theme ) [name_translated:WP_Theme:private] => [errors:WP_Theme:private] => [stylesheet:WP_Theme:private] => some-theme [template:WP_Theme:private] => some-theme [parent:WP_Theme:private] => [theme_root_uri:WP_Theme:private] => [textdomain_loaded:WP_Theme:private] => [cache_hash:WP_Theme:private] => a1a2613543a81b28b06ac802adb785fc ) ) ``` I'm trying to build function that returns an array of the theme names from the objects. ``` function my_get_allowed_themes() { $theme_args = array( 'errors' => false , 'allowed' => 'site' ); $allowed_themes = wp_get_themes($theme_args); $allowed_themes = null; $demos = array(); $allowed_theme_names = array(); // loop over themes and grab the theme name foreach ( $allowed_themes as $allowed_theme ) { $allowed_theme_names[] = $allowed_theme['Name']; } return $allowed_theme_names; } ``` However, this is just returning an empty array. What am I missing?
Correct the `wp_get_themes()` function has most of the information inaccessible to the public which requires you to pull the info out using the `$theme->get( 'Name' );` format. You can build a simple array like so. ``` // Build new empty Array to store the themes $themes = array(); // Loads theme data $all_themes = wp_get_themes(); // Loads theme names into themes array foreach ($all_themes as $theme) { $themes[] = $theme->get('Name'); } // Prints the theme names print_r( $themes ); ``` Which will output ``` Array ( [0] => Anchor Blank [1] => Swell - Anchor Hosting [2] => Swell ) ``` Taking this one step future you can build an array with all of the theme data like so. ``` // Build new empty Array to store the themes $themes = array(); // Loads theme data $all_themes = wp_get_themes(); // Build theme data manually foreach ($all_themes as $theme) { $themes{ $theme->stylesheet } = array( 'Name' => $theme->get('Name'), 'Description' => $theme->get('Description'), 'Author' => $theme->get('Author'), 'AuthorURI' => $theme->get('AuthorURI'), 'Version' => $theme->get('Version'), 'Template' => $theme->get('Template'), 'Status' => $theme->get('Status'), 'Tags' => $theme->get('Tags'), 'TextDomain' => $theme->get('TextDomain'), 'DomainPath' => $theme->get('DomainPath') ); } // Prints the themes print_r( $themes ); ``` This will output an array which looks like the following ``` Array ( [anchor-blank] => Array ( [Name] => Anchor Blank [Description] => Anchor Hosting blank theme [Author] => Anchor Hosting [AuthorURI] => https://anchor.host [Version] => 1.1 [Template] => [Status] => publish [Tags] => Array ( ) [TextDomain] => anchor-blank [DomainPath] => /languages/ ) [swell-anchorhost] => Array ( [Name] => Swell - Anchor Hosting [Description] => Child theme for Anchor Hosting [Author] => Anchor Hosting [AuthorURI] => https://anchor.host [Version] => 1.1.0 [Template] => swell [Status] => publish [Tags] => Array ( ) [TextDomain] => swell [DomainPath] => /languages/ ) [swell] => Array ( [Name] => Swell [Description] => Swell is a one-column, typography-focused, video Wordpress theme. [Author] => ThemeTrust.com [AuthorURI] => http://themetrust.com [Version] => 1.2.6 [Template] => [Status] => publish [Tags] => Array ( ) [TextDomain] => swell [DomainPath] => /languages/ ) ) ```
233,298
<p>I've inherited a website which has a menu structure that is not working. he developer built a site at huge expense but has then left them with a partially working site. It is a WooCommerce site with a custom template. I cannot understand how this is supposed to work - any help much appreciated. :-)</p> <p>The menu in question is:</p> <pre><code> &lt;form id="filter_dropdown_form" method="GET" action="http://www.punjaban.co.uk/wp-content/themes/punjaban/taxonomy-redirect.php"&gt; &lt;input type="hidden" name="post_type" value="product" /&gt; &lt;select name="term_filter" id="" class="turnintodropdown"&gt; &lt;option value=""&gt;Product Categories&lt;/option&gt; &lt;option value="12"&gt;Accompaniments&lt;/option&gt; &lt;option value="20"&gt;Bread&lt;/option&gt; &lt;option value="9"&gt;Curry Bases&lt;/option&gt; &lt;option value="10"&gt;Pickles and Chutneys&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" value="Filter" class="fallback" /&gt; &lt;input type="hidden" name="taxonomy_name" value="product_cat" /&gt; &lt;/form&gt; </code></pre> <p>None of the categories work, an error is displayed suggesting permissions to the taxonomy-redirect.php file aren't correct (it is 644).</p> <p>Taxonomy-redirect.php:</p> <pre><code>&lt;?php require $_SERVER[ 'DOCUMENT_ROOT' ] . '/wp-blog-header.php'; $term_id = $_GET[ 'term_filter' ]; $url = ''; if ( $term_id !== '' ) { $taxonomy_name = $_GET[ 'taxonomy_name' ]; $url = get_term_link( intval( $term_id ), $taxonomy_name ); } else { $post_type = $_GET[ 'post_type' ]; $url = get_post_type_archive_link( $post_type ); } //$url .= '#filter_anchor'; wp_redirect( $url, 301 ); </code></pre> <p>There are 2 files called taxonomy-recipes-category.php and taxonomy-stockists-category.php . The code is below:</p> <pre><code>application/x-httpd-php taxonomy-recipes-category.php ( PHP script text ) &lt;?php /** * The template for displaying archive recipes. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package Punjaban */ get_header(); $post_type = 'recipes' ?&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;?php get_template_part( 'template-parts/slider' ); ?&gt; &lt;div id="content-section" class="&lt;?php echo $post_type; ?&gt;-loop-wrap text-center"&gt; &lt;div class="row"&gt; &lt;h2&gt;&lt;?php the_field($post_type . '_listing_title', 'option'); ?&gt;&lt;/h2&gt; &lt;?php if ( have_posts( ) ) { $recipes_categories = get_terms( 'recipes-category', array( 'orderby' =&gt; 'name', 'order' =&gt; 'ASC', 'hide_empty' =&gt; true, ) ); $term_slug = get_query_var( 'recipes-category' ); if (count( $recipes_categories &gt; 0 ) ){ ?&gt; &lt;form id="filter_dropdown_form" method="GET" action="&lt;?php echo get_stylesheet_directory_uri( ); ?&gt;/taxonomy-redirect.php"&gt; &lt;input type="hidden" name="post_type" value="&lt;?php echo $post_type; ?&gt;" /&gt; &lt;select name="term_filter" id="" class="turnintodropdown"&gt; &lt;option value=""&gt;View Recipes With&lt;/option&gt; &lt;?php foreach( $recipes_categories as $recipes_category ) { echo ' &lt;option value="' . $recipes_category-&gt;term_id . '"' . selected( $term_slug === $recipes_category-&gt;slug, true, false ) . '&gt;' . $recipes_category-&gt;name . '&lt;/option&gt;'; } ?&gt; &lt;/select&gt; &lt;input type="submit" value="Filter" class="fallback" /&gt; &lt;input type="hidden" name="taxonomy_name" value="recipes-category" /&gt; &lt;/form&gt; &lt;?php } ?&gt; &lt;section id="isotope-container" class="isotope-wrap text-center"&gt; &lt;?php $current_page = get_query_var( 'paged' ); if ( !$current_page ) { $current_page = 1; } $featured = get_field( 'featured_recipe_of_the_month', 'options' ); if ( !empty( $featured ) &amp;&amp; $current_page == 1 ) { get_template_part( 'listing-feat-' . $post_type, '' ); } while ( have_posts() ) { the_post(); get_template_part( 'listing', $post_type ); } ?&gt; &lt;span class="clearboth"&gt;&lt;/span&gt; &lt;/section&gt; &lt;?php } else { //get_template_part('content', 'none'); echo '&lt;p&gt;Sorry, no products here&lt;/p&gt;'; } ?&gt; &lt;/div&gt; &lt;?php if ( have_posts( ) ) { global $wp_query; echo TC_Library::get_paging( $wp_query-&gt;found_posts, $wp_query-&gt;query_vars[ 'posts_per_page' ], array( ) ); } ?&gt; &lt;/div&gt; &lt;?php get_template_part( 'template-parts/cta' ); ?&gt; &lt;/main&gt; &lt;/div&gt; &lt;?php get_footer(); </code></pre> <p>Am I correct in thinking that you would need a file per pag? For example they have the same category dropdown on the Blog and Woocommerce shop page but I cannot see any code relating to that.</p> <p>The website is <a href="http://www.punjaban.co.uk" rel="nofollow">www.punjaban.co.uk</a> Thank you.</p>
[ { "answer_id": 233305, "author": "Gary", "author_id": 99006, "author_profile": "https://wordpress.stackexchange.com/users/99006", "pm_score": 0, "selected": false, "text": "<p>From the explanation you have posted it sounds like your webserver does not have permission to execute the PHP script. If the Webserver is Linux, you can use CHMOD and CHOWN commands to modify the persmissons and change the owner respectively, but if you are not familiar with linux, you are best asking your hosting support to help with this. </p>\n\n<p>You would need to ensure the webserver account on the server is the 'owner' of the directory the file resides in, and that it has permission to execute the script. <code>CHMOD 744</code> for example would give the web server (providing the webserver is the owner of the file and directory) permission to execute the file and everyone permission to read. Definately sounds like a permissions issue on the webserver. You can also check the webserver error log which might give you some more information if you have access to the server. </p>\n" }, { "answer_id": 233329, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>The server is setup correctly, no one should be able to execute php which is not at the root directory of wordpress (if he cares about the site's security). You can look into the htaccess or other server settings to figure out how it was done and remove it, but -10 for that option.</p>\n\n<p>The form and its server side handling do not make any sense at all. Either replace the form with links to the actual term pages, or use some JS to direct to them</p>\n" }, { "answer_id": 233333, "author": "Helen", "author_id": 64011, "author_profile": "https://wordpress.stackexchange.com/users/64011", "pm_score": 1, "selected": true, "text": "<p>So, when I looked at the .htaccess file it had the following:</p>\n\n<pre><code>&lt;FilesMatch \"\\.(?i:php)$\"&gt;\n &lt;IfModule !mod_authz_core.c&gt;\n Order allow,deny\n Deny from all\n &lt;/IfModule&gt;\n &lt;IfModule mod_authz_core.c&gt;\n Require all denied\n &lt;/IfModule&gt;\n&lt;/FilesMatch&gt;\n</code></pre>\n\n<p>I removed that and the menu works correctly. This may open up risks to other files so I will post on the Linux page to clarify the correction. Thanks Gary for pointing me in the right direction.</p>\n" } ]
2016/07/26
[ "https://wordpress.stackexchange.com/questions/233298", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64011/" ]
I've inherited a website which has a menu structure that is not working. he developer built a site at huge expense but has then left them with a partially working site. It is a WooCommerce site with a custom template. I cannot understand how this is supposed to work - any help much appreciated. :-) The menu in question is: ``` <form id="filter_dropdown_form" method="GET" action="http://www.punjaban.co.uk/wp-content/themes/punjaban/taxonomy-redirect.php"> <input type="hidden" name="post_type" value="product" /> <select name="term_filter" id="" class="turnintodropdown"> <option value="">Product Categories</option> <option value="12">Accompaniments</option> <option value="20">Bread</option> <option value="9">Curry Bases</option> <option value="10">Pickles and Chutneys</option> </select> <input type="submit" value="Filter" class="fallback" /> <input type="hidden" name="taxonomy_name" value="product_cat" /> </form> ``` None of the categories work, an error is displayed suggesting permissions to the taxonomy-redirect.php file aren't correct (it is 644). Taxonomy-redirect.php: ``` <?php require $_SERVER[ 'DOCUMENT_ROOT' ] . '/wp-blog-header.php'; $term_id = $_GET[ 'term_filter' ]; $url = ''; if ( $term_id !== '' ) { $taxonomy_name = $_GET[ 'taxonomy_name' ]; $url = get_term_link( intval( $term_id ), $taxonomy_name ); } else { $post_type = $_GET[ 'post_type' ]; $url = get_post_type_archive_link( $post_type ); } //$url .= '#filter_anchor'; wp_redirect( $url, 301 ); ``` There are 2 files called taxonomy-recipes-category.php and taxonomy-stockists-category.php . The code is below: ``` application/x-httpd-php taxonomy-recipes-category.php ( PHP script text ) <?php /** * The template for displaying archive recipes. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package Punjaban */ get_header(); $post_type = 'recipes' ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php get_template_part( 'template-parts/slider' ); ?> <div id="content-section" class="<?php echo $post_type; ?>-loop-wrap text-center"> <div class="row"> <h2><?php the_field($post_type . '_listing_title', 'option'); ?></h2> <?php if ( have_posts( ) ) { $recipes_categories = get_terms( 'recipes-category', array( 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true, ) ); $term_slug = get_query_var( 'recipes-category' ); if (count( $recipes_categories > 0 ) ){ ?> <form id="filter_dropdown_form" method="GET" action="<?php echo get_stylesheet_directory_uri( ); ?>/taxonomy-redirect.php"> <input type="hidden" name="post_type" value="<?php echo $post_type; ?>" /> <select name="term_filter" id="" class="turnintodropdown"> <option value="">View Recipes With</option> <?php foreach( $recipes_categories as $recipes_category ) { echo ' <option value="' . $recipes_category->term_id . '"' . selected( $term_slug === $recipes_category->slug, true, false ) . '>' . $recipes_category->name . '</option>'; } ?> </select> <input type="submit" value="Filter" class="fallback" /> <input type="hidden" name="taxonomy_name" value="recipes-category" /> </form> <?php } ?> <section id="isotope-container" class="isotope-wrap text-center"> <?php $current_page = get_query_var( 'paged' ); if ( !$current_page ) { $current_page = 1; } $featured = get_field( 'featured_recipe_of_the_month', 'options' ); if ( !empty( $featured ) && $current_page == 1 ) { get_template_part( 'listing-feat-' . $post_type, '' ); } while ( have_posts() ) { the_post(); get_template_part( 'listing', $post_type ); } ?> <span class="clearboth"></span> </section> <?php } else { //get_template_part('content', 'none'); echo '<p>Sorry, no products here</p>'; } ?> </div> <?php if ( have_posts( ) ) { global $wp_query; echo TC_Library::get_paging( $wp_query->found_posts, $wp_query->query_vars[ 'posts_per_page' ], array( ) ); } ?> </div> <?php get_template_part( 'template-parts/cta' ); ?> </main> </div> <?php get_footer(); ``` Am I correct in thinking that you would need a file per pag? For example they have the same category dropdown on the Blog and Woocommerce shop page but I cannot see any code relating to that. The website is [www.punjaban.co.uk](http://www.punjaban.co.uk) Thank you.
So, when I looked at the .htaccess file it had the following: ``` <FilesMatch "\.(?i:php)$"> <IfModule !mod_authz_core.c> Order allow,deny Deny from all </IfModule> <IfModule mod_authz_core.c> Require all denied </IfModule> </FilesMatch> ``` I removed that and the menu works correctly. This may open up risks to other files so I will post on the Linux page to clarify the correction. Thanks Gary for pointing me in the right direction.
233,327
<p>I have this code in my custom template file:</p> <pre><code>&lt;?php /* Template Name: custom-template-view */ ob_start(); get_header(); function assignPageTitle(){ return "my page title"; } add_filter('wp_title', 'assignPageTitle');// not working add_filter('the_title', 'assignPageTitle'); // not working ?&gt; &lt;div&gt;MY CONTENT&lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I want to set custom title tag but it is not working. In this template I am showing records from custom table.</p>
[ { "answer_id": 233328, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p>Why don't you just echo you custom post title? For example:</p>\n\n<pre><code>if (some_conditional) {\n echo 'My custom title';\n} else {\n the_title();\n}\n</code></pre>\n" }, { "answer_id": 233330, "author": "stoi2m1", "author_id": 10907, "author_profile": "https://wordpress.stackexchange.com/users/10907", "pm_score": 3, "selected": true, "text": "<p>Template files are not the right place to add in functions like that. The template file isnt loaded until late in the hook/filter process. Your function should be in functions.php. This way it can be added in before your tempalte files load, and functions that are in use in them can be altered.</p>\n\n<p>Often times <code>wp_title()</code> is used in the header.php so it possible you are using that, but form the code you show you are filtering functions you are not using. Except maybe in header.php, but its loaded and executed before this custom template file. You also do not show the use of <code>the_title()</code> so I can not tell how/when/where this would actually filter anything if the function was placed in the right location.</p>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233327", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85769/" ]
I have this code in my custom template file: ``` <?php /* Template Name: custom-template-view */ ob_start(); get_header(); function assignPageTitle(){ return "my page title"; } add_filter('wp_title', 'assignPageTitle');// not working add_filter('the_title', 'assignPageTitle'); // not working ?> <div>MY CONTENT</div> <?php get_footer(); ?> ``` I want to set custom title tag but it is not working. In this template I am showing records from custom table.
Template files are not the right place to add in functions like that. The template file isnt loaded until late in the hook/filter process. Your function should be in functions.php. This way it can be added in before your tempalte files load, and functions that are in use in them can be altered. Often times `wp_title()` is used in the header.php so it possible you are using that, but form the code you show you are filtering functions you are not using. Except maybe in header.php, but its loaded and executed before this custom template file. You also do not show the use of `the_title()` so I can not tell how/when/where this would actually filter anything if the function was placed in the right location.
233,338
<p>I am writing a plugin for the first time, and I have a problem.</p> <p>I am using AJAX in my plugin. My JavaScript file is in the folder <code>../wp-content/plugins/myplugin/js/</code> , and in it I am trying to call a PHP file, which is in the folder <code>../wp-content/plugins/myplugin/</code></p> <pre><code>jQuery.ajax({ url: "/wp-content/plugins/myplugin/myfile.php?myparam=" + myparam, context: document.body }); </code></pre> <p>My question is: How can I get this URL reference work independent of, where the user installed the plugin. Because when for example a user install this plugin in <code>http://localhost/subdir/</code>, the reference is not correct. Can I somehow create a relative link ?</p>
[ { "answer_id": 233340, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 3, "selected": false, "text": "<p>First of all, you shouldn't call your own PHP file. You should use <code>admin-ajax</code> endpoint. <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">Documentation</a></p>\n\n<p>On admin side, you could use ajaxurl to get URL for AJAX calls. On front side you have to declare by yourself variable with url. This is written in documentation:</p>\n\n<blockquote>\n <p><strong>Note</strong>: Unlike on the admin side, the ajaxurl javascript global does not get automatically defined for you, unless you have BuddyPress or another Ajax-reliant plugin installed. So instead of relying on a global javascript variable, declare a javascript namespace object with its own property, ajaxurl. You might also use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url( 'admin-ajax.php' ) </p>\n</blockquote>\n\n<p>This should resolve problem:</p>\n\n<pre><code>add_action( 'wp_head', 'front_ajaxurl' );\nfunction front_ajaxurl() {\n wp_register_script( 'admin_ajax_front', plugin_dir_url(__FILE__) . 'script.js' );\n $translation_array = array(\n 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' )\n );\n wp_localize_script( 'admin_ajax_front', 'front', $translation_array );\n wp_enqueue_script( 'admin_ajax_font', false, array(), false, true ); // last param set to true will enqueue script on footer\n}\n</code></pre>\n\n<p>And then in your JS file:</p>\n\n<pre><code>$.ajax({\n url: front.ajaxurl,\n ...\n})\n</code></pre>\n" }, { "answer_id": 248251, "author": "Lzh", "author_id": 108266, "author_profile": "https://wordpress.stackexchange.com/users/108266", "pm_score": 2, "selected": false, "text": "<p>I'm a beginner, but this worked for me</p>\n\n<p>Add the following in functions.php. Note that 'wp_ajax' is a prefix by convention and 'do_something' is my arbitrarily chosen action name:</p>\n\n<pre><code>add_action( 'wp_ajax_do_something', 'do_something' );\n\nfunction do_something() {\n //really, go ahead, do something\n die(\"return something\");\n}\n</code></pre>\n\n<p>To make the ajax call from the browser (client side), I was able to find my endpoint using <code>wp.ajax.settings.url</code>. <code>wp</code> global var is defined on the window object.</p>\n\n<pre><code>//do_something here must match above, you can add other params to this obj\nvar data = { action: 'do_something' };\njQuery.post(wp.ajax.settings.url, data, function(response) {\n console.log('Result: ' + response);\n});\n</code></pre>\n\n<p>I have WordPress 4.6.1 (latest on time of writing) and some plugins installed. I referred to this reference that incorrectly says that ajaxurl is defined, but it's not in my case: <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a> </p>\n" }, { "answer_id": 321533, "author": "gordie", "author_id": 70449, "author_profile": "https://wordpress.stackexchange.com/users/70449", "pm_score": 2, "selected": false, "text": "<p>I faced the same issue.</p>\n\n<p>I wanted to use my own endpoint instead the admin-ajax endpoint because I have rewrite rules populating all the variables I need to run the ajax actions.</p>\n\n<p>Thus, using (as said <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">in the codex</a>)</p>\n\n<pre><code>jQuery(document).ready(function($) {\n var data = {\n 'action': 'my_action',\n 'whatever': ajax_object.we_value // We pass php values differently!\n };\n jQuery.post(ajax_object.ajax_url, data, function(response) {\n alert('Got this from the server: ' + response);\n });\n});\n</code></pre>\n\n<p>and </p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action' );\nadd_action( 'wp_ajax_nopriv_my_action', 'my_action' );\n</code></pre>\n\n<p>just makes my code more complicated.</p>\n\n<p>I ended up doing this and it seems to work:</p>\n\n<pre><code> jQuery.ajax({\n type: \"post\",\n url: MYCUSTOMENDPOINT?ajax_action,\n dataType: 'json',\n ...\n</code></pre>\n\n<p>combined with:</p>\n\n<pre><code> add_action( 'init', 'rewrite_rules');\n add_filter( 'template_include','handle_ajax_action');\n\nfunction rewrite_rules(){\n add_rewrite_tag(\n '%ajax_action%',\n '([^&amp;]+)'\n );\n}\n\nfunction handle_ajax_action($template){\n\n $success = null;\n\n // since the \"ajax\" query variable does not require a value, we need to check for its existence\n if ( !$action = get_query_var( 'ajax_action' ) ) return $template; //ajax action does not exists\n\n $result = array(\n 'input' =&gt; $_REQUEST,\n 'message'=&gt; null,\n 'success'=&gt; null,\n );\n\n $success = ...\n\n if ( is_wp_error($success) ){\n $result['success'] = false;\n $result['message'] = $success-&gt;get_error_message();\n\n }else{\n $result['success'] = $success;\n }\n\n header('Content-type: application/json');\n send_nosniff_header();\n header('Cache-Control: no-cache');\n header('Pragma: no-cache');\n\n wp_send_json( $result ); \n\n}\n</code></pre>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233338", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97806/" ]
I am writing a plugin for the first time, and I have a problem. I am using AJAX in my plugin. My JavaScript file is in the folder `../wp-content/plugins/myplugin/js/` , and in it I am trying to call a PHP file, which is in the folder `../wp-content/plugins/myplugin/` ``` jQuery.ajax({ url: "/wp-content/plugins/myplugin/myfile.php?myparam=" + myparam, context: document.body }); ``` My question is: How can I get this URL reference work independent of, where the user installed the plugin. Because when for example a user install this plugin in `http://localhost/subdir/`, the reference is not correct. Can I somehow create a relative link ?
First of all, you shouldn't call your own PHP file. You should use `admin-ajax` endpoint. [Documentation](https://codex.wordpress.org/AJAX_in_Plugins) On admin side, you could use ajaxurl to get URL for AJAX calls. On front side you have to declare by yourself variable with url. This is written in documentation: > > **Note**: Unlike on the admin side, the ajaxurl javascript global does not get automatically defined for you, unless you have BuddyPress or another Ajax-reliant plugin installed. So instead of relying on a global javascript variable, declare a javascript namespace object with its own property, ajaxurl. You might also use wp\_localize\_script() to make the URL available to your script, and generate it using this expression: admin\_url( 'admin-ajax.php' ) > > > This should resolve problem: ``` add_action( 'wp_head', 'front_ajaxurl' ); function front_ajaxurl() { wp_register_script( 'admin_ajax_front', plugin_dir_url(__FILE__) . 'script.js' ); $translation_array = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ); wp_localize_script( 'admin_ajax_front', 'front', $translation_array ); wp_enqueue_script( 'admin_ajax_font', false, array(), false, true ); // last param set to true will enqueue script on footer } ``` And then in your JS file: ``` $.ajax({ url: front.ajaxurl, ... }) ```
233,344
<p>I have one site that is built with <code>html</code>, <code>css</code> and <code>javascript</code> and has no CMS. It looks great and my client would like that site to have wordpress in the background so he can easily modify the content. So, I'm a little bit stuck here.</p> <p>I know that there are plugins for importing well written html, and they work like charm. But, I never done this kind of migration. How can I transfer whole site to wordpress? Is there a way to make some automatic scraping of the whole site, and easy way to import js libraries so i can preserve all classes, div or span tags in html, styles in css etc?</p>
[ { "answer_id": 233350, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 4, "selected": true, "text": "<p>WordPress has a perfect wrapper for HTML > Theme conversion: The theme itself. All information can be found <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow\">in the Codex page</a>.</p>\n\n<p>It is enough to add a folder to your <code>wp-content/themes</code> directory (or whatever directory you registered in addition to that), and add the following files</p>\n\n<ol>\n<li><code>functions.php</code></li>\n<li><code>style.css</code></li>\n<li><code>index.php</code></li>\n<li><code>header.php</code></li>\n</ol>\n\n<p>to your custom <code>themename</code> folder. Then use the <a href=\"https://codex.wordpress.org/Plugin_API\" rel=\"nofollow\">Plugins API</a> to attach some callbacks into the execution flow of WordPress core. This is where you would define basic things like adding stylesheets or scripts. Example for your <code>functions.php</code>:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function() {\n // Register Stylesheets and Scripts in here\n // @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/\n} );\n</code></pre>\n\n<p>In your <code>header.php</code>, you add the opening calls for your HTML:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html &lt;?php language_attributes(); ?&gt;&gt;\n&lt;head&gt;\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n</code></pre>\n\n<p>The <code>wp_head();</code> function calls all the actions and this is where you registered scripts and stylesheets will appear.</p>\n\n<p>In you <code>index.php</code>, you will add your body markup:</p>\n\n<pre><code>&lt;?php get_header(); ?&gt;\n&lt;body &lt;?php body_class(); ?&gt;&gt;\n &lt;!-- Markup from your HTML files --&gt;\n &lt;?php get_footer(); ?&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>The <code>get_footer();</code> function will call a <code>footer.php</code> file if you include one.</p>\n\n<p>Finally you just need to add <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/\" rel=\"nofollow\">Page templates</a> that replace the original PHP files. Those do not really differ from the <code>index.php</code> above, except for one thing: The header comment. Let's assume you add a copy of your <code>index.php</code>, rename it to <code>about-us.php</code> and add the following as first line:</p>\n\n<pre><code>&lt;?php /** Template Name: About Us */ ?&gt;\n</code></pre>\n\n<p>Now, when you in the admin UI go and add a new page, you can select this new template, you will have a replacement file for some existing HTML file. You can even adjust the slug in the admin UI page edit screen.</p>\n\n<p>All that should give you a good start to converting your HTML templates to a valid WordPress theme. You can later and depending on your contract go and make those templates dynamic bit by bit – for example by splitting out repeating sidebars, make menus adjustable, <a href=\"https://codex.wordpress.org/Function_Reference/the_title\" rel=\"nofollow\">change the title</a> and <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow\">the content</a>.</p>\n" }, { "answer_id": 233352, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>It can be done and you can do a quick (relatively) job or take more time on a better site->WP conversion. I'm going to assume that you can write a theme, or this post will turn into a whole book. If not their are many guides online &amp; in print and you don't need to become a full theme expert to get this conversion started. And we can fine tune my answer to your comfort level.</p>\n\n<p>Here's an approach that gets the main conversion done quickly but leaves jobs such as proper inclusion of styles and scripts until later. You may prefer to do a more rigorous job from the start — up to you.</p>\n\n<h1>Step 1 - Get the Site into WP</h1>\n\n<p>Hopefully your HTML is very consistent across the site and you can readily identify a common header and footer. Your first step is to make yourself a new theme with just these files:</p>\n\n<p>style.css - your existing site's styles with the addition of a proper theme header\nheader.php - the HTML for the header\nfooter.php - the HTML for the footer\nindex.php - standard WP index.php with proper calls for header and footer</p>\n\n<p>If your layout has any obvious sidebars that repeat across the site then throw in some sidebar files too.</p>\n\n<p>Make sure that your header and footer include the obligatory calls to wp_head and wp_footer. Keeping an eye on the WP development guidelines as you go as a checklist helps.</p>\n\n<p>Look at your HTML structure for the main page content, the page title and the bulk of the content. You want to get all the structural HTML into your templates so that in the future you aren't relying on the whoever edits the content to write HTML too. When you've identified the page title and content in one of your key pages (not the home page if it has its own layout as they often do) then you can replace the text in those areas with The Loop containing proper calls to the_title, the_content. You can look at separating out any meta data now, or after the first conversion — it's a choice based on your content and how you want to handle things.</p>\n\n<p>Create a Page with the title and content you've just replaced and see how it looks!</p>\n\n<p>You won't be pulling in your JavaScript and Styles in \"The WordPress Way\" but that can come later. At this stage just make sure that the references to them within your theme still resolve and fix them if not.</p>\n\n<h1>Step 2 - Get the HTML site content into WordPress</h1>\n\n<p>I've had people do this manually on small sites. Works fine. I've also used Stephanie Leary's <a href=\"https://en-gb.wordpress.org/plugins/import-html-pages/\" rel=\"nofollow\">HTML Import 2</a> but you can search the plugin repository for others if you wish.</p>\n\n<p>If your site has content that should be Posts or even custom post types rather than Pages then import in batches and use a post type convertor — <a href=\"https://en-gb.wordpress.org/plugins/post-type-switcher/\" rel=\"nofollow\">John James Jacoby's</a> works well for me and I always think a plugin from a core contributor is likely to work well.</p>\n\n<h1>Interval</h1>\n\n<p>You should now have a roughly working site using what will look, at this stage, like a pretty poorly written theme! Improvements to come include properly coding the nav and including styles and scripts the proper way, which Kaiser covers in his answer to this question.</p>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233344", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89803/" ]
I have one site that is built with `html`, `css` and `javascript` and has no CMS. It looks great and my client would like that site to have wordpress in the background so he can easily modify the content. So, I'm a little bit stuck here. I know that there are plugins for importing well written html, and they work like charm. But, I never done this kind of migration. How can I transfer whole site to wordpress? Is there a way to make some automatic scraping of the whole site, and easy way to import js libraries so i can preserve all classes, div or span tags in html, styles in css etc?
WordPress has a perfect wrapper for HTML > Theme conversion: The theme itself. All information can be found [in the Codex page](https://codex.wordpress.org/Theme_Development). It is enough to add a folder to your `wp-content/themes` directory (or whatever directory you registered in addition to that), and add the following files 1. `functions.php` 2. `style.css` 3. `index.php` 4. `header.php` to your custom `themename` folder. Then use the [Plugins API](https://codex.wordpress.org/Plugin_API) to attach some callbacks into the execution flow of WordPress core. This is where you would define basic things like adding stylesheets or scripts. Example for your `functions.php`: ``` add_action( 'wp_enqueue_scripts', function() { // Register Stylesheets and Scripts in here // @link https://developer.wordpress.org/reference/functions/wp_enqueue_script/ } ); ``` In your `header.php`, you add the opening calls for your HTML: ``` <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <?php wp_head(); ?> </head> ``` The `wp_head();` function calls all the actions and this is where you registered scripts and stylesheets will appear. In you `index.php`, you will add your body markup: ``` <?php get_header(); ?> <body <?php body_class(); ?>> <!-- Markup from your HTML files --> <?php get_footer(); ?> </body> ``` The `get_footer();` function will call a `footer.php` file if you include one. Finally you just need to add [Page templates](https://developer.wordpress.org/themes/template-files-section/page-template-files/page-templates/) that replace the original PHP files. Those do not really differ from the `index.php` above, except for one thing: The header comment. Let's assume you add a copy of your `index.php`, rename it to `about-us.php` and add the following as first line: ``` <?php /** Template Name: About Us */ ?> ``` Now, when you in the admin UI go and add a new page, you can select this new template, you will have a replacement file for some existing HTML file. You can even adjust the slug in the admin UI page edit screen. All that should give you a good start to converting your HTML templates to a valid WordPress theme. You can later and depending on your contract go and make those templates dynamic bit by bit – for example by splitting out repeating sidebars, make menus adjustable, [change the title](https://codex.wordpress.org/Function_Reference/the_title) and [the content](https://developer.wordpress.org/reference/functions/the_content/).
233,354
<p>I've searched Google and can find no mention of how to change Wordpress image captions to wrap the caption in a H2 or H3.</p> <p>How do we wrap image captions inside H2, H3 tags?</p> <p>Thanks.</p>
[ { "answer_id": 233362, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 3, "selected": true, "text": "<p>You can hook into the filter <code>img_caption_shortcode</code> and replace the whole captioned image. Here I've copied the caption shortcode function from WP4.5, left the version used if your theme declares HTML5 support as it is (using figcaption) and modified the non-HTML5 version to use h2.</p>\n\n<pre><code>function wpse_233354_img_caption_shortcode( $empty, $attr, $content = null ) {\n // New-style shortcode with the caption inside the shortcode with the link and image tags.\n if ( ! isset( $attr['caption'] ) ) {\n if ( preg_match( '#((?:&lt;a [^&gt;]+&gt;\\s*)?&lt;img [^&gt;]+&gt;(?:\\s*&lt;/a&gt;)?)(.*)#is', $content, $matches ) ) {\n $content = $matches[1];\n $attr['caption'] = trim( $matches[2] );\n }\n } elseif ( strpos( $attr['caption'], '&lt;' ) !== false ) {\n $attr['caption'] = wp_kses( $attr['caption'], 'post' );\n }\n\n $atts = shortcode_atts( array(\n 'id' =&gt; '',\n 'align' =&gt; 'alignnone',\n 'width' =&gt; '',\n 'caption' =&gt; '',\n 'class' =&gt; '',\n ), $attr, 'caption' );\n\n $atts['width'] = (int) $atts['width'];\n if ( $atts['width'] &lt; 1 || empty( $atts['caption'] ) )\n return $content;\n\n if ( ! empty( $atts['id'] ) )\n $atts['id'] = 'id=\"' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '\" ';\n\n $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );\n\n $html5 = current_theme_supports( 'html5', 'caption' );\n // HTML5 captions never added the extra 10px to the image width\n $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );\n\n /**\n * Filter the width of an image's caption.\n *\n * By default, the caption is 10 pixels greater than the width of the image,\n * to prevent post content from running up against a floated image.\n *\n * @since 3.7.0\n *\n * @see img_caption_shortcode()\n *\n * @param int $width Width of the caption in pixels. To remove this inline style,\n * return zero.\n * @param array $atts Attributes of the caption shortcode.\n * @param string $content The image element, possibly wrapped in a hyperlink.\n */\n $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );\n\n $style = '';\n if ( $caption_width )\n $style = 'style=\"width: ' . (int) $caption_width . 'px\" ';\n\n $html = '';\n if ( $html5 ) {\n $html = '&lt;figure ' . $atts['id'] . $style . 'class=\"' . esc_attr( $class ) . '\"&gt;'\n . do_shortcode( $content ) . '&lt;figcaption class=\"wp-caption-text\"&gt;' . $atts['caption'] . '&lt;/figcaption&gt;&lt;/figure&gt;';\n } else {\n $html = '&lt;div ' . $atts['id'] . $style . 'class=\"' . esc_attr( $class ) . '\"&gt;'\n . do_shortcode( $content ) . '&lt;h2 class=\"wp-caption-text\"&gt;' . $atts['caption'] . '&lt;/h2&gt;&lt;/div&gt;';\n }\n\n return $html;\n}\n\nadd_filter( 'img_caption_shortcode', 'wpse_233354_img_caption_shortcode', 10, 3 );\n</code></pre>\n" }, { "answer_id": 233363, "author": "Fabman", "author_id": 40972, "author_profile": "https://wordpress.stackexchange.com/users/40972", "pm_score": 0, "selected": false, "text": "<p>In WordPress you can modify the HTML output of the [caption] shortcode using a custom filter on the img_caption_shortcode hook. You can change things however you want. The filter should return a string containing the full HTML code that should be displayed.</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/img_caption_shortcode\" rel=\"nofollow\">In the codex</a> you have a full example of how to modify it.</p>\n\n<pre><code>add_filter( 'img_caption_shortcode', 'wpse_233363_img_caption_shortcode', 10, 3 );\n\nfunction wpse_233363_img_caption_shortcode( $empty, $attr, $content ){\n $attr = shortcode_atts( array(\n 'id' =&gt; '',\n 'align' =&gt; 'alignnone',\n 'width' =&gt; '',\n 'caption' =&gt; ''\n ), $attr );\n\n if ( 1 &gt; (int) $attr['width'] || empty( $attr['caption'] ) ) {\n return '';\n }\n\n if ( $attr['id'] ) {\n $attr['id'] = 'id=\"' . esc_attr( $attr['id'] ) . '\" ';\n }\n\n return '&lt;div ' . $attr['id']\n . 'class=\"wp-caption ' . esc_attr( $attr['align'] ) . '\" '\n . 'style=\"max-width: ' . ( 10 + (int) $attr['width'] ) . 'px;\"&gt;'\n . do_shortcode( $content )\n . '&lt;p class=\"wp-caption-text\"&gt;' . $attr['caption'] . '&lt;/p&gt;'\n . '&lt;/div&gt;';\n\n}\n</code></pre>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233354", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
I've searched Google and can find no mention of how to change Wordpress image captions to wrap the caption in a H2 or H3. How do we wrap image captions inside H2, H3 tags? Thanks.
You can hook into the filter `img_caption_shortcode` and replace the whole captioned image. Here I've copied the caption shortcode function from WP4.5, left the version used if your theme declares HTML5 support as it is (using figcaption) and modified the non-HTML5 version to use h2. ``` function wpse_233354_img_caption_shortcode( $empty, $attr, $content = null ) { // New-style shortcode with the caption inside the shortcode with the link and image tags. if ( ! isset( $attr['caption'] ) ) { if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) { $content = $matches[1]; $attr['caption'] = trim( $matches[2] ); } } elseif ( strpos( $attr['caption'], '<' ) !== false ) { $attr['caption'] = wp_kses( $attr['caption'], 'post' ); } $atts = shortcode_atts( array( 'id' => '', 'align' => 'alignnone', 'width' => '', 'caption' => '', 'class' => '', ), $attr, 'caption' ); $atts['width'] = (int) $atts['width']; if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) return $content; if ( ! empty( $atts['id'] ) ) $atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" '; $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] ); $html5 = current_theme_supports( 'html5', 'caption' ); // HTML5 captions never added the extra 10px to the image width $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] ); /** * Filter the width of an image's caption. * * By default, the caption is 10 pixels greater than the width of the image, * to prevent post content from running up against a floated image. * * @since 3.7.0 * * @see img_caption_shortcode() * * @param int $width Width of the caption in pixels. To remove this inline style, * return zero. * @param array $atts Attributes of the caption shortcode. * @param string $content The image element, possibly wrapped in a hyperlink. */ $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content ); $style = ''; if ( $caption_width ) $style = 'style="width: ' . (int) $caption_width . 'px" '; $html = ''; if ( $html5 ) { $html = '<figure ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">' . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>'; } else { $html = '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">' . do_shortcode( $content ) . '<h2 class="wp-caption-text">' . $atts['caption'] . '</h2></div>'; } return $html; } add_filter( 'img_caption_shortcode', 'wpse_233354_img_caption_shortcode', 10, 3 ); ```
233,357
<p>I want to apply different styles for a <em>second page</em> in <code>single.php</code> or posts. How can I do this?</p> <p>I have the following code in <code>single.php</code> to split the page in two parts:</p> <pre><code>&lt;!--nextpage--&gt; </code></pre> <p>If there is a different method to add another "tab" to post or the like, I am grateful for any help… I just want to add a "custom page" to my post – like a gallery for a post – so the URL could be like this:</p> <pre><code>http://localhost/mysite/1024/postname/gallery/ http://localhost/mysite/1024/postname/custom-page/ </code></pre> <p>Code in <code>single.php</code>:</p> <pre><code> &lt;?php get_header();?&gt; &lt;main&gt; &lt;?php get_sidebar() ?&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div id="post"&gt; &lt;div class="top-single-movie"&gt; &lt;div class="info"&gt; &lt;h3 class="title" id="post-&lt;?php the_ID(); ?&gt;"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark"&gt; &lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php if( get_field('date') ): ?&gt; ( &lt;?php the_field('date'); ?&gt; ) &lt;?php endif; ?&gt; &lt;/h3&gt; &lt;/div&gt; &lt;?php if(has_post_thumbnail()) : the_post_thumbnail('medium'); else : echo '&lt;img src="'.get_bloginfo('template_directory').'/img/default.png"&gt;'; endif; ?&gt; &lt;/div&gt;&lt;!-- End. top-single-movie --&gt; &lt;?php the_content(); ?&gt; &lt;?php wp_link_pages( array( 'before' =&gt; '&lt;div class="page-link"&gt;&lt;span&gt;' . __( 'Pages:', 'tl_back' ) . '&lt;/span&gt;', 'after' =&gt; '&lt;/div&gt;' ) ); ?&gt; &lt;?php include (TEMPLATEPATH . '/php/single/tv-single-rand.php'); ?&gt; &lt;/div&gt;&lt;!-- End. content-single-movie --&gt; &lt;p class="tags"&gt;&lt;?php the_tags(); ?&gt; &lt;/p&gt; &lt;!--?php comments_template(); // Get comments.php template ?--&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;!-- END Loop --&gt; &lt;ul class="navigationarrows"&gt; &lt;li class="previous"&gt; &lt;?php previous_post_link('&amp;laquo; %link'); ?&gt; &lt;?php if(!get_adjacent_post(false, '', true)) { echo '&lt;span&gt;&amp;laquo;Previous&lt;/span&gt;'; } ?&gt; &lt;/li&gt; &lt;li class="next"&gt; &lt;?php next_post_link('%link &amp;raquo;'); ?&gt; &lt;?php if(!get_adjacent_post(false, '', false)) { echo '&lt;span&gt;Next post:&lt;/span&gt;'; } ?&gt; &lt;/li&gt; &lt;/ul&gt;&lt;!-- end . navigationarrows --&gt; &lt;/div&gt; &lt;/main&gt; &lt;?php get_footer();?&gt; </code></pre>
[ { "answer_id": 233367, "author": "Michae Pavlos Michael", "author_id": 87826, "author_profile": "https://wordpress.stackexchange.com/users/87826", "pm_score": 0, "selected": false, "text": "<p>If you know the post ID, you can target that specific body with custom CSS. For example, if your custom page has an id of 99, you can set up a custom stylesheet and prefix all the selectors with:</p>\n\n<p>body.postid-99</p>\n\n<p>Obviously, this is depending on your theme. If your theme uses a different class in the body tag ( not .postid-99 ) you would have to change the selector accordingly.</p>\n\n<p>...or...</p>\n\n<p>Enqueue the right stylesheet in your theme functions. for example:-</p>\n\n<pre><code>function my_enqueue_scripts(){\n wp_register_style( 'my-css', \"my-stylesheet.css\" );\n wp_enqueue_style( 'my-css' );\n}\n\nif ( get_the_ID() == 99 )\n add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts');\n</code></pre>\n\n<p>Ive not checked the above code but hopefully it helps you get where you need to be.</p>\n" }, { "answer_id": 233377, "author": "lfreitas", "author_id": 99048, "author_profile": "https://wordpress.stackexchange.com/users/99048", "pm_score": 0, "selected": false, "text": "<p>If I understand correctly, you want to create a different template to a new page.</p>\n\n<p>If that's the case, you need to duplicate the single.php of your theme (preferably in a child theme) and use the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">Template Hierarchy</a> to override the default single.php with the new one.</p>\n\n<ol>\n<li>Get the ID of the page you want to do this</li>\n<li>Duplicate the file single.php and rename to single-ID.php, changing \"ID\" with the page id</li>\n<li>Now you can edit the single-ID.php and the changes will only apply to that page.</li>\n</ol>\n\n<p>If you want to apply to more than one page you could create a new template and add a name to it. Then you'd select it in the page edit in all the pages you want, instead of doing it by id. This would depend on the theme you are using.</p>\n" }, { "answer_id": 233379, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body_class template tag.</p>\n\n<p>On the 2nd page of Page, your body will have these additional classes: <code>paged</code>, <code>paged-2</code> &amp; <code>page-paged-2</code>, so you can see that you can make changes to styles to suit:</p>\n\n<pre><code>body.page {\n background: black;\n color: white;\n}\n\nbody.paged {\n background: green;\n color: red;\n}\n</code></pre>\n\n<p>Core achieves this with this logic:</p>\n\n<pre><code>global $wp_query;\n\n$page = $wp_query-&gt;get( 'page' );\n\n if ( ! $page || $page &lt; 2 )\n $page = $wp_query-&gt;get( 'paged' );\n\n if ( $page &amp;&amp; $page &gt; 1 &amp;&amp; ! is_404() ) {\n $classes[] = 'paged-' . $page;\n\n if ( is_single() )\n $classes[] = 'single-paged-' . $page;\n elseif ( is_page() )\n $classes[] = 'page-paged-' . $page;\n elseif ( is_category() )\n $classes[] = 'category-paged-' . $page;\n elseif ( is_tag() )\n $classes[] = 'tag-paged-' . $page;\n elseif ( is_date() )\n $classes[] = 'date-paged-' . $page;\n elseif ( is_author() )\n $classes[] = 'author-paged-' . $page;\n elseif ( is_search() )\n $classes[] = 'search-paged-' . $page;\n elseif ( is_post_type_archive() )\n $classes[] = 'post-type-paged-' . $page;\n}\n</code></pre>\n\n<p>You could adapt this logic within your templates if you wanted to use different HTML on the first &amp; subsequent pages.</p>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233357", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99036/" ]
I want to apply different styles for a *second page* in `single.php` or posts. How can I do this? I have the following code in `single.php` to split the page in two parts: ``` <!--nextpage--> ``` If there is a different method to add another "tab" to post or the like, I am grateful for any help… I just want to add a "custom page" to my post – like a gallery for a post – so the URL could be like this: ``` http://localhost/mysite/1024/postname/gallery/ http://localhost/mysite/1024/postname/custom-page/ ``` Code in `single.php`: ``` <?php get_header();?> <main> <?php get_sidebar() ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div id="post"> <div class="top-single-movie"> <div class="info"> <h3 class="title" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark"> <?php the_title(); ?></a> <?php if( get_field('date') ): ?> ( <?php the_field('date'); ?> ) <?php endif; ?> </h3> </div> <?php if(has_post_thumbnail()) : the_post_thumbnail('medium'); else : echo '<img src="'.get_bloginfo('template_directory').'/img/default.png">'; endif; ?> </div><!-- End. top-single-movie --> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'tl_back' ) . '</span>', 'after' => '</div>' ) ); ?> <?php include (TEMPLATEPATH . '/php/single/tv-single-rand.php'); ?> </div><!-- End. content-single-movie --> <p class="tags"><?php the_tags(); ?> </p> <!--?php comments_template(); // Get comments.php template ?--> <?php endwhile; else: ?> <p> <?php _e('Sorry, no posts matched your criteria.'); ?> </p> <?php endif; ?> <!-- END Loop --> <ul class="navigationarrows"> <li class="previous"> <?php previous_post_link('&laquo; %link'); ?> <?php if(!get_adjacent_post(false, '', true)) { echo '<span>&laquo;Previous</span>'; } ?> </li> <li class="next"> <?php next_post_link('%link &raquo;'); ?> <?php if(!get_adjacent_post(false, '', false)) { echo '<span>Next post:</span>'; } ?> </li> </ul><!-- end . navigationarrows --> </div> </main> <?php get_footer();?> ```
WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body\_class template tag. On the 2nd page of Page, your body will have these additional classes: `paged`, `paged-2` & `page-paged-2`, so you can see that you can make changes to styles to suit: ``` body.page { background: black; color: white; } body.paged { background: green; color: red; } ``` Core achieves this with this logic: ``` global $wp_query; $page = $wp_query->get( 'page' ); if ( ! $page || $page < 2 ) $page = $wp_query->get( 'paged' ); if ( $page && $page > 1 && ! is_404() ) { $classes[] = 'paged-' . $page; if ( is_single() ) $classes[] = 'single-paged-' . $page; elseif ( is_page() ) $classes[] = 'page-paged-' . $page; elseif ( is_category() ) $classes[] = 'category-paged-' . $page; elseif ( is_tag() ) $classes[] = 'tag-paged-' . $page; elseif ( is_date() ) $classes[] = 'date-paged-' . $page; elseif ( is_author() ) $classes[] = 'author-paged-' . $page; elseif ( is_search() ) $classes[] = 'search-paged-' . $page; elseif ( is_post_type_archive() ) $classes[] = 'post-type-paged-' . $page; } ``` You could adapt this logic within your templates if you wanted to use different HTML on the first & subsequent pages.
233,387
<p>I have a function I wrote in my functions.php page for a gallery to display on certain pages. It displays on custom templates, but now I need it to display on index.php Here is the code from my functions.php file:</p> <pre><code>if ( 'templates/awards.php' == $template || 'templates/events.php' == $template ) { $meta[] = array( 'id' =&gt; 'imageupload', 'post_types' =&gt; array( 'page', $post_type), 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'title' =&gt; __( 'Image Gallery', 'min' ), 'fields' =&gt; array( array( 'name' =&gt; __( 'Show', 'min' ), 'id' =&gt; "{$prefix}_gallery-show", 'desc' =&gt; __( '', 'meta-box' ), 'type' =&gt; 'checkbox', 'clone' =&gt; false, ), array( 'id' =&gt; "{$prefix}_image_advanced", 'name' =&gt; __( 'Image Advanced', 'min' ), 'type' =&gt; 'image_advanced', // Delete image from Media Library when remove it from post meta? // Note: it might affect other posts if you use same image for multiple posts 'force_delete' =&gt; false, // Maximum image uploads //'max_file_uploads' =&gt; 2, ), ), ); } if ( 'index.php' == $template ) { $meta[] = array( 'id' =&gt; 'imageupload', 'post_types' =&gt; array( 'page', $post_type), 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'title' =&gt; __( 'Image Gallery', 'min' ), 'fields' =&gt; array( array( 'name' =&gt; __( 'Show', 'min' ), 'id' =&gt; "{$prefix}_gallery-show", 'desc' =&gt; __( '', 'meta-box' ), 'type' =&gt; 'checkbox', 'clone' =&gt; false, ), array( 'id' =&gt; "{$prefix}_image_advanced", 'name' =&gt; __( 'Image Advanced', 'min' ), 'type' =&gt; 'image_advanced', // Delete image from Media Library when remove it from post meta? // Note: it might affect other posts if you use same image for multiple posts 'force_delete' =&gt; false, // Maximum image uploads //'max_file_uploads' =&gt; 2, ), ), ); } function min_get_page_gallery( $echo = true) { global $post; $show_gallery = get_post_meta($post-&gt;ID, 'min_gallery-show', true); if ( empty($show_gallery) ) { return; } $gallery = get_post_meta($post-&gt;ID, 'min_image_advanced', false); ob_start(); ?&gt; &lt;div class="gallery" id="gallery-&lt;?php echo $post-&gt;ID; ?&gt;"&gt; &lt;button class="gallery-move-left"&gt;&lt;i class="fa fa-arrow-circle-left" aria-hidden="true"&gt;&lt;/i&gt;&lt;/button&gt; &lt;div class="image_container clearfix"&gt; &lt;?php $count = count($gallery); $num = ceil($count / 3); echo '&lt;div class="gallery_inner"&gt;'; for ( $i = 0; $i &lt; $count; $i++) { if ( $i % 3 == 0 ) { echo '&lt;div class="row'. (0 == $i ? ' active': ' inactive') .'"&gt;'; } echo '&lt;div class="col-sm-4 img_container' . (0 == $i ? ' active': ' inactive') . '"&gt;'; echo wp_get_attachment_image($gallery[$i], 'thumb-gallery'); echo '&lt;/div&gt;'; if ( $i % 3 == 2 || ($i+1) == $count) { echo '&lt;/div&gt;'; } } echo '&lt;/div&gt;'; ?&gt; &lt;/div&gt; &lt;button class="gallery-move-right"&gt;&lt;i class="fa fa-arrow-circle-right" aria-hidden="true"&gt;&lt;/i&gt;&lt;/button&gt; &lt;/div&gt; &lt;?php $return = ob_get_contents(); ob_end_clean(); if ( $echo ) { echo $return; } else { return $return; } } </code></pre> <p>That code works like a charm on other page templates, such as awards.php . Here is where I call it as min_get_page_gallery(); in awards.php where it works flawlessly:</p> <pre><code> &lt;?php /* Template Name: Awards Page Template */ get_header(); ?&gt; &lt;div class="container" id="block-no-sidebar"&gt; &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;div id="award-list"&gt; &lt;?php echo min_get_awards(); ?&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;?php min_get_page_gallery(); ?&gt; &lt;/div&gt; &lt;?php min_get_page_tabs(); ?&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>Now finally, I try to add the same function call of min_get_page_gallery(); in my index.php file like this:</p> <pre><code> &lt;?php // Silence is golden. if ( ! defined ( 'ABSPATH' ) ) { exit; } ?&gt; &lt;?php get_header(); ?&gt; &lt;style class="take-to-head"&gt; #block-main-content-with-sidebar { background: #ffffff; } &lt;/style&gt; &lt;div class="container" id="block-main-content-with-sidebar"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-8"&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); l('block-' . get_post_type()); endwhile; else: l('block-none' ); endif; ?&gt; &lt;/div&gt; &lt;div class="col-sm-4"&gt; &lt;?php l('block-sidebar'); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;?php min_get_page_gallery(); ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is there something I'm missing??</p>
[ { "answer_id": 233367, "author": "Michae Pavlos Michael", "author_id": 87826, "author_profile": "https://wordpress.stackexchange.com/users/87826", "pm_score": 0, "selected": false, "text": "<p>If you know the post ID, you can target that specific body with custom CSS. For example, if your custom page has an id of 99, you can set up a custom stylesheet and prefix all the selectors with:</p>\n\n<p>body.postid-99</p>\n\n<p>Obviously, this is depending on your theme. If your theme uses a different class in the body tag ( not .postid-99 ) you would have to change the selector accordingly.</p>\n\n<p>...or...</p>\n\n<p>Enqueue the right stylesheet in your theme functions. for example:-</p>\n\n<pre><code>function my_enqueue_scripts(){\n wp_register_style( 'my-css', \"my-stylesheet.css\" );\n wp_enqueue_style( 'my-css' );\n}\n\nif ( get_the_ID() == 99 )\n add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts');\n</code></pre>\n\n<p>Ive not checked the above code but hopefully it helps you get where you need to be.</p>\n" }, { "answer_id": 233377, "author": "lfreitas", "author_id": 99048, "author_profile": "https://wordpress.stackexchange.com/users/99048", "pm_score": 0, "selected": false, "text": "<p>If I understand correctly, you want to create a different template to a new page.</p>\n\n<p>If that's the case, you need to duplicate the single.php of your theme (preferably in a child theme) and use the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">Template Hierarchy</a> to override the default single.php with the new one.</p>\n\n<ol>\n<li>Get the ID of the page you want to do this</li>\n<li>Duplicate the file single.php and rename to single-ID.php, changing \"ID\" with the page id</li>\n<li>Now you can edit the single-ID.php and the changes will only apply to that page.</li>\n</ol>\n\n<p>If you want to apply to more than one page you could create a new template and add a name to it. Then you'd select it in the page edit in all the pages you want, instead of doing it by id. This would depend on the theme you are using.</p>\n" }, { "answer_id": 233379, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body_class template tag.</p>\n\n<p>On the 2nd page of Page, your body will have these additional classes: <code>paged</code>, <code>paged-2</code> &amp; <code>page-paged-2</code>, so you can see that you can make changes to styles to suit:</p>\n\n<pre><code>body.page {\n background: black;\n color: white;\n}\n\nbody.paged {\n background: green;\n color: red;\n}\n</code></pre>\n\n<p>Core achieves this with this logic:</p>\n\n<pre><code>global $wp_query;\n\n$page = $wp_query-&gt;get( 'page' );\n\n if ( ! $page || $page &lt; 2 )\n $page = $wp_query-&gt;get( 'paged' );\n\n if ( $page &amp;&amp; $page &gt; 1 &amp;&amp; ! is_404() ) {\n $classes[] = 'paged-' . $page;\n\n if ( is_single() )\n $classes[] = 'single-paged-' . $page;\n elseif ( is_page() )\n $classes[] = 'page-paged-' . $page;\n elseif ( is_category() )\n $classes[] = 'category-paged-' . $page;\n elseif ( is_tag() )\n $classes[] = 'tag-paged-' . $page;\n elseif ( is_date() )\n $classes[] = 'date-paged-' . $page;\n elseif ( is_author() )\n $classes[] = 'author-paged-' . $page;\n elseif ( is_search() )\n $classes[] = 'search-paged-' . $page;\n elseif ( is_post_type_archive() )\n $classes[] = 'post-type-paged-' . $page;\n}\n</code></pre>\n\n<p>You could adapt this logic within your templates if you wanted to use different HTML on the first &amp; subsequent pages.</p>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233387", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99056/" ]
I have a function I wrote in my functions.php page for a gallery to display on certain pages. It displays on custom templates, but now I need it to display on index.php Here is the code from my functions.php file: ``` if ( 'templates/awards.php' == $template || 'templates/events.php' == $template ) { $meta[] = array( 'id' => 'imageupload', 'post_types' => array( 'page', $post_type), 'context' => 'normal', 'priority' => 'high', 'title' => __( 'Image Gallery', 'min' ), 'fields' => array( array( 'name' => __( 'Show', 'min' ), 'id' => "{$prefix}_gallery-show", 'desc' => __( '', 'meta-box' ), 'type' => 'checkbox', 'clone' => false, ), array( 'id' => "{$prefix}_image_advanced", 'name' => __( 'Image Advanced', 'min' ), 'type' => 'image_advanced', // Delete image from Media Library when remove it from post meta? // Note: it might affect other posts if you use same image for multiple posts 'force_delete' => false, // Maximum image uploads //'max_file_uploads' => 2, ), ), ); } if ( 'index.php' == $template ) { $meta[] = array( 'id' => 'imageupload', 'post_types' => array( 'page', $post_type), 'context' => 'normal', 'priority' => 'high', 'title' => __( 'Image Gallery', 'min' ), 'fields' => array( array( 'name' => __( 'Show', 'min' ), 'id' => "{$prefix}_gallery-show", 'desc' => __( '', 'meta-box' ), 'type' => 'checkbox', 'clone' => false, ), array( 'id' => "{$prefix}_image_advanced", 'name' => __( 'Image Advanced', 'min' ), 'type' => 'image_advanced', // Delete image from Media Library when remove it from post meta? // Note: it might affect other posts if you use same image for multiple posts 'force_delete' => false, // Maximum image uploads //'max_file_uploads' => 2, ), ), ); } function min_get_page_gallery( $echo = true) { global $post; $show_gallery = get_post_meta($post->ID, 'min_gallery-show', true); if ( empty($show_gallery) ) { return; } $gallery = get_post_meta($post->ID, 'min_image_advanced', false); ob_start(); ?> <div class="gallery" id="gallery-<?php echo $post->ID; ?>"> <button class="gallery-move-left"><i class="fa fa-arrow-circle-left" aria-hidden="true"></i></button> <div class="image_container clearfix"> <?php $count = count($gallery); $num = ceil($count / 3); echo '<div class="gallery_inner">'; for ( $i = 0; $i < $count; $i++) { if ( $i % 3 == 0 ) { echo '<div class="row'. (0 == $i ? ' active': ' inactive') .'">'; } echo '<div class="col-sm-4 img_container' . (0 == $i ? ' active': ' inactive') . '">'; echo wp_get_attachment_image($gallery[$i], 'thumb-gallery'); echo '</div>'; if ( $i % 3 == 2 || ($i+1) == $count) { echo '</div>'; } } echo '</div>'; ?> </div> <button class="gallery-move-right"><i class="fa fa-arrow-circle-right" aria-hidden="true"></i></button> </div> <?php $return = ob_get_contents(); ob_end_clean(); if ( $echo ) { echo $return; } else { return $return; } } ``` That code works like a charm on other page templates, such as awards.php . Here is where I call it as min\_get\_page\_gallery(); in awards.php where it works flawlessly: ``` <?php /* Template Name: Awards Page Template */ get_header(); ?> <div class="container" id="block-no-sidebar"> <h1><?php the_title(); ?></h1> <div id="award-list"> <?php echo min_get_awards(); ?> </div> <div class="row"> <?php min_get_page_gallery(); ?> </div> <?php min_get_page_tabs(); ?> </div> <?php get_footer(); ?> ``` Now finally, I try to add the same function call of min\_get\_page\_gallery(); in my index.php file like this: ``` <?php // Silence is golden. if ( ! defined ( 'ABSPATH' ) ) { exit; } ?> <?php get_header(); ?> <style class="take-to-head"> #block-main-content-with-sidebar { background: #ffffff; } </style> <div class="container" id="block-main-content-with-sidebar"> <div class="row"> <div class="col-sm-8"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); l('block-' . get_post_type()); endwhile; else: l('block-none' ); endif; ?> </div> <div class="col-sm-4"> <?php l('block-sidebar'); ?> </div> </div> <div class="row"> <?php min_get_page_gallery(); ?> </div> </div> ``` Is there something I'm missing??
WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body\_class template tag. On the 2nd page of Page, your body will have these additional classes: `paged`, `paged-2` & `page-paged-2`, so you can see that you can make changes to styles to suit: ``` body.page { background: black; color: white; } body.paged { background: green; color: red; } ``` Core achieves this with this logic: ``` global $wp_query; $page = $wp_query->get( 'page' ); if ( ! $page || $page < 2 ) $page = $wp_query->get( 'paged' ); if ( $page && $page > 1 && ! is_404() ) { $classes[] = 'paged-' . $page; if ( is_single() ) $classes[] = 'single-paged-' . $page; elseif ( is_page() ) $classes[] = 'page-paged-' . $page; elseif ( is_category() ) $classes[] = 'category-paged-' . $page; elseif ( is_tag() ) $classes[] = 'tag-paged-' . $page; elseif ( is_date() ) $classes[] = 'date-paged-' . $page; elseif ( is_author() ) $classes[] = 'author-paged-' . $page; elseif ( is_search() ) $classes[] = 'search-paged-' . $page; elseif ( is_post_type_archive() ) $classes[] = 'post-type-paged-' . $page; } ``` You could adapt this logic within your templates if you wanted to use different HTML on the first & subsequent pages.
233,398
<p>I am following a Wordpress book and am trying to create a plugin and have got an option page showing.</p> <p>In this page I have two text fields (which values are stored in one array). I am trying to add custom validation (for example if empty). The validation is set in the third argument in the register_setting function.</p> <p>The book however, does not have any examples of any kind of possible validation (just using Wordpress functions to sanitize the input).</p> <p>To get the error messages showing I followed this link: <a href="https://codex.wordpress.org/Function_Reference/add_settings_error" rel="nofollow">https://codex.wordpress.org/Function_Reference/add_settings_error</a></p> <p>So in the validation function I have made something like this:</p> <pre><code>if( $input['field_1'] == '' ) { $type = 'error'; $message = __( 'Error message for field 1.' ); add_settings_error( 'uniq1', esc_attr( 'settings_updated' ), $message, $type ); } else { $input['field_1'] = sanitize_text_field( $input['field_1']; } if( $input['field_2'] == '' ) { $type = 'error'; $message = __( 'Error message for field 2.' ); add_settings_error( 'uniq2', esc_attr( 'settings_updated' ), $message, $type ); } else { $input['field_2'] = sanitize_text_field( $input['field_2'] } return $input; </code></pre> <p>What I am stuck on is how to NOT update that value if it hits a error condition. What I have currently for example with a empty value will display the correct error message but will still update the value to empty.</p> <p>Is there any way to pass through the old values to that function so I can set the value to the old one if it meets the error condition eg:</p> <pre><code>if( $input['field_1'] != '' ) { $type = 'error'; $message = __( 'Error message for field 1.' ); add_settings_error( 'uniq1', esc_attr( 'settings_updated' ), $message, $type ); $input['field_1'] = "OLD VALUE"; } else { $input['field_1'] = sanitize_text_field( $input['field_1']; } </code></pre> <p>Or if I am approaching this in the wrong way if anyone could point me in the right direction it would be much appreciated.</p>
[ { "answer_id": 233367, "author": "Michae Pavlos Michael", "author_id": 87826, "author_profile": "https://wordpress.stackexchange.com/users/87826", "pm_score": 0, "selected": false, "text": "<p>If you know the post ID, you can target that specific body with custom CSS. For example, if your custom page has an id of 99, you can set up a custom stylesheet and prefix all the selectors with:</p>\n\n<p>body.postid-99</p>\n\n<p>Obviously, this is depending on your theme. If your theme uses a different class in the body tag ( not .postid-99 ) you would have to change the selector accordingly.</p>\n\n<p>...or...</p>\n\n<p>Enqueue the right stylesheet in your theme functions. for example:-</p>\n\n<pre><code>function my_enqueue_scripts(){\n wp_register_style( 'my-css', \"my-stylesheet.css\" );\n wp_enqueue_style( 'my-css' );\n}\n\nif ( get_the_ID() == 99 )\n add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts');\n</code></pre>\n\n<p>Ive not checked the above code but hopefully it helps you get where you need to be.</p>\n" }, { "answer_id": 233377, "author": "lfreitas", "author_id": 99048, "author_profile": "https://wordpress.stackexchange.com/users/99048", "pm_score": 0, "selected": false, "text": "<p>If I understand correctly, you want to create a different template to a new page.</p>\n\n<p>If that's the case, you need to duplicate the single.php of your theme (preferably in a child theme) and use the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">Template Hierarchy</a> to override the default single.php with the new one.</p>\n\n<ol>\n<li>Get the ID of the page you want to do this</li>\n<li>Duplicate the file single.php and rename to single-ID.php, changing \"ID\" with the page id</li>\n<li>Now you can edit the single-ID.php and the changes will only apply to that page.</li>\n</ol>\n\n<p>If you want to apply to more than one page you could create a new template and add a name to it. Then you'd select it in the page edit in all the pages you want, instead of doing it by id. This would depend on the theme you are using.</p>\n" }, { "answer_id": 233379, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body_class template tag.</p>\n\n<p>On the 2nd page of Page, your body will have these additional classes: <code>paged</code>, <code>paged-2</code> &amp; <code>page-paged-2</code>, so you can see that you can make changes to styles to suit:</p>\n\n<pre><code>body.page {\n background: black;\n color: white;\n}\n\nbody.paged {\n background: green;\n color: red;\n}\n</code></pre>\n\n<p>Core achieves this with this logic:</p>\n\n<pre><code>global $wp_query;\n\n$page = $wp_query-&gt;get( 'page' );\n\n if ( ! $page || $page &lt; 2 )\n $page = $wp_query-&gt;get( 'paged' );\n\n if ( $page &amp;&amp; $page &gt; 1 &amp;&amp; ! is_404() ) {\n $classes[] = 'paged-' . $page;\n\n if ( is_single() )\n $classes[] = 'single-paged-' . $page;\n elseif ( is_page() )\n $classes[] = 'page-paged-' . $page;\n elseif ( is_category() )\n $classes[] = 'category-paged-' . $page;\n elseif ( is_tag() )\n $classes[] = 'tag-paged-' . $page;\n elseif ( is_date() )\n $classes[] = 'date-paged-' . $page;\n elseif ( is_author() )\n $classes[] = 'author-paged-' . $page;\n elseif ( is_search() )\n $classes[] = 'search-paged-' . $page;\n elseif ( is_post_type_archive() )\n $classes[] = 'post-type-paged-' . $page;\n}\n</code></pre>\n\n<p>You could adapt this logic within your templates if you wanted to use different HTML on the first &amp; subsequent pages.</p>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233398", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40956/" ]
I am following a Wordpress book and am trying to create a plugin and have got an option page showing. In this page I have two text fields (which values are stored in one array). I am trying to add custom validation (for example if empty). The validation is set in the third argument in the register\_setting function. The book however, does not have any examples of any kind of possible validation (just using Wordpress functions to sanitize the input). To get the error messages showing I followed this link: <https://codex.wordpress.org/Function_Reference/add_settings_error> So in the validation function I have made something like this: ``` if( $input['field_1'] == '' ) { $type = 'error'; $message = __( 'Error message for field 1.' ); add_settings_error( 'uniq1', esc_attr( 'settings_updated' ), $message, $type ); } else { $input['field_1'] = sanitize_text_field( $input['field_1']; } if( $input['field_2'] == '' ) { $type = 'error'; $message = __( 'Error message for field 2.' ); add_settings_error( 'uniq2', esc_attr( 'settings_updated' ), $message, $type ); } else { $input['field_2'] = sanitize_text_field( $input['field_2'] } return $input; ``` What I am stuck on is how to NOT update that value if it hits a error condition. What I have currently for example with a empty value will display the correct error message but will still update the value to empty. Is there any way to pass through the old values to that function so I can set the value to the old one if it meets the error condition eg: ``` if( $input['field_1'] != '' ) { $type = 'error'; $message = __( 'Error message for field 1.' ); add_settings_error( 'uniq1', esc_attr( 'settings_updated' ), $message, $type ); $input['field_1'] = "OLD VALUE"; } else { $input['field_1'] = sanitize_text_field( $input['field_1']; } ``` Or if I am approaching this in the wrong way if anyone could point me in the right direction it would be much appreciated.
WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body\_class template tag. On the 2nd page of Page, your body will have these additional classes: `paged`, `paged-2` & `page-paged-2`, so you can see that you can make changes to styles to suit: ``` body.page { background: black; color: white; } body.paged { background: green; color: red; } ``` Core achieves this with this logic: ``` global $wp_query; $page = $wp_query->get( 'page' ); if ( ! $page || $page < 2 ) $page = $wp_query->get( 'paged' ); if ( $page && $page > 1 && ! is_404() ) { $classes[] = 'paged-' . $page; if ( is_single() ) $classes[] = 'single-paged-' . $page; elseif ( is_page() ) $classes[] = 'page-paged-' . $page; elseif ( is_category() ) $classes[] = 'category-paged-' . $page; elseif ( is_tag() ) $classes[] = 'tag-paged-' . $page; elseif ( is_date() ) $classes[] = 'date-paged-' . $page; elseif ( is_author() ) $classes[] = 'author-paged-' . $page; elseif ( is_search() ) $classes[] = 'search-paged-' . $page; elseif ( is_post_type_archive() ) $classes[] = 'post-type-paged-' . $page; } ``` You could adapt this logic within your templates if you wanted to use different HTML on the first & subsequent pages.
233,402
<p>I am attempting to loop through all sites on my <code>multisite network</code> blog. However, when I attempt to use <code>get_pages</code> it ignores the fact that the blog has switched via <code>switch_to_blog</code>.</p> <pre><code>$sites = wp_get_sites( array( 'limit' =&gt; 1000 ) ); foreach ( $sites as $site ) { $blog_id = intval( $site['blog_id'] ); if ( $blog_id &lt; 2 ) { continue; } switch_to_blog( $blog_id ); $pages = get_pages( array( 'sort_order' =&gt; 'asc', 'sort_column' =&gt; 'ID', 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', ) ); echo 'Blog ID: ' . get_current_blog_id() . ' | Total Pages: ' . count ( $pages ) . '&lt;br&gt;'; // foreach( $pages as $page ) { // echo 'Blog ID: ' . $blog_id . ' | Post ID: ' . $page-&gt;ID . '&lt;br&gt;'; // } restore_current_blog(); } </code></pre> <p>Output:</p> <pre><code>Blog ID: 2 | Total Pages: 71 Blog ID: 3 | Total Pages: 71 Blog ID: 4 | Total Pages: 71 Blog ID: 5 | Total Pages: 71 Blog ID: 6 | Total Pages: 71 Blog ID: 7 | Total Pages: 71 Blog ID: 8 | Total Pages: 71 Blog ID: 9 | Total Pages: 71 Blog ID: 10 | Total Pages: 71 Blog ID: 11 | Total Pages: 71 Blog ID: 12 | Total Pages: 71 Blog ID: 13 | Total Pages: 71 Blog ID: 14 | Total Pages: 71 Blog ID: 15 | Total Pages: 71 Blog ID: 16 | Total Pages: 71 Blog ID: 17 | Total Pages: 71 Blog ID: 18 | Total Pages: 71 Blog ID: 19 | Total Pages: 71 Blog ID: 20 | Total Pages: 71 </code></pre> <p>The script above will var_dump the same <code>$pages</code> through out the entire loop, regardless of which blog it switches to. What exactly am I doing wrong, and is there a way to accomplish what I'm attempting to do?</p>
[ { "answer_id": 233367, "author": "Michae Pavlos Michael", "author_id": 87826, "author_profile": "https://wordpress.stackexchange.com/users/87826", "pm_score": 0, "selected": false, "text": "<p>If you know the post ID, you can target that specific body with custom CSS. For example, if your custom page has an id of 99, you can set up a custom stylesheet and prefix all the selectors with:</p>\n\n<p>body.postid-99</p>\n\n<p>Obviously, this is depending on your theme. If your theme uses a different class in the body tag ( not .postid-99 ) you would have to change the selector accordingly.</p>\n\n<p>...or...</p>\n\n<p>Enqueue the right stylesheet in your theme functions. for example:-</p>\n\n<pre><code>function my_enqueue_scripts(){\n wp_register_style( 'my-css', \"my-stylesheet.css\" );\n wp_enqueue_style( 'my-css' );\n}\n\nif ( get_the_ID() == 99 )\n add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts');\n</code></pre>\n\n<p>Ive not checked the above code but hopefully it helps you get where you need to be.</p>\n" }, { "answer_id": 233377, "author": "lfreitas", "author_id": 99048, "author_profile": "https://wordpress.stackexchange.com/users/99048", "pm_score": 0, "selected": false, "text": "<p>If I understand correctly, you want to create a different template to a new page.</p>\n\n<p>If that's the case, you need to duplicate the single.php of your theme (preferably in a child theme) and use the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">Template Hierarchy</a> to override the default single.php with the new one.</p>\n\n<ol>\n<li>Get the ID of the page you want to do this</li>\n<li>Duplicate the file single.php and rename to single-ID.php, changing \"ID\" with the page id</li>\n<li>Now you can edit the single-ID.php and the changes will only apply to that page.</li>\n</ol>\n\n<p>If you want to apply to more than one page you could create a new template and add a name to it. Then you'd select it in the page edit in all the pages you want, instead of doing it by id. This would depend on the theme you are using.</p>\n" }, { "answer_id": 233379, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body_class template tag.</p>\n\n<p>On the 2nd page of Page, your body will have these additional classes: <code>paged</code>, <code>paged-2</code> &amp; <code>page-paged-2</code>, so you can see that you can make changes to styles to suit:</p>\n\n<pre><code>body.page {\n background: black;\n color: white;\n}\n\nbody.paged {\n background: green;\n color: red;\n}\n</code></pre>\n\n<p>Core achieves this with this logic:</p>\n\n<pre><code>global $wp_query;\n\n$page = $wp_query-&gt;get( 'page' );\n\n if ( ! $page || $page &lt; 2 )\n $page = $wp_query-&gt;get( 'paged' );\n\n if ( $page &amp;&amp; $page &gt; 1 &amp;&amp; ! is_404() ) {\n $classes[] = 'paged-' . $page;\n\n if ( is_single() )\n $classes[] = 'single-paged-' . $page;\n elseif ( is_page() )\n $classes[] = 'page-paged-' . $page;\n elseif ( is_category() )\n $classes[] = 'category-paged-' . $page;\n elseif ( is_tag() )\n $classes[] = 'tag-paged-' . $page;\n elseif ( is_date() )\n $classes[] = 'date-paged-' . $page;\n elseif ( is_author() )\n $classes[] = 'author-paged-' . $page;\n elseif ( is_search() )\n $classes[] = 'search-paged-' . $page;\n elseif ( is_post_type_archive() )\n $classes[] = 'post-type-paged-' . $page;\n}\n</code></pre>\n\n<p>You could adapt this logic within your templates if you wanted to use different HTML on the first &amp; subsequent pages.</p>\n" } ]
2016/07/27
[ "https://wordpress.stackexchange.com/questions/233402", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83247/" ]
I am attempting to loop through all sites on my `multisite network` blog. However, when I attempt to use `get_pages` it ignores the fact that the blog has switched via `switch_to_blog`. ``` $sites = wp_get_sites( array( 'limit' => 1000 ) ); foreach ( $sites as $site ) { $blog_id = intval( $site['blog_id'] ); if ( $blog_id < 2 ) { continue; } switch_to_blog( $blog_id ); $pages = get_pages( array( 'sort_order' => 'asc', 'sort_column' => 'ID', 'post_type' => 'page', 'post_status' => 'publish', ) ); echo 'Blog ID: ' . get_current_blog_id() . ' | Total Pages: ' . count ( $pages ) . '<br>'; // foreach( $pages as $page ) { // echo 'Blog ID: ' . $blog_id . ' | Post ID: ' . $page->ID . '<br>'; // } restore_current_blog(); } ``` Output: ``` Blog ID: 2 | Total Pages: 71 Blog ID: 3 | Total Pages: 71 Blog ID: 4 | Total Pages: 71 Blog ID: 5 | Total Pages: 71 Blog ID: 6 | Total Pages: 71 Blog ID: 7 | Total Pages: 71 Blog ID: 8 | Total Pages: 71 Blog ID: 9 | Total Pages: 71 Blog ID: 10 | Total Pages: 71 Blog ID: 11 | Total Pages: 71 Blog ID: 12 | Total Pages: 71 Blog ID: 13 | Total Pages: 71 Blog ID: 14 | Total Pages: 71 Blog ID: 15 | Total Pages: 71 Blog ID: 16 | Total Pages: 71 Blog ID: 17 | Total Pages: 71 Blog ID: 18 | Total Pages: 71 Blog ID: 19 | Total Pages: 71 Blog ID: 20 | Total Pages: 71 ``` The script above will var\_dump the same `$pages` through out the entire loop, regardless of which blog it switches to. What exactly am I doing wrong, and is there a way to accomplish what I'm attempting to do?
WordPress already adds classes to the body for you to handle this, as long as your theme correctly uses the body\_class template tag. On the 2nd page of Page, your body will have these additional classes: `paged`, `paged-2` & `page-paged-2`, so you can see that you can make changes to styles to suit: ``` body.page { background: black; color: white; } body.paged { background: green; color: red; } ``` Core achieves this with this logic: ``` global $wp_query; $page = $wp_query->get( 'page' ); if ( ! $page || $page < 2 ) $page = $wp_query->get( 'paged' ); if ( $page && $page > 1 && ! is_404() ) { $classes[] = 'paged-' . $page; if ( is_single() ) $classes[] = 'single-paged-' . $page; elseif ( is_page() ) $classes[] = 'page-paged-' . $page; elseif ( is_category() ) $classes[] = 'category-paged-' . $page; elseif ( is_tag() ) $classes[] = 'tag-paged-' . $page; elseif ( is_date() ) $classes[] = 'date-paged-' . $page; elseif ( is_author() ) $classes[] = 'author-paged-' . $page; elseif ( is_search() ) $classes[] = 'search-paged-' . $page; elseif ( is_post_type_archive() ) $classes[] = 'post-type-paged-' . $page; } ``` You could adapt this logic within your templates if you wanted to use different HTML on the first & subsequent pages.
233,447
<p>In the admin backend we use a query arg that is left in the URL and keeps getting used whether it is supposed to or not.</p> <p>Our plugin has an array with values that can be toggled via the custom backend page. Against the option that should be toggled there is a link titled 'Activate' or 'Deactivate', pressing that link returns to the same admin page but with an added query arg which is parsed when the page is initialised. The admin page can be reloaded by following the toggle links or pressing the standard 'Save changes' backend button. The problem is that with the query arg remains in the URL when 'Save changes' is pressed, so the value is toggled again without the 'Activate' or 'Deactivate' being followed.</p> <p>The arg should be removed when 'Save Changes' is pressed. Is there a filter for the 'Save changes' button so we could add our own filter to remove the custom arg?</p> <pre><code>class Custom_Admin { private $options; public function __construct() { $this-&gt;options = get_option( 'custom_options' ); add_filter('query_vars', array($this, 'add_query_vars')); add_action('init', array($this, 'check_query_vars') ); } public function add_query_vars($public_query_vars) { $public_query_vars[] = 'code_key'; return $public_query_vars; } public function check_query_vars() { $code_key = isset($_GET["code_key"]) ? $_GET["code_key"] : ''; $active = $this-&gt;options[$code_key]['active']; $this-&gt;options[$code_key]['active'] = ($active == true ? false : true); update_option('custom_options', $this-&gt;options); } public function page_init() { register_setting( 'group', // Option group 'options', // Option name array( $this, 'sanitize' ) // Sanitize ); } public function sanitize($input) { // Parse and sanitise more stuff here like a normal person } } </code></pre>
[ { "answer_id": 233464, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>If you are using the Settings API for the Save Changes, you are probably using a nonce field with it (if not it is easy enough to add with <code>wp_nonce_field</code> whether you are using Settings API or not) ... </p>\n\n<p>So testing for the presence of the nonce field is one way to test and help you distiguish between what action should be happening so as to not update the other custom option. eg.</p>\n\n<pre><code>public function check_query_vars() {\n // bug out here if nonce value is set\n if (isset($_REQUEST['_wpnonce'])) {return;}\n\n $code_key = isset($_GET[\"code_key\"]) ? $_GET[\"code_key\"] : '';\n\n $active = $this-&gt;options[$code_key]['active'];\n $this-&gt;options[$code_key]['active'] = ($active == true ? false : true);\n\n update_option('custom_options', $this-&gt;options);\n}\n</code></pre>\n" }, { "answer_id": 233467, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p>Maybe JS will do what you want? This should be the easiest way to achieve what you want. More info about <a href=\"https://stackoverflow.com/questions/1634748/how-can-i-delete-a-query-string-parameter-in-javascript\">removing query string param in JS</a></p>\n" }, { "answer_id": 260754, "author": "AncientRo", "author_id": 110373, "author_profile": "https://wordpress.stackexchange.com/users/110373", "pm_score": 3, "selected": false, "text": "<p>This might be useful: there is a filter called <a href=\"https://developer.wordpress.org/reference/hooks/removable_query_args/\" rel=\"noreferrer\">removable_query_args</a>. You get an array of argument names to which you can append your own argument. Then WP will take care of removing all of the arguments in the list from the URL.</p>\n\n<pre><code>function add_removable_arg($args) {\n array_push($args, 'my-query-arg');\n return $args;\n}\n\nadd_filter('removable_query_args', 'add_removable_arg');\n</code></pre>\n\n<p>Something like:</p>\n\n<pre><code>'...post.php?post=1&amp;my-query-arg=10'\n</code></pre>\n\n<p>Will become:</p>\n\n<pre><code>'...post.php?post=1'\n</code></pre>\n" } ]
2016/07/28
[ "https://wordpress.stackexchange.com/questions/233447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82822/" ]
In the admin backend we use a query arg that is left in the URL and keeps getting used whether it is supposed to or not. Our plugin has an array with values that can be toggled via the custom backend page. Against the option that should be toggled there is a link titled 'Activate' or 'Deactivate', pressing that link returns to the same admin page but with an added query arg which is parsed when the page is initialised. The admin page can be reloaded by following the toggle links or pressing the standard 'Save changes' backend button. The problem is that with the query arg remains in the URL when 'Save changes' is pressed, so the value is toggled again without the 'Activate' or 'Deactivate' being followed. The arg should be removed when 'Save Changes' is pressed. Is there a filter for the 'Save changes' button so we could add our own filter to remove the custom arg? ``` class Custom_Admin { private $options; public function __construct() { $this->options = get_option( 'custom_options' ); add_filter('query_vars', array($this, 'add_query_vars')); add_action('init', array($this, 'check_query_vars') ); } public function add_query_vars($public_query_vars) { $public_query_vars[] = 'code_key'; return $public_query_vars; } public function check_query_vars() { $code_key = isset($_GET["code_key"]) ? $_GET["code_key"] : ''; $active = $this->options[$code_key]['active']; $this->options[$code_key]['active'] = ($active == true ? false : true); update_option('custom_options', $this->options); } public function page_init() { register_setting( 'group', // Option group 'options', // Option name array( $this, 'sanitize' ) // Sanitize ); } public function sanitize($input) { // Parse and sanitise more stuff here like a normal person } } ```
This might be useful: there is a filter called [removable\_query\_args](https://developer.wordpress.org/reference/hooks/removable_query_args/). You get an array of argument names to which you can append your own argument. Then WP will take care of removing all of the arguments in the list from the URL. ``` function add_removable_arg($args) { array_push($args, 'my-query-arg'); return $args; } add_filter('removable_query_args', 'add_removable_arg'); ``` Something like: ``` '...post.php?post=1&my-query-arg=10' ``` Will become: ``` '...post.php?post=1' ```
233,450
<p>I would like to be able add the same custom colours to the swatches at bottom of colour picker panels that appear in the WYSIWYG editors across the site, to make it easier for clients to keep consistent in their styling.</p> <p>The swatches I refer to are the bottom row in the screenshot.</p> <p>I would like to do this without installing a plug-in, ideally.</p> <p><a href="https://i.stack.imgur.com/JeC7j.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JeC7j.png" alt="Colour chooser"></a></p>
[ { "answer_id": 233452, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 5, "selected": true, "text": "<p>Click on the <code>Custom...</code> text and the color picker will pop up. Pick the color of your choice and press <code>OK</code>. Chosen color will appear as a custom swatch for later use.</p>\n\n<p><strong>Note!</strong> The solution above is not a solution. See comments and edit below.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Here is a function which replaces the entire default palette with custom swatches.</p>\n\n<p>Note, there are 7 colors in the list instead 8. That's because there should be also the <em>multiplication&nbsp;X</em> (&amp;#10005;) at the end of the color list which removes any color applied to the text. So, when adding one more row there should be 15 colors, not 16.</p>\n\n<pre><code>function my_mce4_options($init) {\n\n $custom_colours = '\n \"3366FF\", \"Color 1 name\",\n \"CCFFCC\", \"Color 2 name\",\n \"FFFF00\", \"Color 3 name\",\n \"99CC00\", \"Color 4 name\",\n \"FF0000\", \"Color 5 name\",\n \"FF99CC\", \"Color 6 name\",\n \"CCFFFF\", \"Color 7 name\"\n ';\n\n // build colour grid default+custom colors\n $init['textcolor_map'] = '['.$custom_colours.']';\n\n // change the number of rows in the grid if the number of colors changes\n // 8 swatches per row\n $init['textcolor_rows'] = 1;\n\n return $init;\n}\nadd_filter('tiny_mce_before_init', 'my_mce4_options');\n</code></pre>\n\n<p>Also, you can build you own swatch grid depending on the color number and UI requrements:</p>\n\n<pre><code>$init['textcolor_rows'] = 4;\n$init['textcolor_cols'] = 2;\n</code></pre>\n\n<p>Largely based on <a href=\"https://stackoverflow.com/a/23183406/577418\">this WPSE answer</a>.</p>\n\n<p>For more information and customization see <a href=\"https://urosevic.net/wordpress/tips/custom-colours-tinymce-4-wordpress-39/\" rel=\"noreferrer\">this blog post</a>.</p>\n" }, { "answer_id": 349485, "author": "JDandChips", "author_id": 134142, "author_profile": "https://wordpress.stackexchange.com/users/134142", "pm_score": 3, "selected": false, "text": "<p>In addition to Max's answer, if you are looking to add to the existing pallet, here is the default colour pallet:</p>\n\n<pre><code>$custom_colours = '[\n \"000000\", \"Black\",\n \"993300\", \"Burnt orange\",\n \"333300\", \"Dark olive\",\n \"003300\", \"Dark green\",\n \"003366\", \"Dark azure\",\n \"000080\", \"Navy Blue\",\n \"333399\", \"Indigo\",\n \"333333\", \"Very dark gray\",\n \"800000\", \"Maroon\",\n \"FF6600\", \"Orange\",\n \"808000\", \"Olive\",\n \"008000\", \"Green\",\n \"008080\", \"Teal\",\n \"0000FF\", \"Blue\",\n \"666699\", \"Grayish blue\",\n \"808080\", \"Gray\",\n \"FF0000\", \"Red\",\n \"FF9900\", \"Amber\",\n \"99CC00\", \"Yellow green\",\n \"339966\", \"Sea green\",\n \"33CCCC\", \"Turquoise\",\n \"3366FF\", \"Royal blue\",\n \"800080\", \"Purple\",\n \"999999\", \"Medium gray\",\n \"FF00FF\", \"Magenta\",\n \"FFCC00\", \"Gold\",\n \"FFFF00\", \"Yellow\",\n \"00FF00\", \"Lime\",\n \"00FFFF\", \"Aqua\",\n \"00CCFF\", \"Sky blue\",\n \"993366\", \"Red violet\",\n \"FFFFFF\", \"White\",\n \"FF99CC\", \"Pink\",\n \"FFCC99\", \"Peach\",\n \"FFFF99\", \"Light yellow\",\n \"CCFFCC\", \"Pale green\",\n \"CCFFFF\", \"Pale cyan\",\n \"99CCFF\", \"Light sky blue\",\n \"CC99FF\", \"Plum\",\n ... CUSTOM HERE ...\n ]';\n</code></pre>\n" } ]
2016/07/28
[ "https://wordpress.stackexchange.com/questions/233450", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76241/" ]
I would like to be able add the same custom colours to the swatches at bottom of colour picker panels that appear in the WYSIWYG editors across the site, to make it easier for clients to keep consistent in their styling. The swatches I refer to are the bottom row in the screenshot. I would like to do this without installing a plug-in, ideally. [![Colour chooser](https://i.stack.imgur.com/JeC7j.png)](https://i.stack.imgur.com/JeC7j.png)
Click on the `Custom...` text and the color picker will pop up. Pick the color of your choice and press `OK`. Chosen color will appear as a custom swatch for later use. **Note!** The solution above is not a solution. See comments and edit below. **Edit:** Here is a function which replaces the entire default palette with custom swatches. Note, there are 7 colors in the list instead 8. That's because there should be also the *multiplication X* (&#10005;) at the end of the color list which removes any color applied to the text. So, when adding one more row there should be 15 colors, not 16. ``` function my_mce4_options($init) { $custom_colours = ' "3366FF", "Color 1 name", "CCFFCC", "Color 2 name", "FFFF00", "Color 3 name", "99CC00", "Color 4 name", "FF0000", "Color 5 name", "FF99CC", "Color 6 name", "CCFFFF", "Color 7 name" '; // build colour grid default+custom colors $init['textcolor_map'] = '['.$custom_colours.']'; // change the number of rows in the grid if the number of colors changes // 8 swatches per row $init['textcolor_rows'] = 1; return $init; } add_filter('tiny_mce_before_init', 'my_mce4_options'); ``` Also, you can build you own swatch grid depending on the color number and UI requrements: ``` $init['textcolor_rows'] = 4; $init['textcolor_cols'] = 2; ``` Largely based on [this WPSE answer](https://stackoverflow.com/a/23183406/577418). For more information and customization see [this blog post](https://urosevic.net/wordpress/tips/custom-colours-tinymce-4-wordpress-39/).
233,498
<p>I need to turn this code: </p> <pre><code>&lt;?php if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp(); ?&gt; </code></pre> <p>into a shortcode. Can someone help me do this? I have researched but am just lost to be honest. Thanks!</p>
[ { "answer_id": 233499, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 1, "selected": false, "text": "<p>Do you mean something like this (untested):</p>\n\n<pre><code>// function for your shortcode\nfunction shortcode_action($atts) {\n\n ob_start();\n if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp();\n $content = ob_get_clean();\n return $content;\n}\n\n// creates shortcode [shortcodehandle] so change it accordingly\nadd_shortcode( 'shortcodehandle', 'shortcode_action' );\n</code></pre>\n\n<p>Update: using <a href=\"http://php.net/manual/en/function.ob-get-contents.php\" rel=\"nofollow\">ob_get_contents</a> to return the content of the output of <code>echo_ald_crp</code>.</p>\n\n<p>Update 2: using <a href=\"http://php.net/manual/en/function.ob-get-clean.php\" rel=\"nofollow\">ob_get_clean()</a> as highlighted by @jgraup in the comments.</p>\n" }, { "answer_id": 233504, "author": "Jean-philippe Emond", "author_id": 99064, "author_profile": "https://wordpress.stackexchange.com/users/99064", "pm_score": 2, "selected": false, "text": "<p>Init your shortcode</p>\n\n<pre><code>add_shortcode('shortcode_ald_crp', 'myshortcode_echo_ald_crp');\n</code></pre>\n\n<p>The function what you want:</p>\n\n<pre><code>function myshortcode_echo_ald_crp() {\n ob_start(); \n if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp();\n return ob_get_clean();\n}\n</code></pre>\n\n<p>you call you shortcode in a post like this:</p>\n\n<pre><code>[shortcode_ald_crp]\n</code></pre>\n\n<p>Or into the php code:</p>\n\n<pre><code>echo do_shortcode('[shortcode_ald_crp]');\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Change the function <code>add_shortcode</code></p>\n\n<p><code>shortcode_ald_crp</code> for <code>myshortcode_echo_ald_crp</code></p>\n" } ]
2016/07/28
[ "https://wordpress.stackexchange.com/questions/233498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99146/" ]
I need to turn this code: ``` <?php if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp(); ?> ``` into a shortcode. Can someone help me do this? I have researched but am just lost to be honest. Thanks!
Init your shortcode ``` add_shortcode('shortcode_ald_crp', 'myshortcode_echo_ald_crp'); ``` The function what you want: ``` function myshortcode_echo_ald_crp() { ob_start(); if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp(); return ob_get_clean(); } ``` you call you shortcode in a post like this: ``` [shortcode_ald_crp] ``` Or into the php code: ``` echo do_shortcode('[shortcode_ald_crp]'); ``` **UPDATE** Change the function `add_shortcode` `shortcode_ald_crp` for `myshortcode_echo_ald_crp`
233,503
<p>When i use the <strong>"get_template_part();" inside a loop</strong>, does it search for that template file <strong>every cycle</strong> of the loop (each post) <strong>or</strong> does it search for the file <strong>once</strong> and then reuse it every cycle of the loop?</p>
[ { "answer_id": 233499, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 1, "selected": false, "text": "<p>Do you mean something like this (untested):</p>\n\n<pre><code>// function for your shortcode\nfunction shortcode_action($atts) {\n\n ob_start();\n if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp();\n $content = ob_get_clean();\n return $content;\n}\n\n// creates shortcode [shortcodehandle] so change it accordingly\nadd_shortcode( 'shortcodehandle', 'shortcode_action' );\n</code></pre>\n\n<p>Update: using <a href=\"http://php.net/manual/en/function.ob-get-contents.php\" rel=\"nofollow\">ob_get_contents</a> to return the content of the output of <code>echo_ald_crp</code>.</p>\n\n<p>Update 2: using <a href=\"http://php.net/manual/en/function.ob-get-clean.php\" rel=\"nofollow\">ob_get_clean()</a> as highlighted by @jgraup in the comments.</p>\n" }, { "answer_id": 233504, "author": "Jean-philippe Emond", "author_id": 99064, "author_profile": "https://wordpress.stackexchange.com/users/99064", "pm_score": 2, "selected": false, "text": "<p>Init your shortcode</p>\n\n<pre><code>add_shortcode('shortcode_ald_crp', 'myshortcode_echo_ald_crp');\n</code></pre>\n\n<p>The function what you want:</p>\n\n<pre><code>function myshortcode_echo_ald_crp() {\n ob_start(); \n if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp();\n return ob_get_clean();\n}\n</code></pre>\n\n<p>you call you shortcode in a post like this:</p>\n\n<pre><code>[shortcode_ald_crp]\n</code></pre>\n\n<p>Or into the php code:</p>\n\n<pre><code>echo do_shortcode('[shortcode_ald_crp]');\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Change the function <code>add_shortcode</code></p>\n\n<p><code>shortcode_ald_crp</code> for <code>myshortcode_echo_ald_crp</code></p>\n" } ]
2016/07/28
[ "https://wordpress.stackexchange.com/questions/233503", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43619/" ]
When i use the **"get\_template\_part();" inside a loop**, does it search for that template file **every cycle** of the loop (each post) **or** does it search for the file **once** and then reuse it every cycle of the loop?
Init your shortcode ``` add_shortcode('shortcode_ald_crp', 'myshortcode_echo_ald_crp'); ``` The function what you want: ``` function myshortcode_echo_ald_crp() { ob_start(); if ( function_exists( 'echo_ald_crp' ) ) echo_ald_crp(); return ob_get_clean(); } ``` you call you shortcode in a post like this: ``` [shortcode_ald_crp] ``` Or into the php code: ``` echo do_shortcode('[shortcode_ald_crp]'); ``` **UPDATE** Change the function `add_shortcode` `shortcode_ald_crp` for `myshortcode_echo_ald_crp`
233,513
<blockquote> <p>This is a continuing question from <a href="https://wordpress.stackexchange.com/questions/232029/merging-a-complex-query-with-post-rewind-and-splitting-posts-into-two-columns">Merging a complex query with post_rewind and splitting posts into two columns</a></p> </blockquote> <p>Hi, I need help with my loop. What is does is split posts into two columns.</p> <pre><code>&lt;?php $row_start = 1; while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?&gt; &lt;?php if( $row_start % 2 != 0) {// odd ?&gt; &lt;div class="post"&gt; left - &lt;?php the_title();?&gt;&lt;br&gt; &lt;/div&gt; &lt;?php } ;?&gt; &lt;?php if( $row_start % 2 == 0) {// even ?&gt; &lt;div class="post"&gt; right - &lt;?php the_title();?&gt;&lt;br&gt; &lt;/div&gt; &lt;?php } ;?&gt; &lt;?php ++$row_start; endwhile; wp_reset_postdata(); endif; ?&gt; </code></pre> <p>It outputs the loop as the following:</p> <pre><code>&lt;div class="left"&gt;post&lt;/div&gt; &lt;div class="left"&gt;post&lt;/div&gt; &lt;div class="right"&gt;post&lt;/div&gt; &lt;div class="left"&gt;post&lt;/div&gt; &lt;div class="right"&gt;post&lt;/div&gt; &lt;div class="left"&gt;post&lt;/div&gt; &lt;div class="right"&gt;post&lt;/div&gt; </code></pre> <p>What I would to do is to wrap all posts in a div, like the following:</p> <pre><code>&lt;div class="left"&gt; post post post &lt;/div&gt; &lt;div class="right"&gt; post post post &lt;/div&gt; </code></pre> <p>Thanks </p>
[ { "answer_id": 233514, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 2, "selected": false, "text": "<p>Run through the loop with % for the left side first, then rewind the loop and start in on the right side. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/rewind_posts</a></p>\n\n<p>Update:</p>\n\n<p>Based on the answer you selected that stores the ID in two different arrays, then loops through those IDs again per side - you might want to consider reducing the loops by only storing the resulting output into two separate strings. </p>\n\n<p><code>ob_start()</code> will capture the output buffer, do your visual logic and <code>$&lt;side&gt; .= ob_get_clean()</code> will append the data. </p>\n\n<p>When your loop is finished you only need to <code>echo \"&lt;div&gt;$left&lt;/div&gt;&lt;div&gt;$right&lt;/div&gt;\";</code></p>\n" }, { "answer_id": 233523, "author": "gloria", "author_id": 28571, "author_profile": "https://wordpress.stackexchange.com/users/28571", "pm_score": 2, "selected": true, "text": "<p>You could always try to create 2 arrays of titles, say $left and $right, $odd and $even, or $tom and $jerry, and fill them with the titles during your loop, and print them after the loop has ended like so:</p>\n\n<p>Create array</p>\n\n<pre><code>$left = $right = array();\n</code></pre>\n\n<p>Then unleash your loop [edited the below to reflect the comments]</p>\n\n<pre><code>&lt;?php // The loop\n\n if ( $query-&gt;have_posts() ) : $row_start = 1; \n while ( $query-&gt;have_posts() ) : $query-&gt;the_post();\n\n if ( in_array( get_the_ID(), $duplicates ) ) continue;\n if( $row_start % 2 != 0) {\n // odd: add result to $left\n // $left[] = get_the_title();\n $left[] = $post-&gt;id;\n } else {\n // even: add it to $right\n //$right[] = get_the_title();\n $right[] = $post-&gt;id;\n }\n ++$row_start; endwhile; wp_reset_postdata();\n // now loop has ended and we have 2 full arrays\n // that we can print each in it's div\n print \"&lt;div class=\\\"left\\\"&gt;\";\n foreach($left as $postID) {\n $postData = get_post( $postID );\n print $postData-&gt;post_title;\n print $postData-&gt;post_content;\n // etc... you can also get thumbnails using the post ID:\n print get_the_post_thumbnail($postID, 'thumbnail');\n }\n print \"&lt;/div&gt;\";\n // next column\n print \"&lt;div class=\\\"right\\\"&gt;\";\n foreach($right as $postID) {\n // ... just like the above...\n }\n print \"&lt;/div&gt;\";\n endif;\n\n?&gt;\n</code></pre>\n\n<p>I've not yet tested this but it should work (or some close variation of it). I personally would output the list of posts in unordered lists (<code>&lt;ul class=\"right or left\"&gt;</code>) and put each title in an <code>&lt;li&gt;</code>.</p>\n\n<p>Good luck :)</p>\n" } ]
2016/07/28
[ "https://wordpress.stackexchange.com/questions/233513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
> > This is a continuing question from [Merging a complex query with post\_rewind and splitting posts into two columns](https://wordpress.stackexchange.com/questions/232029/merging-a-complex-query-with-post-rewind-and-splitting-posts-into-two-columns) > > > Hi, I need help with my loop. What is does is split posts into two columns. ``` <?php $row_start = 1; while ( $query->have_posts() ) : $query->the_post(); ?> <?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?> <?php if( $row_start % 2 != 0) {// odd ?> <div class="post"> left - <?php the_title();?><br> </div> <?php } ;?> <?php if( $row_start % 2 == 0) {// even ?> <div class="post"> right - <?php the_title();?><br> </div> <?php } ;?> <?php ++$row_start; endwhile; wp_reset_postdata(); endif; ?> ``` It outputs the loop as the following: ``` <div class="left">post</div> <div class="left">post</div> <div class="right">post</div> <div class="left">post</div> <div class="right">post</div> <div class="left">post</div> <div class="right">post</div> ``` What I would to do is to wrap all posts in a div, like the following: ``` <div class="left"> post post post </div> <div class="right"> post post post </div> ``` Thanks
You could always try to create 2 arrays of titles, say $left and $right, $odd and $even, or $tom and $jerry, and fill them with the titles during your loop, and print them after the loop has ended like so: Create array ``` $left = $right = array(); ``` Then unleash your loop [edited the below to reflect the comments] ``` <?php // The loop if ( $query->have_posts() ) : $row_start = 1; while ( $query->have_posts() ) : $query->the_post(); if ( in_array( get_the_ID(), $duplicates ) ) continue; if( $row_start % 2 != 0) { // odd: add result to $left // $left[] = get_the_title(); $left[] = $post->id; } else { // even: add it to $right //$right[] = get_the_title(); $right[] = $post->id; } ++$row_start; endwhile; wp_reset_postdata(); // now loop has ended and we have 2 full arrays // that we can print each in it's div print "<div class=\"left\">"; foreach($left as $postID) { $postData = get_post( $postID ); print $postData->post_title; print $postData->post_content; // etc... you can also get thumbnails using the post ID: print get_the_post_thumbnail($postID, 'thumbnail'); } print "</div>"; // next column print "<div class=\"right\">"; foreach($right as $postID) { // ... just like the above... } print "</div>"; endif; ?> ``` I've not yet tested this but it should work (or some close variation of it). I personally would output the list of posts in unordered lists (`<ul class="right or left">`) and put each title in an `<li>`. Good luck :)
233,515
<p>I think I might be able to parse the URL for the <code>replytocom</code> parameter and get the comment ID from that. However, it would mean that my plugin would not be fully compatible with other plugins that can remove this parameter (most notably <em>Yoast SEO</em>). Plus, it feels a bit hacky. Is there another way?</p> <p>Endgoal: I need that comment ID to use in an AJAX request - to fetch data (such as the comment thread depth) so that I can display custom data in the front end. </p>
[ { "answer_id": 233528, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": true, "text": "<p>Here are few ideas:</p>\n\n<ul>\n<li><p>It's possible to inject custom HTML or data attributes via the <a href=\"https://developer.wordpress.org/reference/functions/comment_reply_link/\" rel=\"nofollow\"><code>comment_reply_link</code></a> filter, but I think it would be better to keep it unobtrusive. </p></li>\n<li><p>One could try to get the comment parent value from the reply comment form:</p>\n\n<pre><code>&lt;input type='hidden' name='comment_parent' id='comment_parent' value='0' /&gt;\n</code></pre>\n\n<p>after it has been updated with the corresponding value.</p></li>\n<li><p>Another approach would be to scan for IDs in the HTML of the comments list:</p>\n\n<p>Generated by the <code>Walker_Comment::html5_comment()</code>:</p>\n\n<pre><code>&lt;li id=\"comment-34\" class=\"comment even thread-even depth-1\"&gt;\n &lt;article id=\"div-comment-34\" class=\"comment-body\"&gt;\n ... cut...\n</code></pre>\n\n<p>Generated by the <code>Walker_Comment::comment()</code>:</p>\n\n<pre><code>&lt;li class=\"comment even thread-even depth-1 parent\" id=\"comment-34\"&gt;\n &lt;div id=\"div-comment-34\" class=\"comment-body\"&gt;\n ... cut...\n</code></pre>\n\n<p>One could e.g. search for both cases, but it's possible for the user to override these with a custom output. </p>\n\n<p>Also note the <code>depth</code> information here.</p></li>\n<li><p>One could try to parse the <code>onclick</code> attribute of the <em>replyto</em> link:</p>\n\n<pre><code>onclick='return addComment.moveForm( \"div-comment-34\", \"34\", \"respond\", \"123\" )'\n</code></pre></li>\n</ul>\n" }, { "answer_id": 233614, "author": "woodduck", "author_id": 98026, "author_profile": "https://wordpress.stackexchange.com/users/98026", "pm_score": 1, "selected": false, "text": "<p>This is my implementation of <a href=\"https://wordpress.stackexchange.com/users/26350/birgire\">birgire</a>'s last suggestion (to parse the onclick):</p>\n\n<pre><code>jQuery(document).on( 'click', 'a.comment-reply-link', function( event ) {\n\n// THIS PART GETS THE COMMENT ID\nvar hayStack = jQuery(this).attr('onclick');\nvar strawA = '\"div-comment-';\nvar strawB = '\"';\nvar tipNeedle = hayStack.lastIndexOf(strawA)+strawA.length;\nvar hayTruss = hayStack.substring(tipNeedle);\nvar endNeedle = hayTruss.indexOf(strawB); \nvar needle = hayTruss.substring(0, endNeedle);\nalert(needle);\n\n// optional: THIS PART LOOKS UP THE PARENT ID (php side not shown)\nvar datatopost = {\n action: 'my_ajax_hook',\n nonce: ajaxobject.nonce,\n selected_comment_id: needle,\n };\njQuery.ajax({\n type: 'post',\n dataType: 'json',\n url: ajaxobject.ajaxurl,\n data: datatopost,\n error: function() { // Ajax request has failed\n jQuery('#comment').val('An error has occurred');\n },\n success: function (response) { // Ajax request has succeeded\n if (response.success) {\n // JSON successfully received\n alert(response.data.selected_comment_parent);\n }\n }\n}); \n});\n</code></pre>\n" } ]
2016/07/28
[ "https://wordpress.stackexchange.com/questions/233515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98026/" ]
I think I might be able to parse the URL for the `replytocom` parameter and get the comment ID from that. However, it would mean that my plugin would not be fully compatible with other plugins that can remove this parameter (most notably *Yoast SEO*). Plus, it feels a bit hacky. Is there another way? Endgoal: I need that comment ID to use in an AJAX request - to fetch data (such as the comment thread depth) so that I can display custom data in the front end.
Here are few ideas: * It's possible to inject custom HTML or data attributes via the [`comment_reply_link`](https://developer.wordpress.org/reference/functions/comment_reply_link/) filter, but I think it would be better to keep it unobtrusive. * One could try to get the comment parent value from the reply comment form: ``` <input type='hidden' name='comment_parent' id='comment_parent' value='0' /> ``` after it has been updated with the corresponding value. * Another approach would be to scan for IDs in the HTML of the comments list: Generated by the `Walker_Comment::html5_comment()`: ``` <li id="comment-34" class="comment even thread-even depth-1"> <article id="div-comment-34" class="comment-body"> ... cut... ``` Generated by the `Walker_Comment::comment()`: ``` <li class="comment even thread-even depth-1 parent" id="comment-34"> <div id="div-comment-34" class="comment-body"> ... cut... ``` One could e.g. search for both cases, but it's possible for the user to override these with a custom output. Also note the `depth` information here. * One could try to parse the `onclick` attribute of the *replyto* link: ``` onclick='return addComment.moveForm( "div-comment-34", "34", "respond", "123" )' ```
233,526
<p>I have a problem understanding the behavior of the Attachment Page Permalinks Into Setting-->Permalinks I have set <a href="http://www.example.com/sample-post/" rel="nofollow">http://www.example.com/sample-post/</a> as the preferred setting.</p> <p>When I upload an image a permalink for the Attachment Page is automatically created. Example:</p> <ul> <li>I'm into Service (a page) and I upload landscape.jpg to the media gallery.</li> <li>The permalink <a href="http://www.example.com/services/landscape/" rel="nofollow">http://www.example.com/services/landscape/</a> is automatically created</li> <li>If I want to create a page at named landscape with services as parent I can't</li> <li>When i create the page Landscape wordpress rename it <strong><em>example.com/services/landscape-2/</em></strong></li> </ul> <p>Is there a way to modify the way WordPress handles the permalinks of Attachment Pages that are automatically created when we upload the images to the media gallery?</p> <ul> <li>Can we modify all the Attachment Page having into the permalink something like <strong><em>/img-upload/</em></strong> so wordpress will not get confused ?</li> <li>Is it possiible to revert to the old style permalink handling just for the attachment pages? Before with the permalink of the attachment page having this kind of url <strong><em>example.com/?attachment_id=37</em></strong> we had no this problem.. and for the seo we were just redirecting all the attachment page url to the page that was containing the image; solving in this way the duplicated content issue that was giving the creation of a page with Title description and image...</li> </ul> <p>Thanks in advance!</p>
[ { "answer_id": 233537, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 0, "selected": false, "text": "<p>The \"attachment page\" is just a post type, like \"page\" or \"post\" are.</p>\n\n<p>The slug in the URL for each post must be unique, shared slug is only permitted accross different post types (<a href=\"https://core.trac.wordpress.org/ticket/18962\" rel=\"nofollow\">since WordPress 4.1</a>), but with some limitations.</p>\n\n<p>One obvious limitation is that same slug <strong>can not be allowed</strong> for posts which have the same post parent. If the post parent is the same, the URL path will be the same and the post slug will be in the same level in that path, which is obviously a problem: same path and slug would result in the same URL for the two different contents. That is why WordPress adds <code>-2</code> to one of the them and fix this issue.</p>\n\n<p>The situation described above is what is happening to you. You are trying to create two posts of different post types that share post parent and URL path.</p>\n\n<p>Even you use a different URL structure for pages and attachments, WordPress won't allow same slug in both if they share the same parent post.</p>\n\n<p>So the best solution is to give each post, attachment and page, different names and slugs. URL manipulation is quite more complicated and won't give you the desired SEO benefits you think it will give you.</p>\n\n<p><strong>That is my opinion</strong> from a SEO perspective. Using different slugs, for example <code>example.com/services/landscape-photo/</code> for attachement page, won't hurt your SEO at all.</p>\n\n<p>In the other hand, redirecting the attachment page, as you are doing, may actually hurt your SEO. I assume you are doing it with 3xx status code which means \"Content moved for xx reason\". For example, 301 code means \"Content moved permanently to a new location\".</p>\n\n<p>If you use 3xx status code to redirect attachment page to parent page, you are doing it wrong. Simply because <strong>you have not moved the content</strong>, the content of the URL where you are redirecting to is not the same content of the URL where you are redirecting from, so <strong>there is not duplicated content</strong> and there is not moved content. That is why the redirection is incorrect from a SEO perspective.</p>\n\n<p>If you don't want attachement pages being indexed by search engines, I would use robots meta tag with <code>noindex</code> value. Other methods can be used to avoid attachment be indexed and avoid fake redirections, it depends on the exact situation.</p>\n" }, { "answer_id": 254086, "author": "leendertvb", "author_id": 27308, "author_profile": "https://wordpress.stackexchange.com/users/27308", "pm_score": 2, "selected": false, "text": "<p>To provide an answer to your first question and for future reference to tackle the problem you described with the slug already being in use when you first uploaded an attachment to the same parent. The following code will get rid of this 'annoying' thing <em>(annoying in some use cases)</em>.</p>\n\n<p>This code rewrites the slug of the attachment upon uploading to add a prefix (or suffix) to the slug. In that case you have less chance of getting in the way of page slugs in the future.</p>\n\n<pre><code>add_action('add_attachment', function($postId) {\n // get the attachment post object\n $attachment = get_post($postId);\n // get the slug for the attachment\n $slug = $attachment-&gt;post_name;\n // update the post data of the attachment with an edited slug\n wp_update_post(array(\n 'ID' =&gt; $postId,\n 'post_name' =&gt; 'media-'.$slug, //adds a prefix\n //'post_name' =&gt; $slug.'-photo', //adds a suffix\n ));\n});\n</code></pre>\n\n<p>I hope this will help anyone.</p>\n" } ]
2016/07/29
[ "https://wordpress.stackexchange.com/questions/233526", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99157/" ]
I have a problem understanding the behavior of the Attachment Page Permalinks Into Setting-->Permalinks I have set <http://www.example.com/sample-post/> as the preferred setting. When I upload an image a permalink for the Attachment Page is automatically created. Example: * I'm into Service (a page) and I upload landscape.jpg to the media gallery. * The permalink <http://www.example.com/services/landscape/> is automatically created * If I want to create a page at named landscape with services as parent I can't * When i create the page Landscape wordpress rename it ***example.com/services/landscape-2/*** Is there a way to modify the way WordPress handles the permalinks of Attachment Pages that are automatically created when we upload the images to the media gallery? * Can we modify all the Attachment Page having into the permalink something like ***/img-upload/*** so wordpress will not get confused ? * Is it possiible to revert to the old style permalink handling just for the attachment pages? Before with the permalink of the attachment page having this kind of url ***example.com/?attachment\_id=37*** we had no this problem.. and for the seo we were just redirecting all the attachment page url to the page that was containing the image; solving in this way the duplicated content issue that was giving the creation of a page with Title description and image... Thanks in advance!
To provide an answer to your first question and for future reference to tackle the problem you described with the slug already being in use when you first uploaded an attachment to the same parent. The following code will get rid of this 'annoying' thing *(annoying in some use cases)*. This code rewrites the slug of the attachment upon uploading to add a prefix (or suffix) to the slug. In that case you have less chance of getting in the way of page slugs in the future. ``` add_action('add_attachment', function($postId) { // get the attachment post object $attachment = get_post($postId); // get the slug for the attachment $slug = $attachment->post_name; // update the post data of the attachment with an edited slug wp_update_post(array( 'ID' => $postId, 'post_name' => 'media-'.$slug, //adds a prefix //'post_name' => $slug.'-photo', //adds a suffix )); }); ``` I hope this will help anyone.
233,533
<p>I have tried searching, and tried a few options, but I'm not able to remove the H1 / title / Underscore for specific pages.</p> <p>I don't want use CSS. I would like to remove it via <code>functions.php</code> or in <code>content.php</code>.</p> <p>I'm not good in PHP, so the Codex didn't help me too much.</p> <p>I need something like this:</p> <pre><code>if &gt; page slugs / IDs &gt; do not display H1/ title </code></pre> <p>Can anybody help? Thanks.</p>
[ { "answer_id": 233534, "author": "Devender Narwal", "author_id": 99170, "author_profile": "https://wordpress.stackexchange.com/users/99170", "pm_score": 0, "selected": false, "text": "<p>WordPress has the predefined function <code>is_page()</code>, which looks like this:</p>\n\n<pre><code>is_page( int|string|array $page = '' )\n</code></pre>\n\n<p>If the <code>$page</code> parameter is specified, this function will additionally check if the query is for one of the pages specified.</p>\n\n<p>It returns <code>true</code> or <code>false</code>, depending on whether the query is for an existing single page.</p>\n\n<p>You can find more details <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow\">in the documentation</a>.</p>\n" }, { "answer_id": 233570, "author": "Rob Sterling", "author_id": 90807, "author_profile": "https://wordpress.stackexchange.com/users/90807", "pm_score": 2, "selected": true, "text": "<p>The way I would do this is to create a separate page template that lacks the H1 code, and then manually select that template (in the Page Attributes box on the page editor screen) for each desired page. </p>\n" } ]
2016/07/29
[ "https://wordpress.stackexchange.com/questions/233533", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86748/" ]
I have tried searching, and tried a few options, but I'm not able to remove the H1 / title / Underscore for specific pages. I don't want use CSS. I would like to remove it via `functions.php` or in `content.php`. I'm not good in PHP, so the Codex didn't help me too much. I need something like this: ``` if > page slugs / IDs > do not display H1/ title ``` Can anybody help? Thanks.
The way I would do this is to create a separate page template that lacks the H1 code, and then manually select that template (in the Page Attributes box on the page editor screen) for each desired page.
233,535
<p>I am creating a Super Admin role in wordpress Roles.</p> <pre><code>$capabilities=array(); add_role('Administrator', 'Administrator', $capabilities ); add_role('Super Admin', 'Super Admin', $capabilities) ); </code></pre> <p>So while adding a new user I got the Role Option Super Admin. So I added a Super User .</p> <p>Now When I login to wp-admin It gives me error saying:</p> <blockquote> <p>you do not have sufficient permissions to access this page.</p> </blockquote> <p>What more I have to do to make it work. I dont want to use any pluggin.</p> <p>I tried this too</p> <pre><code>add_role('Super Admin', 'Super Admin', array("manage_network","manage_sites","manage_network_users", "manage_network_plugins","manage_network_themes","manage_network_options", "read") ); </code></pre> <p>and </p> <pre><code> add_role('Super Admin', 'Super Admin', array("manage_network"=&gt;true,"manage_sites"=&gt;true, "manage_network_users"=&gt;true,"manage_network_plugins"=&gt;true, "manage_network_themes"=&gt;true,"manage_network_options"=&gt;true,"read"=&gt;true) ); </code></pre> <p>I want this user to access all stuff in wp-admin panel</p>
[ { "answer_id": 233534, "author": "Devender Narwal", "author_id": 99170, "author_profile": "https://wordpress.stackexchange.com/users/99170", "pm_score": 0, "selected": false, "text": "<p>WordPress has the predefined function <code>is_page()</code>, which looks like this:</p>\n\n<pre><code>is_page( int|string|array $page = '' )\n</code></pre>\n\n<p>If the <code>$page</code> parameter is specified, this function will additionally check if the query is for one of the pages specified.</p>\n\n<p>It returns <code>true</code> or <code>false</code>, depending on whether the query is for an existing single page.</p>\n\n<p>You can find more details <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow\">in the documentation</a>.</p>\n" }, { "answer_id": 233570, "author": "Rob Sterling", "author_id": 90807, "author_profile": "https://wordpress.stackexchange.com/users/90807", "pm_score": 2, "selected": true, "text": "<p>The way I would do this is to create a separate page template that lacks the H1 code, and then manually select that template (in the Page Attributes box on the page editor screen) for each desired page. </p>\n" } ]
2016/07/29
[ "https://wordpress.stackexchange.com/questions/233535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86281/" ]
I am creating a Super Admin role in wordpress Roles. ``` $capabilities=array(); add_role('Administrator', 'Administrator', $capabilities ); add_role('Super Admin', 'Super Admin', $capabilities) ); ``` So while adding a new user I got the Role Option Super Admin. So I added a Super User . Now When I login to wp-admin It gives me error saying: > > you do not have sufficient permissions to access this page. > > > What more I have to do to make it work. I dont want to use any pluggin. I tried this too ``` add_role('Super Admin', 'Super Admin', array("manage_network","manage_sites","manage_network_users", "manage_network_plugins","manage_network_themes","manage_network_options", "read") ); ``` and ``` add_role('Super Admin', 'Super Admin', array("manage_network"=>true,"manage_sites"=>true, "manage_network_users"=>true,"manage_network_plugins"=>true, "manage_network_themes"=>true,"manage_network_options"=>true,"read"=>true) ); ``` I want this user to access all stuff in wp-admin panel
The way I would do this is to create a separate page template that lacks the H1 code, and then manually select that template (in the Page Attributes box on the page editor screen) for each desired page.
233,543
<p>I know that I can use the following function to remove the version from all <code>.css</code> and <code>.js</code> files:</p> <pre><code>add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999 ); add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999 ); function sdt_remove_ver_css_js( $src ) { if ( strpos( $src, 'ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; } </code></pre> <p>But I have some files, for instance <code>style.css</code>, in the case of which I want to add a version in the following way:</p> <pre><code>function css_versioning() { wp_enqueue_style( 'style', get_stylesheet_directory_uri() . '/style.css' , false, filemtime( get_stylesheet_directory() . '/style.css' ), 'all' ); } </code></pre> <p>But the previous function removes also this version. So the question is how to make the two work together?</p>
[ { "answer_id": 233548, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>You can check for the current <em>handle</em> before removing the version. </p>\n\n<p>Here's an example (untested):</p>\n\n<pre><code>add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999, 2 );\nadd_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999, 2 );\n\nfunction sdt_remove_ver_css_js( $src, $handle ) \n{\n $handles_with_version = [ 'style' ]; // &lt;-- Adjust to your needs!\n\n if ( strpos( $src, 'ver=' ) &amp;&amp; ! in_array( $handle, $handles_with_version, true ) )\n $src = remove_query_arg( 'ver', $src );\n\n return $src;\n}\n</code></pre>\n" }, { "answer_id": 323926, "author": "Amr", "author_id": 131332, "author_profile": "https://wordpress.stackexchange.com/users/131332", "pm_score": 3, "selected": false, "text": "<p>Since this question was written, a lot has changed with WordPress. Here is a new way to prevent WordPress from displaying its version number:</p>\n\n<pre><code>// remove version from head\nremove_action('wp_head', 'wp_generator');\n\n// remove version from rss\nadd_filter('the_generator', '__return_empty_string');\n\n// remove version from scripts and styles\nfunction remove_version_scripts_styles($src) {\n if (strpos($src, 'ver=')) {\n $src = remove_query_arg('ver', $src);\n }\n return $src;\n}\nadd_filter('style_loader_src', 'remove_version_scripts_styles', 9999);\nadd_filter('script_loader_src', 'remove_version_scripts_styles', 9999);\n</code></pre>\n\n<p>No editing required. Add to functions.php and done. Or add via simple custom plugin. The choice is yours! :)</p>\n\n<p><a href=\"https://digwp.com/2009/07/remove-wordpress-version-number/\" rel=\"nofollow noreferrer\">Original article</a></p>\n" }, { "answer_id": 373143, "author": "Haveigonemental", "author_id": 193236, "author_profile": "https://wordpress.stackexchange.com/users/193236", "pm_score": 1, "selected": false, "text": "<p>To target a specific file</p>\n<pre><code>// remove version from scripts and styles\nfunction remove_version_scripts_styles($src) {\n if (strpos($src, 'yourfile.js')) {\n $src = remove_query_arg('ver', $src);\n }\n return $src;\n}\nadd_filter('script_loader_src', 'remove_version_scripts_styles', 9999);\n</code></pre>\n" } ]
2016/07/29
[ "https://wordpress.stackexchange.com/questions/233543", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70882/" ]
I know that I can use the following function to remove the version from all `.css` and `.js` files: ``` add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999 ); add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999 ); function sdt_remove_ver_css_js( $src ) { if ( strpos( $src, 'ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; } ``` But I have some files, for instance `style.css`, in the case of which I want to add a version in the following way: ``` function css_versioning() { wp_enqueue_style( 'style', get_stylesheet_directory_uri() . '/style.css' , false, filemtime( get_stylesheet_directory() . '/style.css' ), 'all' ); } ``` But the previous function removes also this version. So the question is how to make the two work together?
You can check for the current *handle* before removing the version. Here's an example (untested): ``` add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999, 2 ); add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999, 2 ); function sdt_remove_ver_css_js( $src, $handle ) { $handles_with_version = [ 'style' ]; // <-- Adjust to your needs! if ( strpos( $src, 'ver=' ) && ! in_array( $handle, $handles_with_version, true ) ) $src = remove_query_arg( 'ver', $src ); return $src; } ```
233,559
<p>I'm using a function in a custom theme which auto-populates the navigation with all the child pages of each parent. I found the code on <a href="https://wordpress.stackexchange.com/questions/100841/add-child-pages-automatically-to-nav-menu">this site</a></p> <p>This works well but the only thing this function doesn't do for me is order the pages with the order set in the Pages section in Wordpress. I think I need to use something like 'sort_column=menu_order&amp;title_li=&amp;child_of=' somewhere in the following code, but can't for the life of me work out where?</p> <pre><code>/** * auto_child_page_menu * * class to add top level page menu items all child pages on the fly * @author Ohad Raz &lt;[email protected]&gt; */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz &lt;[email protected]&gt; * @param array $args * @return void */ function __construct($args = array()){ add_filter('wp_nav_menu_objects',array($this,'on_the_fly')); } /** * the magic function that adds the child pages * @author Ohad Raz &lt;[email protected]&gt; * @param array $items * @return array */ function on_the_fly($items) { global $post; $tmp = array(); foreach ($items as $key =&gt; $i) { $tmp[] = $i; //if not page move on if ($i-&gt;object != 'page'){ continue; } $page = get_post($i-&gt;object_id); //if not parent page move on if (!isset($page-&gt;post_parent) || $page-&gt;post_parent != 0) { continue; } $children = get_pages( array('child_of' =&gt; $i-&gt;object_id) ); foreach ((array)$children as $c) { //set parent menu $c-&gt;menu_item_parent = $i-&gt;ID; $c-&gt;object_id = $c-&gt;ID; $c-&gt;object = 'page'; $c-&gt;type = 'post_type'; $c-&gt;type_label = 'Page'; $c-&gt;url = get_permalink( $c-&gt;ID); $c-&gt;title = $c-&gt;post_title; $c-&gt;target = ''; $c-&gt;attr_title = ''; $c-&gt;description = ''; $c-&gt;classes = array('','menu-item','menu-item-type-post_type','menu-item-object-page'); $c-&gt;xfn = ''; $c-&gt;current = ($post-&gt;ID == $c-&gt;ID)? true: false; $c-&gt;current_item_ancestor = ($post-&gt;ID == $c-&gt;post_parent)? true: false; //probbably not right $c-&gt;current_item_parent = ($post-&gt;ID == $c-&gt;post_parent)? true: false; $tmp[] = $c; } } return $tmp; } } new auto_child_page_menu(); </code></pre>
[ { "answer_id": 233561, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p><code>$items</code> which are passed to this function are already sorted (see <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/nav-menu-template.php#L379\" rel=\"nofollow\">here</a>). So you have to order them once again, by yourself, before <code>return $tmp;</code></p>\n" }, { "answer_id": 235284, "author": "Acevandermeer", "author_id": 99182, "author_profile": "https://wordpress.stackexchange.com/users/99182", "pm_score": 2, "selected": true, "text": "<p>I eventually found the fix for anyone who has the same issue:</p>\n\n<pre><code> /**\n * auto_child_page_menu\n * \n * class to add top level page menu items all child pages on the fly\n * @author Ohad Raz &lt;[email protected]&gt;\n */\n class auto_child_page_menu\n {\n /**\n * class constructor\n * @author Ohad Raz &lt;[email protected]&gt;\n * @param array $args \n * @return void\n */\n function __construct($args = array()){\n add_filter('wp_nav_menu_objects',array($this,'on_the_fly'));\n }\n /**\n * the magic function that adds the child pages\n * @author Ohad Raz &lt;[email protected]&gt;\n * @param array $items \n * @return array \n */\n function on_the_fly($items) {\n global $post;\n $tmp = array();\n foreach ($items as $key =&gt; $i) {\n $tmp[] = $i;\n //if not page move on\n if ($i-&gt;object != 'page'){\n continue;\n }\n $page = get_post($i-&gt;object_id);\n //if not parent page move on\n if (!isset($page-&gt;post_parent) || $page-&gt;post_parent != 0) {\n continue;\n }\n $children = get_pages( array('child_of' =&gt; $i-&gt;object_id, 'sort_column' =&gt; 'menu_order') );\n foreach ((array)$children as $c) {\n //set parent menu \n $c-&gt;menu_item_parent = $i-&gt;ID;\n $c-&gt;object_id = $c-&gt;ID;\n $c-&gt;object = 'page';\n $c-&gt;type = 'post_type';\n $c-&gt;type_label = 'Page';\n $c-&gt;url = get_permalink( $c-&gt;ID);\n $c-&gt;title = $c-&gt;post_title;\n $c-&gt;target = '';\n $c-&gt;attr_title = '';\n $c-&gt;description = '';\n $c-&gt;classes = array('','menu-item','menu-item-type-post_type','menu-item-object-page');\n $c-&gt;xfn = '';\n $c-&gt;current = ($post-&gt;ID == $c-&gt;ID)? true: false;\n $c-&gt;current_item_ancestor = ($post-&gt;ID == $c-&gt;post_parent)? true: false; //probbably not right\n $c-&gt;current_item_parent = ($post-&gt;ID == $c-&gt;post_parent)? true: false;\n $tmp[] = $c;\n }\n\n }\n return $tmp;\n }\n }\n new auto_child_page_menu();\n</code></pre>\n" } ]
2016/07/29
[ "https://wordpress.stackexchange.com/questions/233559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99182/" ]
I'm using a function in a custom theme which auto-populates the navigation with all the child pages of each parent. I found the code on [this site](https://wordpress.stackexchange.com/questions/100841/add-child-pages-automatically-to-nav-menu) This works well but the only thing this function doesn't do for me is order the pages with the order set in the Pages section in Wordpress. I think I need to use something like 'sort\_column=menu\_order&title\_li=&child\_of=' somewhere in the following code, but can't for the life of me work out where? ``` /** * auto_child_page_menu * * class to add top level page menu items all child pages on the fly * @author Ohad Raz <[email protected]> */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz <[email protected]> * @param array $args * @return void */ function __construct($args = array()){ add_filter('wp_nav_menu_objects',array($this,'on_the_fly')); } /** * the magic function that adds the child pages * @author Ohad Raz <[email protected]> * @param array $items * @return array */ function on_the_fly($items) { global $post; $tmp = array(); foreach ($items as $key => $i) { $tmp[] = $i; //if not page move on if ($i->object != 'page'){ continue; } $page = get_post($i->object_id); //if not parent page move on if (!isset($page->post_parent) || $page->post_parent != 0) { continue; } $children = get_pages( array('child_of' => $i->object_id) ); foreach ((array)$children as $c) { //set parent menu $c->menu_item_parent = $i->ID; $c->object_id = $c->ID; $c->object = 'page'; $c->type = 'post_type'; $c->type_label = 'Page'; $c->url = get_permalink( $c->ID); $c->title = $c->post_title; $c->target = ''; $c->attr_title = ''; $c->description = ''; $c->classes = array('','menu-item','menu-item-type-post_type','menu-item-object-page'); $c->xfn = ''; $c->current = ($post->ID == $c->ID)? true: false; $c->current_item_ancestor = ($post->ID == $c->post_parent)? true: false; //probbably not right $c->current_item_parent = ($post->ID == $c->post_parent)? true: false; $tmp[] = $c; } } return $tmp; } } new auto_child_page_menu(); ```
I eventually found the fix for anyone who has the same issue: ``` /** * auto_child_page_menu * * class to add top level page menu items all child pages on the fly * @author Ohad Raz <[email protected]> */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz <[email protected]> * @param array $args * @return void */ function __construct($args = array()){ add_filter('wp_nav_menu_objects',array($this,'on_the_fly')); } /** * the magic function that adds the child pages * @author Ohad Raz <[email protected]> * @param array $items * @return array */ function on_the_fly($items) { global $post; $tmp = array(); foreach ($items as $key => $i) { $tmp[] = $i; //if not page move on if ($i->object != 'page'){ continue; } $page = get_post($i->object_id); //if not parent page move on if (!isset($page->post_parent) || $page->post_parent != 0) { continue; } $children = get_pages( array('child_of' => $i->object_id, 'sort_column' => 'menu_order') ); foreach ((array)$children as $c) { //set parent menu $c->menu_item_parent = $i->ID; $c->object_id = $c->ID; $c->object = 'page'; $c->type = 'post_type'; $c->type_label = 'Page'; $c->url = get_permalink( $c->ID); $c->title = $c->post_title; $c->target = ''; $c->attr_title = ''; $c->description = ''; $c->classes = array('','menu-item','menu-item-type-post_type','menu-item-object-page'); $c->xfn = ''; $c->current = ($post->ID == $c->ID)? true: false; $c->current_item_ancestor = ($post->ID == $c->post_parent)? true: false; //probbably not right $c->current_item_parent = ($post->ID == $c->post_parent)? true: false; $tmp[] = $c; } } return $tmp; } } new auto_child_page_menu(); ```
233,562
<p>By seeing the wordpress core I understand that plugin.php is being loaded way before plugins are loaded. But yet some plugins are loading it again. Any advantage of reloading the plugin.php? </p> <p>And does'nt PHP through errors for including the same file with function definitions?</p>
[ { "answer_id": 233561, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p><code>$items</code> which are passed to this function are already sorted (see <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/nav-menu-template.php#L379\" rel=\"nofollow\">here</a>). So you have to order them once again, by yourself, before <code>return $tmp;</code></p>\n" }, { "answer_id": 235284, "author": "Acevandermeer", "author_id": 99182, "author_profile": "https://wordpress.stackexchange.com/users/99182", "pm_score": 2, "selected": true, "text": "<p>I eventually found the fix for anyone who has the same issue:</p>\n\n<pre><code> /**\n * auto_child_page_menu\n * \n * class to add top level page menu items all child pages on the fly\n * @author Ohad Raz &lt;[email protected]&gt;\n */\n class auto_child_page_menu\n {\n /**\n * class constructor\n * @author Ohad Raz &lt;[email protected]&gt;\n * @param array $args \n * @return void\n */\n function __construct($args = array()){\n add_filter('wp_nav_menu_objects',array($this,'on_the_fly'));\n }\n /**\n * the magic function that adds the child pages\n * @author Ohad Raz &lt;[email protected]&gt;\n * @param array $items \n * @return array \n */\n function on_the_fly($items) {\n global $post;\n $tmp = array();\n foreach ($items as $key =&gt; $i) {\n $tmp[] = $i;\n //if not page move on\n if ($i-&gt;object != 'page'){\n continue;\n }\n $page = get_post($i-&gt;object_id);\n //if not parent page move on\n if (!isset($page-&gt;post_parent) || $page-&gt;post_parent != 0) {\n continue;\n }\n $children = get_pages( array('child_of' =&gt; $i-&gt;object_id, 'sort_column' =&gt; 'menu_order') );\n foreach ((array)$children as $c) {\n //set parent menu \n $c-&gt;menu_item_parent = $i-&gt;ID;\n $c-&gt;object_id = $c-&gt;ID;\n $c-&gt;object = 'page';\n $c-&gt;type = 'post_type';\n $c-&gt;type_label = 'Page';\n $c-&gt;url = get_permalink( $c-&gt;ID);\n $c-&gt;title = $c-&gt;post_title;\n $c-&gt;target = '';\n $c-&gt;attr_title = '';\n $c-&gt;description = '';\n $c-&gt;classes = array('','menu-item','menu-item-type-post_type','menu-item-object-page');\n $c-&gt;xfn = '';\n $c-&gt;current = ($post-&gt;ID == $c-&gt;ID)? true: false;\n $c-&gt;current_item_ancestor = ($post-&gt;ID == $c-&gt;post_parent)? true: false; //probbably not right\n $c-&gt;current_item_parent = ($post-&gt;ID == $c-&gt;post_parent)? true: false;\n $tmp[] = $c;\n }\n\n }\n return $tmp;\n }\n }\n new auto_child_page_menu();\n</code></pre>\n" } ]
2016/07/29
[ "https://wordpress.stackexchange.com/questions/233562", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64811/" ]
By seeing the wordpress core I understand that plugin.php is being loaded way before plugins are loaded. But yet some plugins are loading it again. Any advantage of reloading the plugin.php? And does'nt PHP through errors for including the same file with function definitions?
I eventually found the fix for anyone who has the same issue: ``` /** * auto_child_page_menu * * class to add top level page menu items all child pages on the fly * @author Ohad Raz <[email protected]> */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz <[email protected]> * @param array $args * @return void */ function __construct($args = array()){ add_filter('wp_nav_menu_objects',array($this,'on_the_fly')); } /** * the magic function that adds the child pages * @author Ohad Raz <[email protected]> * @param array $items * @return array */ function on_the_fly($items) { global $post; $tmp = array(); foreach ($items as $key => $i) { $tmp[] = $i; //if not page move on if ($i->object != 'page'){ continue; } $page = get_post($i->object_id); //if not parent page move on if (!isset($page->post_parent) || $page->post_parent != 0) { continue; } $children = get_pages( array('child_of' => $i->object_id, 'sort_column' => 'menu_order') ); foreach ((array)$children as $c) { //set parent menu $c->menu_item_parent = $i->ID; $c->object_id = $c->ID; $c->object = 'page'; $c->type = 'post_type'; $c->type_label = 'Page'; $c->url = get_permalink( $c->ID); $c->title = $c->post_title; $c->target = ''; $c->attr_title = ''; $c->description = ''; $c->classes = array('','menu-item','menu-item-type-post_type','menu-item-object-page'); $c->xfn = ''; $c->current = ($post->ID == $c->ID)? true: false; $c->current_item_ancestor = ($post->ID == $c->post_parent)? true: false; //probbably not right $c->current_item_parent = ($post->ID == $c->post_parent)? true: false; $tmp[] = $c; } } return $tmp; } } new auto_child_page_menu(); ```
233,565
<p>I'm not an expert in PHP but would like to customize the pagination of my posts.</p> <p>Instead of having : prev 1, 2, 3, 4, next</p> <p>I would like : Prev 1 of 4 Next</p> <p>It seems I have to modify my single.php file and these lines : </p> <pre><code>&lt;?php wp_link_pages(array('before' =&gt; '&lt;div class="pagination"&gt;', 'after' =&gt; '&lt;/div&gt;', 'link_before' =&gt; '&lt;span class="current"&gt;&lt;span class="currenttext"&gt;', 'link_after' =&gt; '&lt;/span&gt;&lt;/span&gt;', 'next_or_number' =&gt; 'next_and_number', 'nextpagelink' =&gt; __('Next', 'sociallyviral' ), 'previouspagelink' =&gt; __('Previous', 'sociallyviral' ), 'pagelink' =&gt; '%','echo' =&gt; 1 )); ?&gt; </code></pre> <p>If you already have made this customization could you help me ?</p> <p>Thank you very much</p>
[ { "answer_id": 233571, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You could try combining these:</p>\n\n<h2>Buttons</h2>\n\n<pre><code>next_posts_link( 'Prev' );\nprevious_posts_link( 'Next' ); \n</code></pre>\n\n<h2>Current page</h2>\n\n<pre><code>echo (get_query_var('paged')) ? get_query_var('paged') : 1;\n</code></pre>\n\n<h2>Total pages</h2>\n\n<pre><code>wp_count_posts();\n</code></pre>\n\n<h2>In HTML</h2>\n\n<pre><code>&lt;?php next_posts_link( 'Prev' ); ?&gt;\n&lt;?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?&gt;\n&lt;span&gt; of &lt;/span&gt;\n&lt;?php echo wp_count_posts(); ?&gt;\n&lt;?php next_posts_link( 'Prev' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 233577, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>If we set the content pagination type to <code>next</code> with:</p>\n\n<pre><code>add_filter( 'wp_link_pages_args', function( Array $args )\n{\n $args['next_or_number'] = 'next';\n return $args;\n} );\n</code></pre>\n\n<p>then we can inject the <code>x of y</code> part between the <em>Previous page</em> and <em>Next page</em> links with:</p>\n\n<pre><code>add_filter( 'wp_link_pages_link', function( $link, $nextorprev ) use ( &amp;$page, &amp;$numpages )\n{\n if( $nextorprev &lt;= $page || 1 === $page )\n $link .= sprintf( ' %d %s %d ', $page, esc_html__( 'of', 'mydomain' ), $numpages );\n\n return $link;\n}, 10, 2 );\n</code></pre>\n\n<p>Then the output of <code>wp_link_pages()</code> would be like:</p>\n\n<pre><code>Pages: Previous page 5 of 6 Next page\n</code></pre>\n" } ]
2016/07/29
[ "https://wordpress.stackexchange.com/questions/233565", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99193/" ]
I'm not an expert in PHP but would like to customize the pagination of my posts. Instead of having : prev 1, 2, 3, 4, next I would like : Prev 1 of 4 Next It seems I have to modify my single.php file and these lines : ``` <?php wp_link_pages(array('before' => '<div class="pagination">', 'after' => '</div>', 'link_before' => '<span class="current"><span class="currenttext">', 'link_after' => '</span></span>', 'next_or_number' => 'next_and_number', 'nextpagelink' => __('Next', 'sociallyviral' ), 'previouspagelink' => __('Previous', 'sociallyviral' ), 'pagelink' => '%','echo' => 1 )); ?> ``` If you already have made this customization could you help me ? Thank you very much
You could try combining these: Buttons ------- ``` next_posts_link( 'Prev' ); previous_posts_link( 'Next' ); ``` Current page ------------ ``` echo (get_query_var('paged')) ? get_query_var('paged') : 1; ``` Total pages ----------- ``` wp_count_posts(); ``` In HTML ------- ``` <?php next_posts_link( 'Prev' ); ?> <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?> <span> of </span> <?php echo wp_count_posts(); ?> <?php next_posts_link( 'Prev' ); ?> ```
233,598
<p>I'm not familiar with working outside the loop so forgive me if this question has been asked already. </p> <p>How do I get a featured image of a post that's outside the loop? I did a <code>print_r</code> and I didn't see anything related to a featured image.</p> <p>Any ideas on what to do next?</p> <p><strong>Update:</strong> I was able to get it working but I need a way to show every image size associated with the post's featured image.</p> <p>This is what I've done so far:</p> <pre><code>// the query. Only show posts with a certain taxonomy &lt;?php $args = array('tax_query' =&gt; array(array('taxonomy' =&gt; 'post-status','field' =&gt; 'slug','terms' =&gt; array ('post-status-published')))); $query = new WP_Query( $args );?&gt; &lt;?php if ( $query-&gt;have_posts() ) : $major = false; $major_first = false; $duplicates = []; while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; //check if any post belongs to a certain category &lt;?php if ( in_category( 'major' ) ) : ?&gt; &lt;?php $major = true;?&gt; &lt;?php $major_data [] = get_post($post-&gt;ID) ;?&gt; &lt;?php endif; ?&gt; &lt;?php if ( in_category( 'major-first' ) ) : ?&gt; &lt;?php $major_first = true;?&gt; &lt;?php $major_first_data [] = get_post($post-&gt;ID) ;?&gt; &lt;?php $image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ),'large' ); $image = $image_array; ?&gt; &lt;?php endif; ?&gt; // end of the loop &lt;?php endwhile; endif; ?&gt; // show content &lt;?php if ($major == true):?&gt; &lt;?php if ($major == true):?&gt; &lt;?php foreach($major_first_data as $postID) { ;?&gt; &lt;?php $postData = get_post( $postID );?&gt; &lt;?php print $postData-&gt;post_title;?&gt;&lt;br&gt; &lt;?php echo $image[0]; ?&gt; &lt;?php } ?&gt; &lt;?php endif;?&gt; &lt;?php foreach($major_data as $postID) { ;?&gt; &lt;?php $postData = get_post( $postID );?&gt; &lt;?php print $postData-&gt;post_title;?&gt;&lt;br&gt; &lt;?php } ?&gt; &lt;?php endif;?&gt; </code></pre>
[ { "answer_id": 233571, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You could try combining these:</p>\n\n<h2>Buttons</h2>\n\n<pre><code>next_posts_link( 'Prev' );\nprevious_posts_link( 'Next' ); \n</code></pre>\n\n<h2>Current page</h2>\n\n<pre><code>echo (get_query_var('paged')) ? get_query_var('paged') : 1;\n</code></pre>\n\n<h2>Total pages</h2>\n\n<pre><code>wp_count_posts();\n</code></pre>\n\n<h2>In HTML</h2>\n\n<pre><code>&lt;?php next_posts_link( 'Prev' ); ?&gt;\n&lt;?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?&gt;\n&lt;span&gt; of &lt;/span&gt;\n&lt;?php echo wp_count_posts(); ?&gt;\n&lt;?php next_posts_link( 'Prev' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 233577, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>If we set the content pagination type to <code>next</code> with:</p>\n\n<pre><code>add_filter( 'wp_link_pages_args', function( Array $args )\n{\n $args['next_or_number'] = 'next';\n return $args;\n} );\n</code></pre>\n\n<p>then we can inject the <code>x of y</code> part between the <em>Previous page</em> and <em>Next page</em> links with:</p>\n\n<pre><code>add_filter( 'wp_link_pages_link', function( $link, $nextorprev ) use ( &amp;$page, &amp;$numpages )\n{\n if( $nextorprev &lt;= $page || 1 === $page )\n $link .= sprintf( ' %d %s %d ', $page, esc_html__( 'of', 'mydomain' ), $numpages );\n\n return $link;\n}, 10, 2 );\n</code></pre>\n\n<p>Then the output of <code>wp_link_pages()</code> would be like:</p>\n\n<pre><code>Pages: Previous page 5 of 6 Next page\n</code></pre>\n" } ]
2016/07/30
[ "https://wordpress.stackexchange.com/questions/233598", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I'm not familiar with working outside the loop so forgive me if this question has been asked already. How do I get a featured image of a post that's outside the loop? I did a `print_r` and I didn't see anything related to a featured image. Any ideas on what to do next? **Update:** I was able to get it working but I need a way to show every image size associated with the post's featured image. This is what I've done so far: ``` // the query. Only show posts with a certain taxonomy <?php $args = array('tax_query' => array(array('taxonomy' => 'post-status','field' => 'slug','terms' => array ('post-status-published')))); $query = new WP_Query( $args );?> <?php if ( $query->have_posts() ) : $major = false; $major_first = false; $duplicates = []; while ( $query->have_posts() ) : $query->the_post(); ?> //check if any post belongs to a certain category <?php if ( in_category( 'major' ) ) : ?> <?php $major = true;?> <?php $major_data [] = get_post($post->ID) ;?> <?php endif; ?> <?php if ( in_category( 'major-first' ) ) : ?> <?php $major_first = true;?> <?php $major_first_data [] = get_post($post->ID) ;?> <?php $image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ),'large' ); $image = $image_array; ?> <?php endif; ?> // end of the loop <?php endwhile; endif; ?> // show content <?php if ($major == true):?> <?php if ($major == true):?> <?php foreach($major_first_data as $postID) { ;?> <?php $postData = get_post( $postID );?> <?php print $postData->post_title;?><br> <?php echo $image[0]; ?> <?php } ?> <?php endif;?> <?php foreach($major_data as $postID) { ;?> <?php $postData = get_post( $postID );?> <?php print $postData->post_title;?><br> <?php } ?> <?php endif;?> ```
You could try combining these: Buttons ------- ``` next_posts_link( 'Prev' ); previous_posts_link( 'Next' ); ``` Current page ------------ ``` echo (get_query_var('paged')) ? get_query_var('paged') : 1; ``` Total pages ----------- ``` wp_count_posts(); ``` In HTML ------- ``` <?php next_posts_link( 'Prev' ); ?> <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?> <span> of </span> <?php echo wp_count_posts(); ?> <?php next_posts_link( 'Prev' ); ?> ```
233,612
<p>I have a post with something like this:</p> <pre><code>[code] $foo = &lt;&lt;&lt;EOT .... EOT; [/code] </code></pre> <p>It gets converted to this by <code>do_shortcodes_in_html_tags()</code>:</p> <pre><code>[code] $foo = &lt;&lt;&lt;EOT .... EOT; &amp;#91;/code&amp;#q3; </code></pre> <p>Therefore, the shortcode doesn't run. Is there a way to make this shortcode work correctly?</p>
[ { "answer_id": 233617, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>A workaround might be:</p>\n\n<pre><code>[code]\n$foo = &amp;lt;&amp;lt;&amp;lt;EOT\n ....\nEOT;\n[/code]\n</code></pre>\n\n<p>where we change <code>&lt;&lt;&lt;</code> to <code>&amp;lt;&amp;lt;&amp;lt;</code>. We could do this automatically before <code>do_shortcode</code> filters the content and then replace it again afterwards.</p>\n\n<p>I tested this version:</p>\n\n<pre><code>[code]\n$foo = &lt;&lt;&lt;EOT\n....\nEOT;&lt;!----&gt;\n[/code]\n</code></pre>\n\n<p>and it seems to parse the shortocde's content correctly. But then we would need to remove the extra <code>&lt;!----&gt;</code> part, after <code>do_shortcode</code> has filtered the content. <em>This approach, with the HTML comment, would display the correct HTML source, but the rendering would be problematic, except within a <code>&lt;textarea&gt;</code>.</em></p>\n\n<p><strong>Peeking into the <code>/wp-includes/shortcodes.php</code> file</strong></p>\n\n<p>The problem using an unclosed HTML tag, within the shortcode's content, seems to be that the <code>do_shortcodes_in_html_tags()</code> parser thinks <code>[/code]</code> is a part of it. </p>\n\n<p><a href=\"https://github.com/WordPress/WordPress/blob/ba12f4e95fec5e132868c21c5944a246841da9f3/wp-includes/shortcodes.php#L386-L387\" rel=\"nofollow\">This part</a> of <code>do_shortcodes_in_html_tags()</code> seems to influense this behavior:</p>\n\n<pre><code>// Looks like we found some crazy unfiltered HTML. Skipping it for sanity.\n$element = strtr( $element, $trans );\n</code></pre>\n\n<p>where <code>[/code]</code> is replaced to <code>&amp;#91;/code&amp;#93;</code>.</p>\n\n<p>This happens just before the shortcode regex-replacements.</p>\n\n<p>We would see <code>&amp;#91;/code&amp;#93;</code> from the output of <code>the_content()</code>, if <a href=\"https://github.com/WordPress/WordPress/blob/ba12f4e95fec5e132868c21c5944a246841da9f3/wp-includes/shortcodes.php#L226\" rel=\"nofollow\">this part</a>:</p>\n\n<pre><code>$content = unescape_invalid_shortcodes( $content );\n</code></pre>\n\n<p>wouldn't run at the end of the <code>do_shortcode()</code> function.</p>\n\n<p>So it's like we didn't close the shortcode.</p>\n\n<p><strong>HTML Encoding The Code Blocks</strong></p>\n\n<p>We could HTML encode the content of the code blocks with:</p>\n\n<pre><code>add_filter( 'the_content', function( $content )\n{\n if( has_shortcode( $content, 'code' ) ) \n $content = preg_replace_callback( \n '#\\[code\\](.*?)\\[/code\\]#s', \n 'wpse_code_filter', \n $content \n );\n\n return $content;\n\n}, 1 );\n</code></pre>\n\n<p>where our custom callback is defined as:</p>\n\n<pre><code>function wpse_code_filter( $matches )\n{\n return esc_html( $matches[0] );\n}\n</code></pre>\n\n<p>Note that there are still things to be sorted out like </p>\n\n<ul>\n<li>content filters within the core, e.g. the <code>wpautop</code> filter, </li>\n<li>content filters from 3rd party plugins</li>\n<li>shortcodes inside the codeblock, </li>\n<li>etc. </li>\n</ul>\n\n<p>It's informative to look at plugins like <a href=\"https://wordpress.org/plugins/syntaxhighlighter/\" rel=\"nofollow\"><code>SyntaxHighligther Evolved</code></a> to see the what kind of workarounds would be needed. (I'm not related to that plugin).</p>\n\n<p><strong>Alternatives</strong></p>\n\n<p>Another approach is to move the code outside of the content editor and store it in e.g. </p>\n\n<ul>\n<li>custom fields, </li>\n<li>custom tables</li>\n<li>custom post type (e.g. stored as excerpts). </li>\n</ul>\n\n<p>For the latter case, this kind of shortcode comes to mind (PHP 7+):</p>\n\n<pre><code>add_shortcode( 'codeblock', function( Array $atts, String $content )\n{\n // Setup default attributes\n $atts = shortcode_atts( [ 'id' =&gt; 0 ], $atts, 'codeblock_shortcode' );\n\n // We only want to target the 'codeblock' post type\n if( empty( $atts['id'] ) || 'codeblock' !== get_post_type( $atts['id'] ) ) \n return $content;\n\n // Pre wrapped and HTML escaped post-excerpt from the 'codeblock' post type\n return sprintf( \n '&lt;pre&gt;%s&lt;/pre&gt;',\n esc_html( \n get_post_field(\n 'post_excerpt', \n $atts['id'], \n 'raw' \n )\n )\n );\n} );\n</code></pre>\n\n<p><em>This might need further testing and adjustments!</em></p>\n\n<p>Then we could refer to each codeblock with</p>\n\n<pre><code>[codeblock id=\"123\"]\n</code></pre>\n\n<p>in the content editor.</p>\n" }, { "answer_id": 233740, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<h2>Shortcode With Hidden Payload</h2>\n\n<p>Another approach would be to pre-process the shortcode's content, by temporarily removing it, before e.g. the <code>wpautop()</code> and <code>do_shortcode()</code> act on it and then replacing it again afterwards.</p>\n\n<p><em>I'm sure this kind of approach has been implemented in various ways before, but I played with it in this way:</em></p>\n\n<h2>Example</h2>\n\n<p>Here's an example of the pre-processing:</p>\n\n<pre><code>[code lang=\"php\"]\n$foo = &lt;&lt;&lt;EOT\n ....\nEOT;\n[/code]\n</code></pre>\n\n<p>This code block would be replaced with:</p>\n\n<pre><code>[code lang=\"php\"]code_b6a7d410d48883693b6714b68a4eee0a[/code]\n</code></pre>\n\n<p>where the reference number could be <code>md5</code> of the code block's content.</p>\n\n<p>The processing of <code>do_shortcode()</code> and <code>wpautop()</code> should now not be a problem for the content of our code block.</p>\n\n<p>Our shortcode will then output the code block corresponding to the reference number.</p>\n\n<h2>Basic implementation</h2>\n\n<p>The basic setup would be registering the shortcode and the early pre-processing filter:</p>\n\n<pre><code>add_shortcode( $tag, [ $this, 'shortcode' ] );\nadd_filter( 'the_content', [ $this, 'filter_before' ], 0 );\n</code></pre>\n\n<p>The shortcode is defined as:</p>\n\n<pre><code>public function shortcode( $atts, $content )\n{\n // Default attributes\n $atts = shortcode_atts( ['lang' =&gt; 'php'], $atts, 'codeblock_shortcode' );\n\n // Restore the code block's content, HTML escaped it and pre-wrap it\n return sprintf( \n '&lt;pre lang=\"%s\"&gt;%s&lt;/pre&gt;',\n esc_attr( $atts['lang'] ),\n esc_html( $this-&gt;filter_after( $content ) ) \n );\n}\n</code></pre>\n\n<p>where the code blocks are hidden with a <code>filter_before()</code> method and restored with a <code>filter_after()</code> method. Then HTML escaped and finally wrapped in a <code>&lt;pre&gt;</code> tag.</p>\n\n<p>In this kind of a problem, it's handy to use <code>preg_replace</code> with a callback.</p>\n\n<h2>Demo Plugin</h2>\n\n<p>Here's a demo plugin:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Simple Code Block\n * Description: Support for the [code] shortcode to display code snippets.\n * Plugin URI: http://wordpress.stackexchange.com/a/233740/26350\n * Author: birgire\n * Version: 1.0.0\n */\n\nnamespace WPSE\\SimpleCodeBlock;\n\nadd_action( 'init', function()\n{\n $o = new CodeBlock;\n $o-&gt;init( $tag = 'code' );\n} );\n\n\nclass CodeBlock\n{\n private $blocks;\n private $tag;\n\n public function init( $tag )\n { \n if( ! shortcode_exists( $tag ) &amp;&amp; preg_match( '#^[a-z]+$#', $tag ) )\n {\n $this-&gt;tag = $tag;\n $this-&gt;blocks = [];\n\n add_shortcode( $tag, [ $this, 'shortcode' ] );\n add_filter( 'the_content', [ $this, 'filter_before' ], 0 );\n }\n }\n\n public function filter_before( $content )\n {\n if( $this-&gt;has_code_block( $content ) )\n {\n $tag = preg_quote( $this-&gt;tag );\n\n $pattern = \"#(\\[{$tag}(\\s+[^\\]]+)?\\])(.*?)(\\[\\/{$tag}\\])#s\";\n $content = preg_replace_callback( \n $pattern, \n [ $this, 'regex_before' ], \n $content \n );\n\n }\n return $content;\n }\n\n public function filter_after( $content ) \n {\n if( $this-&gt;has_code_key( $content ) )\n {\n $tag = preg_quote( $this-&gt;tag );\n $pattern = \"#{$tag}\\_[a-z0-9]{32}#\"; \n $content = preg_replace_callback(\n $pattern,\n [ $this, 'regex_after' ], \n $content \n );\n } \n return $content;\n }\n\n public function regex_before ( Array $matches ) \n { \n // Nothing to do \n if( 5 !== count( $matches ) )\n return;\n\n // Generate a key from the code block's content\n $key = $this-&gt;tag . '_' . md5( $matches[3] );\n\n // Temporarily store the code block\n $this-&gt;blocks[$key] = $matches[3]; \n\n // Return this form [code ...]code_b6a7d410d48883693b6714b68a4eee0a[/code]\n return $matches[1] . $key . $matches[4];\n }\n\n public function regex_after( Array $matches )\n { \n $key = $matches[0];\n\n // Restore the code block's content\n if( isset( $this-&gt;blocks[$key] ) )\n return $this-&gt;blocks[$key];\n\n return; \n }\n\n public function shortcode( $atts = [], $content = '' )\n {\n // Default attributes\n $atts = shortcode_atts( ['lang' =&gt; 'php'], $atts, 'codeblock_shortcode' );\n\n // Restore the code block's content, HTML escaped it and pre-wrap it\n return sprintf( \n '&lt;pre lang=\"%s\"&gt;%s&lt;/pre&gt;',\n esc_attr( $atts['lang'] ),\n esc_html( $this-&gt;filter_after( $content ) ) \n );\n }\n\n private function has_code_key( $content )\n {\n return false !== strpos( $content, $this-&gt;tag . '_' );\n }\n\n private function has_code_block( $content )\n {\n return false !== strpos( $content, '[' . $this-&gt;tag );\n }\n\n} // end class\n</code></pre>\n\n<p>It's also possible to adjust this slightly, so that <code>[code]</code> isn't defined as a shortcode and restore the code block's content at the priority of <code>PHP_INT_MAX</code> within the <code>the_content</code> filter.</p>\n" } ]
2016/07/30
[ "https://wordpress.stackexchange.com/questions/233612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23538/" ]
I have a post with something like this: ``` [code] $foo = <<<EOT .... EOT; [/code] ``` It gets converted to this by `do_shortcodes_in_html_tags()`: ``` [code] $foo = <<<EOT .... EOT; &#91;/code&#q3; ``` Therefore, the shortcode doesn't run. Is there a way to make this shortcode work correctly?
A workaround might be: ``` [code] $foo = &lt;&lt;&lt;EOT .... EOT; [/code] ``` where we change `<<<` to `&lt;&lt;&lt;`. We could do this automatically before `do_shortcode` filters the content and then replace it again afterwards. I tested this version: ``` [code] $foo = <<<EOT .... EOT;<!----> [/code] ``` and it seems to parse the shortocde's content correctly. But then we would need to remove the extra `<!---->` part, after `do_shortcode` has filtered the content. *This approach, with the HTML comment, would display the correct HTML source, but the rendering would be problematic, except within a `<textarea>`.* **Peeking into the `/wp-includes/shortcodes.php` file** The problem using an unclosed HTML tag, within the shortcode's content, seems to be that the `do_shortcodes_in_html_tags()` parser thinks `[/code]` is a part of it. [This part](https://github.com/WordPress/WordPress/blob/ba12f4e95fec5e132868c21c5944a246841da9f3/wp-includes/shortcodes.php#L386-L387) of `do_shortcodes_in_html_tags()` seems to influense this behavior: ``` // Looks like we found some crazy unfiltered HTML. Skipping it for sanity. $element = strtr( $element, $trans ); ``` where `[/code]` is replaced to `&#91;/code&#93;`. This happens just before the shortcode regex-replacements. We would see `&#91;/code&#93;` from the output of `the_content()`, if [this part](https://github.com/WordPress/WordPress/blob/ba12f4e95fec5e132868c21c5944a246841da9f3/wp-includes/shortcodes.php#L226): ``` $content = unescape_invalid_shortcodes( $content ); ``` wouldn't run at the end of the `do_shortcode()` function. So it's like we didn't close the shortcode. **HTML Encoding The Code Blocks** We could HTML encode the content of the code blocks with: ``` add_filter( 'the_content', function( $content ) { if( has_shortcode( $content, 'code' ) ) $content = preg_replace_callback( '#\[code\](.*?)\[/code\]#s', 'wpse_code_filter', $content ); return $content; }, 1 ); ``` where our custom callback is defined as: ``` function wpse_code_filter( $matches ) { return esc_html( $matches[0] ); } ``` Note that there are still things to be sorted out like * content filters within the core, e.g. the `wpautop` filter, * content filters from 3rd party plugins * shortcodes inside the codeblock, * etc. It's informative to look at plugins like [`SyntaxHighligther Evolved`](https://wordpress.org/plugins/syntaxhighlighter/) to see the what kind of workarounds would be needed. (I'm not related to that plugin). **Alternatives** Another approach is to move the code outside of the content editor and store it in e.g. * custom fields, * custom tables * custom post type (e.g. stored as excerpts). For the latter case, this kind of shortcode comes to mind (PHP 7+): ``` add_shortcode( 'codeblock', function( Array $atts, String $content ) { // Setup default attributes $atts = shortcode_atts( [ 'id' => 0 ], $atts, 'codeblock_shortcode' ); // We only want to target the 'codeblock' post type if( empty( $atts['id'] ) || 'codeblock' !== get_post_type( $atts['id'] ) ) return $content; // Pre wrapped and HTML escaped post-excerpt from the 'codeblock' post type return sprintf( '<pre>%s</pre>', esc_html( get_post_field( 'post_excerpt', $atts['id'], 'raw' ) ) ); } ); ``` *This might need further testing and adjustments!* Then we could refer to each codeblock with ``` [codeblock id="123"] ``` in the content editor.
233,616
<p>I have created a page template where I need current page URL</p> <p>I have tried </p> <pre><code>get_site_url(); </code></pre> <p>and</p> <pre><code>get_permalink(); </code></pre> <p>but it shows nothing. </p> <p>Let me know is anything missing in code.</p>
[ { "answer_id": 233618, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 3, "selected": true, "text": "<p>if you're using a page template, then if you want to get the current page URL you could try to use this function:</p>\n\n<pre><code>get_permalink();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>echo get_permalink();\n</code></pre>\n\n<p>if you want to print the result</p>\n" }, { "answer_id": 233621, "author": "ma_dev_15", "author_id": 99113, "author_profile": "https://wordpress.stackexchange.com/users/99113", "pm_score": 0, "selected": false, "text": "<p>You can get page url like this.</p>\n\n<pre><code>global $post;\necho get_permalink( $post-&gt;ID );\n</code></pre>\n\n<p>Hope it helps :)</p>\n" } ]
2016/07/30
[ "https://wordpress.stackexchange.com/questions/233616", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95126/" ]
I have created a page template where I need current page URL I have tried ``` get_site_url(); ``` and ``` get_permalink(); ``` but it shows nothing. Let me know is anything missing in code.
if you're using a page template, then if you want to get the current page URL you could try to use this function: ``` get_permalink(); ``` or ``` echo get_permalink(); ``` if you want to print the result
233,667
<p>I want to hide an item from a menu if a user is logged out.</p> <p>I am currently using the below code that achieves this using two separate menus, but to save duplication, I would like to only have to manage one nav menu.</p> <pre><code>function my_wp_nav_menu_args( $args = '' ) { if ( is_user_logged_in() ) { $args['menu'] = 'logged-in'; } else { $args['menu'] = 'logged-out'; } return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); </code></pre> <p>Is it possible to hide just one item for a logged out user, rather than doing it the way I currently am?</p>
[ { "answer_id": 233671, "author": "MD Sultan Nasir Uddin", "author_id": 86834, "author_profile": "https://wordpress.stackexchange.com/users/86834", "pm_score": -1, "selected": true, "text": "<p>Find the class or id of the menu item that you want to hide.\nsuppose the class of that menu is <code>logged-in-menu</code></p>\n<p>Then in header.php file of your theme before closing head tag use the below code</p>\n<pre><code>&lt;style&gt;\n&lt;?php if(! is_user_logged_in() ) : ?&gt;\n .logged-in-menu{\n display: none;\n }\n&lt;?php endif; ?&gt;\n&lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 233675, "author": "chrisguitarguy", "author_id": 6035, "author_profile": "https://wordpress.stackexchange.com/users/6035", "pm_score": 3, "selected": false, "text": "<p>Filter <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu_objects</code></a>. It will contain the sorted list of nav menu items to render. Have a look at <a href=\"https://github.com/WordPress/WordPress/blob/eb7df1379be5f7b24a6d29c1a390c1b1bf2e6183/wp-includes/nav-menu.php#L732\" rel=\"nofollow noreferrer\"><code>wp_setup_nav_menu_item</code></a> for some properties you can use.</p>\n\n<p>Here's a quick (untested) example.</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', function( array $items, array $args ) {\n\n if ( 'someThemeLocation' !== $args-&gt;theme_location ) {\n return $items;\n }\n\n return array_filter( $items, function( $item ) {\n return '/user-specific-thingy' === $item-&gt;url \n &amp;&amp; ! is_user_logged_in();\n } );\n\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 233680, "author": "kaiser", "author_id": 385, "author_profile": "https://wordpress.stackexchange.com/users/385", "pm_score": 3, "selected": false, "text": "<p>As @chrisguitarguy already added a more than valid answered while I was writing this answer, here's a simple <em>addition</em> to the other two answers.</p>\n\n<p>The <code>return</code> value of the <code>wp_setup_nav_menu()</code> function has <a href=\"https://github.com/WordPress/WordPress/blob/eb7df1379be5f7b24a6d29c1a390c1b1bf2e6183/wp-includes/nav-menu.php#L880\" rel=\"nofollow noreferrer\">a filter</a>, which has <code>$menu_item</code> as only value provided – exactly before it is returned – and it is of type <code>object</code> and a <code>\\stdClass</code> with the following <code>public</code> properties that you can check against:</p>\n\n<ul>\n<li><code>ID</code>: The term_id if the menu item represents a taxonomy term.</li>\n<li><code>attr_title</code>: The title attribute of the link element for this menu item.</li>\n<li><code>classes</code>: The array of class attribute values for the link element of this menu item.</li>\n<li><code>db_id</code>: The DB ID of this item as a nav_menu_item object, if it exists (0 if it doesn't exist).</li>\n<li><code>description</code>: The description of this menu item.</li>\n<li><code>menu_item_parent</code>: The DB ID of the nav_menu_item that is this item's menu parent, if any. 0 otherwise.</li>\n<li><code>object</code>: The type of object originally represented, such as \"category,\" \"post\", or \"attachment.\"</li>\n<li><code>object_id</code>: The DB ID of the original object this menu item represents, e.g. ID for posts and term_id for categories.</li>\n<li><code>post_parent</code>: The DB ID of the original object's parent object, if any (0 otherwise).</li>\n<li><code>post_title</code>: A \"no title\" label if menu item represents a post that lacks a title.</li>\n<li><code>target</code>: The target attribute of the link element for this menu item.</li>\n<li><code>title</code>: The title of this menu item.</li>\n<li><code>type</code>: The family of objects originally represented, such as \"post_type\" or \"taxonomy.\"</li>\n<li><code>type_label</code>: The singular label used to describe this type of menu item.</li>\n<li><code>url</code>: The URL to which this menu item points.</li>\n<li><code>xfn</code>: The XFN relationship expressed in the link of this menu item.</li>\n<li><code>_invalid</code>: Whether the menu item represents an object that no longer exists.</li>\n</ul>\n\n<p>So a simple callback will allow you to use some conditional logic and then maybe exclude an item:</p>\n\n<pre><code>add_filter( 'wp_setup_nav_menu', function( \\stdClass $item ) {\n # Check conditionals, and invalidate an item in case\n $item-&gt;_invalid = is_user_logged_in() \n &amp;&amp; 'post' === $item-&gt;object\n &amp;&amp; 'post_type' === $item-&gt;type\n # &amp;&amp; … whatever you need to check for your invalidation of an item\n ;\n\n return $item;\n} );\n</code></pre>\n\n<p>The exclusion logic lives inside the <code>_invalid</code> property and is executed by the <a href=\"https://github.com/WordPress/WordPress/blob/eb7df1379be5f7b24a6d29c1a390c1b1bf2e6183/wp-includes/nav-menu.php#L603-L605\" rel=\"nofollow noreferrer\"><code>_is_valid_nav_menu_item( $item )</code></a> function that is a callback used when <a href=\"https://github.com/WordPress/WordPress/blob/eb7df1379be5f7b24a6d29c1a390c1b1bf2e6183/wp-includes/nav-menu.php#L678-L682\" rel=\"nofollow noreferrer\">nav menu items are retrieved</a>. It uses it inside a <code>array_filter()</code> to reduce the number of items depending on this <em>flag</em>.</p>\n\n<hr>\n\n<p>As extension to @MD Sultan Nasir Uddin solution: While a CSS only solution will work, goal should be to not even have the data in this request, in the database query and in the render pipeline. For a complete answer, here still is the <em>how</em>: Example using <a href=\"https://codex.wordpress.org/Function_Reference/wp_add_inline_style\" rel=\"nofollow noreferrer\"><code>wp_add_inline_style()</code></a> to inline the styles and <a href=\"http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc\" rel=\"nofollow noreferrer\">PHP heredoc syntax</a> for readability:</p>\n\n<pre><code>&lt;?php\n/** Plugin Name: Hide menu items for logged in users */\n\n# Add class:\nadd_filter( 'wp_nav_menu_args', function( Array $args ) {\n if ( is_user_logged_in() )\n $args['menu_class'] .= ' logged-in';\n return $args;\n} );\n\n# Add inline styles\nadd_action( 'wp_enqueue_scripts', function() {\n\n $styles = &lt;&lt;&lt;STYLES\n.logged-in .special-item {\n display: none;\n}\nSTYLES;\n\n wp_add_inline_style( 'custom-style', $styles );\n} );\n</code></pre>\n\n<p>You could probably just use the <code>body</code> classes to find a <code>logged-in</code> or similar class for a more specific target as well – instead of adding an additional class like above.</p>\n" }, { "answer_id": 235270, "author": "Iqbal Mahmud", "author_id": 99257, "author_profile": "https://wordpress.stackexchange.com/users/99257", "pm_score": 2, "selected": false, "text": "<p>After that I make it done using css nth child the procedure is </p>\n\n<pre><code>add_action('wp_head','hide_menu');\n\nfunction hide_menu() { \n if ( is_user_logged_in() ) {\n //\n } else {\n $output=\"&lt;style&gt; .menu li:nth-child(3) { display: none; } &lt;/style&gt;\";\n }\n echo $output;\n}\n</code></pre>\n\n<p>Thanks all of you for your effort :)</p>\n" }, { "answer_id": 384420, "author": "Mohannad Najjar", "author_id": 202796, "author_profile": "https://wordpress.stackexchange.com/users/202796", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php\n//Then in header.php file of your theme before closing head tag use the below code\n//https://wordpress.stackexchange.com/questions/233667/how-to-hide-an-item-from-a-menu-to-logged-out-users-without-a-plugin\n &lt;?php\n if ( is_user_logged_in() ) {\n $output=&quot;&lt;style&gt;.menu-item-8685 {display: none !important;}&lt;/style&gt;&quot;;\necho $output;\n } else { \n echo '&lt;script&gt;alert(&quot;Welcome vistor&quot;)&lt;/script&gt;';\n }\n ?&gt;\n</code></pre>\n" }, { "answer_id": 407154, "author": "Jamio", "author_id": 195391, "author_profile": "https://wordpress.stackexchange.com/users/195391", "pm_score": 0, "selected": false, "text": "<p>I don't like the idea of just hiding menu items with CSS as they would still be visible using the code inspector on the page. For anyone looking for a more secure way of removing menu items, this should do the trick:</p>\n<p><strong>In this example I want to remove a &quot;Downloads&quot; menu item for anyone that is not currently logged in.</strong></p>\n<pre><code>add_filter( 'wp_nav_menu_objects', 'remove_menu_items' ), 10, 2 );\n</code></pre>\n<pre><code>function remove_menu_items( $items, $args ) {\n\n // If you need to remove several menu items, then it's good practice to set a variable for the check beforehand so that it's not running the same check function repeatedly.\n $logged_in = is_user_logged_in();\n\n foreach ( $items as $item_index =&gt; $item ) {\n // Remove &quot;Downloads&quot; menu item when not logged in\n if ( $item-&gt;title == 'Downloads' ) {\n if ( !$logged_in ) {\n unset($items[$item_index]);\n }\n }\n }\n return $items;\n}\n</code></pre>\n" }, { "answer_id": 410677, "author": "Eunice", "author_id": 191000, "author_profile": "https://wordpress.stackexchange.com/users/191000", "pm_score": 1, "selected": false, "text": "<p>Based on @jamio answer I agree that if you just <code>display:none</code> the menu its still accessible thru <code>inspect element</code>, therefore I come up with the solution that if you want to hide the nav menus based on their class you can use <code>classes[0] </code> instead of <code>title</code> so that you can now just add a class on menu instead on setting each menu thru code</p>\n<pre><code> add_filter( 'wp_nav_menu_objects', 'remove_menu_items', 10, 2 );\nfunction remove_menu_items( $items, $args ) {\n\n $logged_in = is_user_logged_in();\n\n foreach ( $items as $item_index =&gt; $item ) {\n // Remove menu item with &quot;hide_when_logout&quot; class when not logged in\n if ( $item-&gt;classes[0] == 'hide_when_logout' ) {\n if ( !$logged_in ) {\n unset($items[$item_index]);\n }\n }\n }\n return $items;\n}\n</code></pre>\n" } ]
2016/07/31
[ "https://wordpress.stackexchange.com/questions/233667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99257/" ]
I want to hide an item from a menu if a user is logged out. I am currently using the below code that achieves this using two separate menus, but to save duplication, I would like to only have to manage one nav menu. ``` function my_wp_nav_menu_args( $args = '' ) { if ( is_user_logged_in() ) { $args['menu'] = 'logged-in'; } else { $args['menu'] = 'logged-out'; } return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); ``` Is it possible to hide just one item for a logged out user, rather than doing it the way I currently am?
Find the class or id of the menu item that you want to hide. suppose the class of that menu is `logged-in-menu` Then in header.php file of your theme before closing head tag use the below code ``` <style> <?php if(! is_user_logged_in() ) : ?> .logged-in-menu{ display: none; } <?php endif; ?> </style> ```
233,681
<p>I have a custom post type "book", and a taxonomy "language" with terms "php" , "java" ,"c", "python". I want to count "book" posts not having terms "java" &amp; "c".. such that posts with only "java" or "c" should be counted but posts with both "java" and "c" should not be counted. I tried tax_query of WP_QUERY using operator "NOT IN" and "=" but haven't got correct answer. There should be "NAND" operator for tax_query.</p> <p><em>P.S : I have approx 20 terms and 200 posts for each. With this tax_query I have added 1 AND tax_query also and that is for other taxonomy term.</em></p> <p><code>$myargs=array( 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'author', 'field' =&gt; 'slug', 'terms' =&gt; array( 'ABC', 'XYZ' ), ), array( 'taxonomy' =&gt; 'language', 'field' =&gt; 'slug', 'terms' =&gt; array( "c", "java"), 'operator' =&gt; 'NOT IN', ), ), 'post_type' =&gt; 'book');</code></p> <p>A book may have one or more language terms.</p>
[ { "answer_id": 233688, "author": "Luis Sanz", "author_id": 81084, "author_profile": "https://wordpress.stackexchange.com/users/81084", "pm_score": 1, "selected": false, "text": "<p>There is not a <code>NAND</code> operator for the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\"><code>tax_query</code> of <code>WP_Query</code></a>. If I understood correctly, what you intend can be rewritten this way:</p>\n\n<ol>\n<li>Get all the posts without the term <code>c</code>.</li>\n<li>Get all the posts without the term <code>java</code>.</li>\n<li>Exclude the posts having both the terms <code>c</code> and <code>java</code>.</li>\n</ol>\n\n<p>To achieve that, you can combine two <code>NOT IN</code> queries and match them with an <code>OR</code>:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'book',\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'taxonomy' =&gt; 'language',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( 'c' ),\n 'operator' =&gt; 'NOT IN',\n ),\n array(\n 'taxonomy' =&gt; 'language',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( 'java' ),\n 'operator' =&gt; 'NOT IN',\n ),\n ) \n);\n\n$posts = get_posts( $args );\n\necho count( $posts );\n</code></pre>\n" }, { "answer_id": 233696, "author": "Mihir", "author_id": 86197, "author_profile": "https://wordpress.stackexchange.com/users/86197", "pm_score": 0, "selected": false, "text": "<p>Hey guys somehow this helped me to get count of NAND operation.\nBecause I dont need ti iterate through those posts, I used <code>found_posts</code> of <code>WP_Query</code> . Subtracting my posts count from total post count.</p>\n\n<p>I'm still waiting for a better way if any. Thanx <a href=\"https://wordpress.stackexchange.com/a/233688/86197\">Luis</a>.</p>\n\n<pre><code>$myargs=array(\n'posts_per_page' =&gt; -1,\n'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'taxonomy' =&gt; 'author',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $author_terms //array of author term slug(s),\n 'operator' =&gt; 'IN' //default operator ?\n\n ),\n array(\n 'taxonomy' =&gt; 'language',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $language_terms //array of language term slug(s)\n 'operator' =&gt; 'AND' \n )\n ),\n'post_type' =&gt; 'apk');\n\n$allargs=array(\n'posts_per_page' =&gt; -1,\n'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'author',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $author_terms //array of author term slug(s),\n 'operator' =&gt; 'IN' //default operator ?\n\n )\n ),\n'post_type' =&gt; 'apk');\n\n$myquery=new WP_Query($myargs);\n$allquery=new WP_Query($allargs);\n\necho allquery-&gt;found_posts - $myquery-&gt;found_posts;\n</code></pre>\n" } ]
2016/07/31
[ "https://wordpress.stackexchange.com/questions/233681", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86197/" ]
I have a custom post type "book", and a taxonomy "language" with terms "php" , "java" ,"c", "python". I want to count "book" posts not having terms "java" & "c".. such that posts with only "java" or "c" should be counted but posts with both "java" and "c" should not be counted. I tried tax\_query of WP\_QUERY using operator "NOT IN" and "=" but haven't got correct answer. There should be "NAND" operator for tax\_query. *P.S : I have approx 20 terms and 200 posts for each. With this tax\_query I have added 1 AND tax\_query also and that is for other taxonomy term.* `$myargs=array( 'posts_per_page' => -1, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'author', 'field' => 'slug', 'terms' => array( 'ABC', 'XYZ' ), ), array( 'taxonomy' => 'language', 'field' => 'slug', 'terms' => array( "c", "java"), 'operator' => 'NOT IN', ), ), 'post_type' => 'book');` A book may have one or more language terms.
There is not a `NAND` operator for the [`tax_query` of `WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters). If I understood correctly, what you intend can be rewritten this way: 1. Get all the posts without the term `c`. 2. Get all the posts without the term `java`. 3. Exclude the posts having both the terms `c` and `java`. To achieve that, you can combine two `NOT IN` queries and match them with an `OR`: ``` $args = array( 'post_type' => 'book', 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'language', 'field' => 'slug', 'terms' => array( 'c' ), 'operator' => 'NOT IN', ), array( 'taxonomy' => 'language', 'field' => 'slug', 'terms' => array( 'java' ), 'operator' => 'NOT IN', ), ) ); $posts = get_posts( $args ); echo count( $posts ); ```
233,724
<p>hey i am developing a plugin and i am almost near to close the plugin but i am facing a small problem in displaying the code <code>&lt;?php global $options; $options = get_option('p2h_theme_options'); ?&gt;</code> below the <code>&lt;?php wp_head(); ?&gt;</code> in the header. i tried using echo but no use it is displaying in string rather of code. below is the code i tried to display:</p> <pre><code> add_action( 'wp_head', 'my_facebook_tags' ); function my_facebook_tags() { echo '&lt;?php global $options; $options = get_option("p2h_theme_options") ?&gt;'; } </code></pre> <p>thanks in advance for help..</p>
[ { "answer_id": 233688, "author": "Luis Sanz", "author_id": 81084, "author_profile": "https://wordpress.stackexchange.com/users/81084", "pm_score": 1, "selected": false, "text": "<p>There is not a <code>NAND</code> operator for the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\"><code>tax_query</code> of <code>WP_Query</code></a>. If I understood correctly, what you intend can be rewritten this way:</p>\n\n<ol>\n<li>Get all the posts without the term <code>c</code>.</li>\n<li>Get all the posts without the term <code>java</code>.</li>\n<li>Exclude the posts having both the terms <code>c</code> and <code>java</code>.</li>\n</ol>\n\n<p>To achieve that, you can combine two <code>NOT IN</code> queries and match them with an <code>OR</code>:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'book',\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'OR',\n array(\n 'taxonomy' =&gt; 'language',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( 'c' ),\n 'operator' =&gt; 'NOT IN',\n ),\n array(\n 'taxonomy' =&gt; 'language',\n 'field' =&gt; 'slug',\n 'terms' =&gt; array( 'java' ),\n 'operator' =&gt; 'NOT IN',\n ),\n ) \n);\n\n$posts = get_posts( $args );\n\necho count( $posts );\n</code></pre>\n" }, { "answer_id": 233696, "author": "Mihir", "author_id": 86197, "author_profile": "https://wordpress.stackexchange.com/users/86197", "pm_score": 0, "selected": false, "text": "<p>Hey guys somehow this helped me to get count of NAND operation.\nBecause I dont need ti iterate through those posts, I used <code>found_posts</code> of <code>WP_Query</code> . Subtracting my posts count from total post count.</p>\n\n<p>I'm still waiting for a better way if any. Thanx <a href=\"https://wordpress.stackexchange.com/a/233688/86197\">Luis</a>.</p>\n\n<pre><code>$myargs=array(\n'posts_per_page' =&gt; -1,\n'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array(\n 'taxonomy' =&gt; 'author',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $author_terms //array of author term slug(s),\n 'operator' =&gt; 'IN' //default operator ?\n\n ),\n array(\n 'taxonomy' =&gt; 'language',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $language_terms //array of language term slug(s)\n 'operator' =&gt; 'AND' \n )\n ),\n'post_type' =&gt; 'apk');\n\n$allargs=array(\n'posts_per_page' =&gt; -1,\n'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'author',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $author_terms //array of author term slug(s),\n 'operator' =&gt; 'IN' //default operator ?\n\n )\n ),\n'post_type' =&gt; 'apk');\n\n$myquery=new WP_Query($myargs);\n$allquery=new WP_Query($allargs);\n\necho allquery-&gt;found_posts - $myquery-&gt;found_posts;\n</code></pre>\n" } ]
2016/08/01
[ "https://wordpress.stackexchange.com/questions/233724", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97802/" ]
hey i am developing a plugin and i am almost near to close the plugin but i am facing a small problem in displaying the code `<?php global $options; $options = get_option('p2h_theme_options'); ?>` below the `<?php wp_head(); ?>` in the header. i tried using echo but no use it is displaying in string rather of code. below is the code i tried to display: ``` add_action( 'wp_head', 'my_facebook_tags' ); function my_facebook_tags() { echo '<?php global $options; $options = get_option("p2h_theme_options") ?>'; } ``` thanks in advance for help..
There is not a `NAND` operator for the [`tax_query` of `WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters). If I understood correctly, what you intend can be rewritten this way: 1. Get all the posts without the term `c`. 2. Get all the posts without the term `java`. 3. Exclude the posts having both the terms `c` and `java`. To achieve that, you can combine two `NOT IN` queries and match them with an `OR`: ``` $args = array( 'post_type' => 'book', 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'language', 'field' => 'slug', 'terms' => array( 'c' ), 'operator' => 'NOT IN', ), array( 'taxonomy' => 'language', 'field' => 'slug', 'terms' => array( 'java' ), 'operator' => 'NOT IN', ), ) ); $posts = get_posts( $args ); echo count( $posts ); ```
233,757
<p>This is a very common issue, but all the answers I read don't relate to what's happening in my case.</p> <p>I'm writing a custom plugin that reads and writes/updates data to a custom database table (it's very simple).</p> <p>However, when an update is made, I wish to redirect to the main page, and then display a success admin notice on the page. However, when submitting the form, and attempting <code>wp_safe_redirect</code> I get the following:</p> <blockquote> <p>Warning: Cannot modify header information - headers already sent by (output started at C:\wamp64\www\bellavou\wp-includes\formatting.php:4593) in C:\wamp64\www\bellavou\wp-includes\pluggable.php on line 1167</p> </blockquote> <p>I don't have any blank spaces in my plugin files, and my call to the redirect, within the <code>wpdb-&gt;update</code> call looks like this:</p> <pre><code>if($wpdb-&gt;update( 'wp_before_after', $bv_before_after_data, array( 'id' =&gt; $bv_id ), array( '%s', // value1 '%s', // value2 '%s', // value3 '%d', // value4 '%d', // value5 '%d', // value6 '%d', // value7 '%d', // value8 '%s', // value9 '%s', // value10 '%s', // value11 '%s', // value12 ), array( '%d' ) )) { // Success wp_safe_redirect('/wp-admin/admin.php?page=bv_before_afters_main&amp;amp;updated=1'); } else { // Error echo '&lt;div class="notice notice-error is-dismissible"&gt;&lt;p&gt;Could not be updated! (Maybe there was nothing to update?)&lt;/p&gt;&lt;/div&gt;'; } </code></pre> <p>How can I order this correctly so the redirect, and admin notice will work correctly?</p> <p>UPDATE:</p> <p>My main plugin file looks like this (with the includes to other pages):</p> <pre><code>// Create page in WP Admin function my_admin_menu() { add_menu_page( 'Before &amp; After Photos', 'Before &amp; Afters', 'edit_posts', 'bv_before_afters_main', 'bv_before_afters_main', 'dashicons-format-gallery', 58 ); add_submenu_page( 'bv_before_afters_main', 'Add set', 'Add set', 'edit_posts', 'bv_before_afters_add', 'bv_before_afters_add' ); add_submenu_page( 'bv_before_afters_main', 'Edit set', 'Edit set', 'edit_posts', 'bv_before_afters_edit', 'bv_before_afters_edit' ); } add_action( 'admin_menu', 'my_admin_menu' ); // Apply stylesheets function bv_before_afters_styles(){ wp_enqueue_style( 'bv_before_after_styles', plugins_url( '/bv_before_afters.css', __FILE__ ) ); } add_action('admin_print_styles', 'bv_before_afters_styles'); // Display the main page function bv_before_afters_main(){ include_once plugin_dir_path( __FILE__ ).'/views/view_all.php'; } // Display the edit page function bv_before_afters_edit(){ include_once plugin_dir_path( __FILE__ ).'/views/edit.php'; } // Display the add page function bv_before_afters_add(){ include_once plugin_dir_path( __FILE__ ).'/views/add.php'; } </code></pre> <p>(the redirect code is within <code>edit.php</code>)</p>
[ { "answer_id": 233769, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 4, "selected": true, "text": "<h2>Background</h2>\n<p>The infamous &quot;<strong>Headers already sent</strong>&quot; error rears it's ugly head in circumstances where something attempts to modify the HTTP headers for the server's response <em>after</em> they have already been dispatched to the browser - that is to say, when the server should only be generating the <em>body</em> of the response.</p>\n<p>This often happens in one of two ways:</p>\n<ul>\n<li>Code prints things too early before WordPress has finished composing headers - this pushes the HTTP response to the browser and forces the HTTP headers to be dispatched in the process. Any attempts by WordPress or third-party code that would normally properly modify the headers will subsequently produce the error.</li>\n<li>Code attempts to alter HTTP headers too late after WordPress has already sent them and begun to render HTML.</li>\n</ul>\n<hr />\n<h2>Problem &amp; Solution Overview</h2>\n<p>This instance, the problem is the latter. This is because the <code>wp_safe_redirect()</code> function works by setting a <code>300</code>-range HTTP status header. Since the callback function arguments for <code>add_menu_page()</code> and <code>add_submenu_page()</code> are used to print custom markup after the dashboard sidebar and floating toolbar have already been generated, the callbacks are too late in WordPress's execution to use the <code>wp_safe_redirect()</code> function. As discussed in the comments, the solution is to move the <code>$wpdb-&gt;update()</code> and <code>wp_safe_redirect()</code> calls outside of your <code>views/edit.php</code> view template and &quot;hook&quot; them to an action that occurs before the HTTP headers are sent (before any HTML is sent to the browser).</p>\n<hr />\n<h2>Solving the Problem</h2>\n<p>Looking at <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"nofollow noreferrer\">the action reference for the typical admin-page request</a>, it's reasonable to assume that the <code>'send_headers'</code> action is the absolute latest that HTTP headers can be reliably modified. So your desired outcome could be achieved by attaching a function to that action or one before it containing your redirect logic - but you'd need to manually check which admin page is being displayed to ensure that you only process the <code>$wpdb-&gt;update()</code> and subsequent redirect for your <code>views/edit.php</code> template.</p>\n<p>Conveniently, WordPress provides a shortcut for this contextual functionality with <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/load-(page)\" rel=\"nofollow noreferrer\">the <code>'load-{page hook}'</code> action</a>, which is dynamically triggered for each admin page loaded. While your call to <code>add_submenu_page()</code> will return the <code>{page hook}</code> value needed to hook an action for execution when your custom templates load, page hooks can be inferred in the format <code>{parent page slug}_page_{child page slug}</code>. Taking the values from your code, then, we end up with the <code>'load-bv_before_afters_main_page_bv_before_afters_edit'</code> action, which will only execute while loading your <code>views/edit.php</code> template.</p>\n<p>The final issue becomes the matter of passing along whether or not <code>$wpdb-&gt;update()</code> produced an error to your <code>views/edit.php</code> template to determine whether or not to display the error message. This could be done using global variables or a custom action, however a better solution is to attach a function that will print your error to the <code>'admin_notices'</code> action which exists for exactly this reason. <code>'admin_notices'</code> will trigger right before WordPress renders your custom view template, ensuring that your error message ends up on the top of the page.</p>\n<blockquote>\n<p><strong>Note</strong></p>\n<p>The <code>$wpdb-&gt;update()</code> method returns the number of rows updated or <code>false</code> if an error is encountered - this means that a successful update query can change no rows and return <code>0</code>, which your <code>if()</code> conditional will lazily evaluate as <code>false</code> and display your error message. For this reason, if you wish to only display your error when the call actually fails, you should compare <code>$wpdb-&gt;update()</code>'s return value against <code>false</code> using the identity comparison operator <code>!==</code>.</p>\n</blockquote>\n<hr />\n<h2>Implementation</h2>\n<p>Combining all of the above, one solution might look as follows. Here I've used an extra array to hold the page slugs for your admin pages for the sake of easy reference, ensuring no typo-related issues and making the slugs easier to change, if necessary.</p>\n<p>The entire portion of the <code>views/edit.php</code> file that you originally posted would now reside in the action hook, as well as any other business logic used to process the edit form.</p>\n<p><strong>Plugin File:</strong></p>\n<pre><code>$bv_admin_page_slugs = [\n 'main' =&gt; 'bv_before_afters_main',\n 'edit' =&gt; 'bv_before_afters_edit',\n 'add' =&gt; 'bv_before_afters_add'\n];\n\nadd_action( 'admin_menu', 'bv_register_admin_pages' );\n\n// Create page in WP Admin\nfunction bv_register_admin_pages() {\n add_menu_page(\n 'Before &amp; After Photos',\n 'Before &amp; Afters',\n 'edit_posts',\n $bv_admin_page_slugs['main'],\n 'bv_before_afters_main',\n 'dashicons-format-gallery',\n 58\n );\n\n add_submenu_page(\n $bv_admin_page_slugs['main'],\n 'Add set',\n 'Add set',\n 'edit_posts',\n $bv_admin_page_slugs['add'],\n 'bv_before_afters_add'\n );\n\n add_submenu_page(\n $bv_admin_page_slugs['main'],\n 'Edit set',\n 'Edit set',\n 'edit_posts',\n $bv_admin_page_slugs['edit'],\n 'bv_before_afters_edit'\n ); \n}\n\n// Process the update/redirect logic whenever the the custom edit page is visited\nadd_action(\n 'load-' . $bv_admin_page_slugs['main'] . '_page_' . $bv_admin_page_slugs['edit'],\n 'bv_update_before_after'\n);\n\n// Performs a redirect on a successful update, adds an error message otherwise\nfunction bv_update_before_after() {\n // Don't process an edit if one was not submitted\n if( /* (An edit was NOT submitted) */ )\n return;\n\n $result = $wpdb-&gt;update( /* (Your Arguments) */ );\n\n if( $result !== false ) {\n wp_safe_redirect('/wp-admin/admin.php?page=' . $bv_admin_page_slugs['main'] . '&amp;updated=1');\n exit;\n }\n else {\n // Tell WordPress to print the error when it usually prints errors\n add_action(\n 'admin_notices',\n function() {\n echo '&lt;div class=&quot;notice notice-error is-dismissible&quot;&gt;&lt;p&gt;Could not be updated!&lt;/p&gt;&lt;/div&gt;';\n }\n );\n } \n}\n\n// Apply stylesheets\nfunction bv_before_afters_styles(){\n wp_enqueue_style( 'bv_before_after_styles', plugins_url( '/bv_before_afters.css', __FILE__ ) );\n}\nadd_action('admin_print_styles', 'bv_before_afters_styles');\n\n// Display the main page\nfunction bv_before_afters_main(){\n include_once plugin_dir_path( __FILE__ ).'/views/view_all.php';\n}\n\n// Display the edit page\nfunction bv_before_afters_edit(){\n include_once plugin_dir_path( __FILE__ ).'/views/edit.php';\n}\n\n// Display the add page\nfunction bv_before_afters_add(){\n include_once plugin_dir_path( __FILE__ ).'/views/add.php';\n}\n</code></pre>\n" }, { "answer_id": 302323, "author": "Anders Lund", "author_id": 142774, "author_profile": "https://wordpress.stackexchange.com/users/142774", "pm_score": 0, "selected": false, "text": "<p>I didn't send any new headers, so had a hard time finding this. </p>\n\n<p>Tried inspecting the DOM. In the top of my DOM, i had a wild comment section standing at the top for some reason, which ruined the rest of the header.</p>\n\n<p>I removed the comment section, which was for some reason rendered at the top of my DOM.</p>\n\n<p>Hope this helps someone else</p>\n" } ]
2016/08/01
[ "https://wordpress.stackexchange.com/questions/233757", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47505/" ]
This is a very common issue, but all the answers I read don't relate to what's happening in my case. I'm writing a custom plugin that reads and writes/updates data to a custom database table (it's very simple). However, when an update is made, I wish to redirect to the main page, and then display a success admin notice on the page. However, when submitting the form, and attempting `wp_safe_redirect` I get the following: > > Warning: Cannot modify header information - headers already sent by > (output started at > C:\wamp64\www\bellavou\wp-includes\formatting.php:4593) in > C:\wamp64\www\bellavou\wp-includes\pluggable.php on line 1167 > > > I don't have any blank spaces in my plugin files, and my call to the redirect, within the `wpdb->update` call looks like this: ``` if($wpdb->update( 'wp_before_after', $bv_before_after_data, array( 'id' => $bv_id ), array( '%s', // value1 '%s', // value2 '%s', // value3 '%d', // value4 '%d', // value5 '%d', // value6 '%d', // value7 '%d', // value8 '%s', // value9 '%s', // value10 '%s', // value11 '%s', // value12 ), array( '%d' ) )) { // Success wp_safe_redirect('/wp-admin/admin.php?page=bv_before_afters_main&amp;updated=1'); } else { // Error echo '<div class="notice notice-error is-dismissible"><p>Could not be updated! (Maybe there was nothing to update?)</p></div>'; } ``` How can I order this correctly so the redirect, and admin notice will work correctly? UPDATE: My main plugin file looks like this (with the includes to other pages): ``` // Create page in WP Admin function my_admin_menu() { add_menu_page( 'Before & After Photos', 'Before & Afters', 'edit_posts', 'bv_before_afters_main', 'bv_before_afters_main', 'dashicons-format-gallery', 58 ); add_submenu_page( 'bv_before_afters_main', 'Add set', 'Add set', 'edit_posts', 'bv_before_afters_add', 'bv_before_afters_add' ); add_submenu_page( 'bv_before_afters_main', 'Edit set', 'Edit set', 'edit_posts', 'bv_before_afters_edit', 'bv_before_afters_edit' ); } add_action( 'admin_menu', 'my_admin_menu' ); // Apply stylesheets function bv_before_afters_styles(){ wp_enqueue_style( 'bv_before_after_styles', plugins_url( '/bv_before_afters.css', __FILE__ ) ); } add_action('admin_print_styles', 'bv_before_afters_styles'); // Display the main page function bv_before_afters_main(){ include_once plugin_dir_path( __FILE__ ).'/views/view_all.php'; } // Display the edit page function bv_before_afters_edit(){ include_once plugin_dir_path( __FILE__ ).'/views/edit.php'; } // Display the add page function bv_before_afters_add(){ include_once plugin_dir_path( __FILE__ ).'/views/add.php'; } ``` (the redirect code is within `edit.php`)
Background ---------- The infamous "**Headers already sent**" error rears it's ugly head in circumstances where something attempts to modify the HTTP headers for the server's response *after* they have already been dispatched to the browser - that is to say, when the server should only be generating the *body* of the response. This often happens in one of two ways: * Code prints things too early before WordPress has finished composing headers - this pushes the HTTP response to the browser and forces the HTTP headers to be dispatched in the process. Any attempts by WordPress or third-party code that would normally properly modify the headers will subsequently produce the error. * Code attempts to alter HTTP headers too late after WordPress has already sent them and begun to render HTML. --- Problem & Solution Overview --------------------------- This instance, the problem is the latter. This is because the `wp_safe_redirect()` function works by setting a `300`-range HTTP status header. Since the callback function arguments for `add_menu_page()` and `add_submenu_page()` are used to print custom markup after the dashboard sidebar and floating toolbar have already been generated, the callbacks are too late in WordPress's execution to use the `wp_safe_redirect()` function. As discussed in the comments, the solution is to move the `$wpdb->update()` and `wp_safe_redirect()` calls outside of your `views/edit.php` view template and "hook" them to an action that occurs before the HTTP headers are sent (before any HTML is sent to the browser). --- Solving the Problem ------------------- Looking at [the action reference for the typical admin-page request](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request), it's reasonable to assume that the `'send_headers'` action is the absolute latest that HTTP headers can be reliably modified. So your desired outcome could be achieved by attaching a function to that action or one before it containing your redirect logic - but you'd need to manually check which admin page is being displayed to ensure that you only process the `$wpdb->update()` and subsequent redirect for your `views/edit.php` template. Conveniently, WordPress provides a shortcut for this contextual functionality with [the `'load-{page hook}'` action](https://codex.wordpress.org/Plugin_API/Action_Reference/load-(page)), which is dynamically triggered for each admin page loaded. While your call to `add_submenu_page()` will return the `{page hook}` value needed to hook an action for execution when your custom templates load, page hooks can be inferred in the format `{parent page slug}_page_{child page slug}`. Taking the values from your code, then, we end up with the `'load-bv_before_afters_main_page_bv_before_afters_edit'` action, which will only execute while loading your `views/edit.php` template. The final issue becomes the matter of passing along whether or not `$wpdb->update()` produced an error to your `views/edit.php` template to determine whether or not to display the error message. This could be done using global variables or a custom action, however a better solution is to attach a function that will print your error to the `'admin_notices'` action which exists for exactly this reason. `'admin_notices'` will trigger right before WordPress renders your custom view template, ensuring that your error message ends up on the top of the page. > > **Note** > > > The `$wpdb->update()` method returns the number of rows updated or `false` if an error is encountered - this means that a successful update query can change no rows and return `0`, which your `if()` conditional will lazily evaluate as `false` and display your error message. For this reason, if you wish to only display your error when the call actually fails, you should compare `$wpdb->update()`'s return value against `false` using the identity comparison operator `!==`. > > > --- Implementation -------------- Combining all of the above, one solution might look as follows. Here I've used an extra array to hold the page slugs for your admin pages for the sake of easy reference, ensuring no typo-related issues and making the slugs easier to change, if necessary. The entire portion of the `views/edit.php` file that you originally posted would now reside in the action hook, as well as any other business logic used to process the edit form. **Plugin File:** ``` $bv_admin_page_slugs = [ 'main' => 'bv_before_afters_main', 'edit' => 'bv_before_afters_edit', 'add' => 'bv_before_afters_add' ]; add_action( 'admin_menu', 'bv_register_admin_pages' ); // Create page in WP Admin function bv_register_admin_pages() { add_menu_page( 'Before & After Photos', 'Before & Afters', 'edit_posts', $bv_admin_page_slugs['main'], 'bv_before_afters_main', 'dashicons-format-gallery', 58 ); add_submenu_page( $bv_admin_page_slugs['main'], 'Add set', 'Add set', 'edit_posts', $bv_admin_page_slugs['add'], 'bv_before_afters_add' ); add_submenu_page( $bv_admin_page_slugs['main'], 'Edit set', 'Edit set', 'edit_posts', $bv_admin_page_slugs['edit'], 'bv_before_afters_edit' ); } // Process the update/redirect logic whenever the the custom edit page is visited add_action( 'load-' . $bv_admin_page_slugs['main'] . '_page_' . $bv_admin_page_slugs['edit'], 'bv_update_before_after' ); // Performs a redirect on a successful update, adds an error message otherwise function bv_update_before_after() { // Don't process an edit if one was not submitted if( /* (An edit was NOT submitted) */ ) return; $result = $wpdb->update( /* (Your Arguments) */ ); if( $result !== false ) { wp_safe_redirect('/wp-admin/admin.php?page=' . $bv_admin_page_slugs['main'] . '&updated=1'); exit; } else { // Tell WordPress to print the error when it usually prints errors add_action( 'admin_notices', function() { echo '<div class="notice notice-error is-dismissible"><p>Could not be updated!</p></div>'; } ); } } // Apply stylesheets function bv_before_afters_styles(){ wp_enqueue_style( 'bv_before_after_styles', plugins_url( '/bv_before_afters.css', __FILE__ ) ); } add_action('admin_print_styles', 'bv_before_afters_styles'); // Display the main page function bv_before_afters_main(){ include_once plugin_dir_path( __FILE__ ).'/views/view_all.php'; } // Display the edit page function bv_before_afters_edit(){ include_once plugin_dir_path( __FILE__ ).'/views/edit.php'; } // Display the add page function bv_before_afters_add(){ include_once plugin_dir_path( __FILE__ ).'/views/add.php'; } ```
233,760
<p>I'm trying get a list of all parent posts, based on a current taxonomy. It seems to work, but the list is repeating 5 times again. </p> <p>This means, when there should be 3 posts in a list, I get 15 posts. Is there something I did wrong with the loop ?</p> <pre><code> &lt;ul&gt; &lt;?php $terms = get_terms('taxonomy-name'); foreach($terms as $term) { $posts = get_posts(array( 'numberposts' =&gt; -1, 'post_type' =&gt; get_post_type(), 'post_parent' =&gt; 0, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'taxonomy-name', 'field' =&gt; 'slug', 'terms' =&gt; 'term-name', ) ), )); foreach($posts as $post) : ?&gt; &lt;li&gt; &lt;?php the_title(); ?&gt; &lt;/li&gt; &lt;?php endforeach; wp_reset_postdata();?&gt; &lt;?php } ?&gt; &lt;/ul&gt; </code></pre> <p>Thank you!</p>
[ { "answer_id": 233764, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p><code>the_title()</code> is a template tag which relies on global state. Specifically <code>$post</code> global variable, holding current post instance.</p>\n\n<p>While you <em>query</em> a set of posts, you never set up that global state for template tag to use.</p>\n\n<p>Though in case you started with <code>get_posts()</code> it might be more convenient to leave global state alone altogether and just use <code>get_the_title()</code>, which can retrieve title of specific post on demand.</p>\n" }, { "answer_id": 233863, "author": "Filip", "author_id": 99035, "author_profile": "https://wordpress.stackexchange.com/users/99035", "pm_score": -1, "selected": false, "text": "<p>thank you for anwer and recommend. I've done some code formation. I'm using dreamweaver, seems to be always a bit messy when working with PHP.</p>\n\n<p>If I'm using <strong>the_post();</strong> instead, I get a loop, which repeats only twice. Better than before, but I think I'm doing something wrong. What do you exactly mean with avoiding the <strong>$post</strong> variable? Is it better to rename the post variable to exclude other conflicts?</p>\n\n<pre><code>&lt;ul&gt;\n &lt;?php\n$terms = get_terms($taxonomy);\nforeach($terms as $term)\n {\n $posts = get_posts(array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; get_post_type() ,\n 'post_parent' =&gt; 0,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; $taxonomy,\n 'field' =&gt; 'slug',\n 'terms' =&gt; custom_taxonomies_terms_links() ,\n )\n ) ,\n ));\n foreach($posts as $post): ?&gt;\n &lt;li&gt;&lt;!--Content here--&gt;&lt;/li&gt;\n\n &lt;?php endforeach; \n the_post(); ?&gt;\n &lt;?php } ?&gt;\n</code></pre>\n\n<p></p>\n\n<p>The <strong>custom_taxonomies_terms_links()</strong> is a way, to get the current term of current taxonomy. </p>\n\n<pre><code>&lt;?php\n\nfunction custom_taxonomies_terms_links()\n {\n global $post, $post_id;\n $post = &amp; get_post($post-&gt;ID);\n $post_type = $post-&gt;post_type;\n\n $taxonomies = get_object_taxonomies($post_type);\n foreach($taxonomies as $taxonomy)\n {\n $terms = get_the_terms($post-&gt;ID, $taxonomy);\n if (!empty($terms))\n {\n foreach($terms as $term) $out.= $term-&gt;name;\n }\n }\n\n return $out;\n } ?&gt;\n</code></pre>\n\n<p>Actually, I'm not sure, if this is the best or elegant way to do it like this.</p>\n" } ]
2016/08/01
[ "https://wordpress.stackexchange.com/questions/233760", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99035/" ]
I'm trying get a list of all parent posts, based on a current taxonomy. It seems to work, but the list is repeating 5 times again. This means, when there should be 3 posts in a list, I get 15 posts. Is there something I did wrong with the loop ? ``` <ul> <?php $terms = get_terms('taxonomy-name'); foreach($terms as $term) { $posts = get_posts(array( 'numberposts' => -1, 'post_type' => get_post_type(), 'post_parent' => 0, 'tax_query' => array( array( 'taxonomy' => 'taxonomy-name', 'field' => 'slug', 'terms' => 'term-name', ) ), )); foreach($posts as $post) : ?> <li> <?php the_title(); ?> </li> <?php endforeach; wp_reset_postdata();?> <?php } ?> </ul> ``` Thank you!
`the_title()` is a template tag which relies on global state. Specifically `$post` global variable, holding current post instance. While you *query* a set of posts, you never set up that global state for template tag to use. Though in case you started with `get_posts()` it might be more convenient to leave global state alone altogether and just use `get_the_title()`, which can retrieve title of specific post on demand.
233,765
<p>In the "posts -> all posts" admin page, I would like to search and see only posts with some element in their url (for example, the character "-3" to indicate they are a duplicate post).</p> <p>How can this be done?</p>
[ { "answer_id": 233773, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 1, "selected": false, "text": "<p>You can't really perform that kind of query from the admin UI without explicitly coding it in a theme or plugin. If you're looking to find all posts ending with <code>-3</code> in their name, I suggest running an SQL query, perhaps couple it with some WP-CLI magic too:</p>\n\n<pre><code>wp post list --fields=url --post__in=$(wp db query \"SELECT ID FROM wp_posts WHERE post_name LIKE '%-3';\" | paste -s -d,)\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 233781, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Here's one way to support searching for <strong>post slugs</strong> in the backend. </p>\n\n<p>Let's invoke this kind of search by the <code>slug:</code> string in the search term. </p>\n\n<p><strong>Example</strong></p>\n\n<p>To search for slugs that end in <code>-2</code> we want to be able to search for:</p>\n\n<pre><code>slug:*-2\n</code></pre>\n\n<p>where * is the wildcard.</p>\n\n<p><strong>Demo Plugin</strong></p>\n\n<p>Here's a demo plugin that might need further testing and adjustments:</p>\n\n<pre><code>add_filter( 'posts_search', function( $search, \\WP_Query $q ) use ( &amp;$wpdb )\n{\n // Nothing to do\n if( \n ! did_action( 'load-edit.php' ) \n || ! is_admin() \n || ! $q-&gt;is_search() \n || ! $q-&gt;is_main_query() \n )\n return $search;\n\n // Get the search input\n $s = $q-&gt;get( 's' );\n\n // Check for \"slug:\" part in the search input\n if( 'slug:' === mb_substr( trim( $s ), 0, 5 ) )\n {\n // Override the search query \n $search = $wpdb-&gt;prepare(\n \" AND {$wpdb-&gt;posts}.post_name LIKE %s \",\n str_replace( \n [ '**', '*' ], \n [ '*', '%' ], \n mb_strtolower( \n $wpdb-&gt;esc_like( \n trim( mb_substr( $s, 5 ) ) \n ) \n )\n )\n );\n\n // Adjust the ordering\n $q-&gt;set('orderby', 'post_name' );\n $q-&gt;set('order', 'ASC' );\n }\n return $search;\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p><em>This is based on the <code>_name__like</code> plugin in my previous answer <a href=\"https://wordpress.stackexchange.com/a/136758/26350\">here</a>.</em></p>\n" }, { "answer_id": 405277, "author": "Pranavmtn", "author_id": 181471, "author_profile": "https://wordpress.stackexchange.com/users/181471", "pm_score": 0, "selected": false, "text": "<p>Or you can go to your mysql database ,Use the search option to find for <strong>wp_posts</strong> posts table in the column <strong>post_name</strong></p>\n<p>And perform a search!</p>\n<p>Screenshot :<a href=\"https://prnt.sc/SDQ3QZL1kyZ1\" rel=\"nofollow noreferrer\">https://prnt.sc/SDQ3QZL1kyZ1</a></p>\n<p></p>\n" } ]
2016/08/01
[ "https://wordpress.stackexchange.com/questions/233765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161/" ]
In the "posts -> all posts" admin page, I would like to search and see only posts with some element in their url (for example, the character "-3" to indicate they are a duplicate post). How can this be done?
Here's one way to support searching for **post slugs** in the backend. Let's invoke this kind of search by the `slug:` string in the search term. **Example** To search for slugs that end in `-2` we want to be able to search for: ``` slug:*-2 ``` where \* is the wildcard. **Demo Plugin** Here's a demo plugin that might need further testing and adjustments: ``` add_filter( 'posts_search', function( $search, \WP_Query $q ) use ( &$wpdb ) { // Nothing to do if( ! did_action( 'load-edit.php' ) || ! is_admin() || ! $q->is_search() || ! $q->is_main_query() ) return $search; // Get the search input $s = $q->get( 's' ); // Check for "slug:" part in the search input if( 'slug:' === mb_substr( trim( $s ), 0, 5 ) ) { // Override the search query $search = $wpdb->prepare( " AND {$wpdb->posts}.post_name LIKE %s ", str_replace( [ '**', '*' ], [ '*', '%' ], mb_strtolower( $wpdb->esc_like( trim( mb_substr( $s, 5 ) ) ) ) ) ); // Adjust the ordering $q->set('orderby', 'post_name' ); $q->set('order', 'ASC' ); } return $search; }, PHP_INT_MAX, 2 ); ``` *This is based on the `_name__like` plugin in my previous answer [here](https://wordpress.stackexchange.com/a/136758/26350).*
233,780
<p>I am trying to figure out to fire a hook for a custom post type called "bananas" when a new bananas post is published.</p> <p>Requirements:</p> <ul> <li>Can't use $_POST </li> <li>Need to be able to get post statuses so I can prevent code from running again later and check if its already published</li> <li>Need to be able to get_post_meta</li> </ul> <p>The action hook is working perfectly. The only issue is that NEW post can't seem to get_post_meta. If you go from pending to publish or vice versa getting the meta works. But getting the meta on new post does not work and returns an empty result.</p> <p>Heres an example of what I am trying to do.</p> <pre><code>class bananas { public function __construct() { add_action( 'transition_post_status', array( $this, 'email_bananas_published' ), 10, 3 ); } public function email_bananas_published( $new_status, $old_status, $post ) { if ( $post-&gt;post_type === 'bananas' &amp;&amp; $new_status !== $old_status ) { $email = get_post_meta( $post-&gt;ID, '_bananas_email', true ); error_log( $email ); } } } </code></pre> <p>I have been stuck on this for a while and any help is much appreciated.</p>
[ { "answer_id": 233785, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 0, "selected": false, "text": "<p>Have you checked <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_post\" rel=\"nofollow\">wp_insert_post</a> hook in the codex?</p>\n\n<p>I believe this is what you are looking for. (untested)</p>\n\n<pre><code>class bananas {\n\n public function __construct() {\n add_action( 'wp_insert_post', array( $this, 'email_bananas_published' ), 10, 3 );\n }\n\n\n public function email_bananas_published( $post_id, $post, $update ) {\n\n // If this is a revision, don't send the email.\n if ( wp_is_post_revision( $post_id ) || $update )\n return;\n\n\n if ( $post-&gt;post_type === 'bananas' &amp;&amp; $post-&gt;post_status === 'publish' ) {\n $email = get_post_meta( $post_id, '_bananas_email', true );\n error_log( $email );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 321313, "author": "Palmer Del Campo", "author_id": 73459, "author_profile": "https://wordpress.stackexchange.com/users/73459", "pm_score": 2, "selected": false, "text": "<p>The following worked for me. I hooked my meta saving and retrieving to the same action (post_transition_status), but with different priorities.</p>\n\n<pre><code>//Save Your Custom Meta Meta, but hook it to transition_post_status instead of save_post, with a priority of 1\nfunction save_yourpost_meta(){\n global $post;\n if($post -&gt; post_type == 'your_post_type') {\n update_post_meta($post-&gt;ID, \"your_meta_key\", $_POST[\"your_meta_key\"]);\n }\n }\nadd_action('transition_post_status', 'save_yourpost_meta',1,1);\n\n\n//Then retrieve your custom meta only when the post is saved for the first time, not on updates. Hooked to the same action, with a lower priority of 100\n\nfunction get_meta_on_publish($new_status, $old_status, $post) {\nif('publish' == $new_status &amp;&amp; 'publish' !== $old_status &amp;&amp; $post-&gt;post_type == 'your_post_type') {\n //Get your meta info\n global $post;\n $postID = $post-&gt;ID;\n $custom = get_post_custom($postID);\n //You have your custom now, have fun.\n\n }\n}\nadd_action('transition_post_status', 'get_meta_on_publish',100,3);\n</code></pre>\n\n<p>I hope this helps!</p>\n" } ]
2016/08/01
[ "https://wordpress.stackexchange.com/questions/233780", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49017/" ]
I am trying to figure out to fire a hook for a custom post type called "bananas" when a new bananas post is published. Requirements: * Can't use $\_POST * Need to be able to get post statuses so I can prevent code from running again later and check if its already published * Need to be able to get\_post\_meta The action hook is working perfectly. The only issue is that NEW post can't seem to get\_post\_meta. If you go from pending to publish or vice versa getting the meta works. But getting the meta on new post does not work and returns an empty result. Heres an example of what I am trying to do. ``` class bananas { public function __construct() { add_action( 'transition_post_status', array( $this, 'email_bananas_published' ), 10, 3 ); } public function email_bananas_published( $new_status, $old_status, $post ) { if ( $post->post_type === 'bananas' && $new_status !== $old_status ) { $email = get_post_meta( $post->ID, '_bananas_email', true ); error_log( $email ); } } } ``` I have been stuck on this for a while and any help is much appreciated.
The following worked for me. I hooked my meta saving and retrieving to the same action (post\_transition\_status), but with different priorities. ``` //Save Your Custom Meta Meta, but hook it to transition_post_status instead of save_post, with a priority of 1 function save_yourpost_meta(){ global $post; if($post -> post_type == 'your_post_type') { update_post_meta($post->ID, "your_meta_key", $_POST["your_meta_key"]); } } add_action('transition_post_status', 'save_yourpost_meta',1,1); //Then retrieve your custom meta only when the post is saved for the first time, not on updates. Hooked to the same action, with a lower priority of 100 function get_meta_on_publish($new_status, $old_status, $post) { if('publish' == $new_status && 'publish' !== $old_status && $post->post_type == 'your_post_type') { //Get your meta info global $post; $postID = $post->ID; $custom = get_post_custom($postID); //You have your custom now, have fun. } } add_action('transition_post_status', 'get_meta_on_publish',100,3); ``` I hope this helps!
233,793
<p>i'm currently using this code to display a custom tag:</p> <pre><code>&lt;?php echo get_the_term_list( $post-&gt;ID, 'region', 'Region: ', ', ', '&lt;br&gt;' ); ?&gt; </code></pre> <p>The output of this looks like this:</p> <pre><code>Region: USA </code></pre> <p>What i want to do is display a flag instead of the words USA, EUR, JPN, etc like so:</p> <p>Region: <a href="https://i.stack.imgur.com/B2K4X.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B2K4X.gif" alt="enter image description here"></a></p> <p>What's the easiest way to achieve this? In the past i used a very bloated method but i want to know an efficient way to do this, old method:</p> <pre><code>$posttags = get_the_tags(); // Get articles tags $home = get_bloginfo('url'); // Get homepage URL // Check tagslug.png exists and display it echo '&lt;div class="entry-meta"&gt;&lt;span class="tag-links"&gt;'; if ($posttags) { foreach($posttags as $tag) { $image = "/img/$tag-&gt;slug.gif"; if (file_exists("img/$tag-&gt;slug.gif")) { echo '&lt;a href="' . $home . '/tag/' . $tag-&gt;slug . '/"&gt;Region:&lt;img title="' . $tag-&gt;name . '" alt="' . $tag-&gt;name . '" src="' . $image . '"&gt;&lt;/a&gt;'; // If no image found, output no flag version } else { echo '&lt;a href="' . $home . '/tag/' . $tag-&gt;slug . '/"&gt;' . $tag-&gt;name . '&lt;/a&gt;'; } } } echo "&lt;/span&gt;"; echo "&lt;/div&gt;"; </code></pre>
[ { "answer_id": 233797, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 3, "selected": true, "text": "<p>A clean and semantic way to do it would be with CSS.</p>\n\n<p>First, the PHP:</p>\n\n<pre><code>&lt;div class=\"entry-meta\"&gt;\n &lt;span class=\"term-links\"&gt;\n &lt;?php foreach ( get_the_terms( $post-&gt;ID, 'region') as $term ) : ?&gt;\n &lt;a href=\"&lt;?php echo esc_url( get_term_link( $term-&gt;term_id ) ) ?&gt;\"&gt;Region: &lt;span class=\"&lt;?php echo $term-&gt;slug ?&gt;\"&gt;&lt;?php echo $term-&gt;name ?&gt;&lt;/span&gt;&lt;/a&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Next, the CSS:</p>\n\n<pre><code>.term-links .usa {\n display: inline-block;\n width: 16px;\n height: 11px;\n background: url('http://i.stack.imgur.com/B2K4X.gif');\n text-indent: 100%;\n white-space: nowrap;\n overflow: hidden;\n}\n</code></pre>\n\n<p>Just repeat the CSS for each region, changing the background URL.</p>\n" }, { "answer_id": 233882, "author": "Mike Eng", "author_id": 7313, "author_profile": "https://wordpress.stackexchange.com/users/7313", "pm_score": 2, "selected": false, "text": "<p>I'm assuming you want a comma-separated list of terms with links. Here's PHP to output that:</p>\n\n<pre><code>$post_regions = get_the_terms($post-&gt;ID,'regions');\n\n//determines what the last region is so we know when to stop inserting commas between multiple regions\n$region_keys = array_keys($post_regions);\n$last_region_key = array_pop($region_keys);\n\necho('Region: ');\nforeach ($post_regions as $key =&gt; $value) {\n echo('&lt;a href=\"'.esc_url(get_tag_link($value-&gt;term_id)).'\" class=\"'.$value-&gt;name.'\" &gt;'.$value-&gt;name.'&lt;/a&gt;');\n //only insert a comma between if it's not the last region\n if ($key != $last_region_key){\n echo(', ');\n }\n }\n</code></pre>\n\n<p>It should end up with the following HTML, depending on the actual terms on the post of course:</p>\n\n<pre><code>Region: &lt;a href=\"#\" rel=\"tag\" class=\"USA\"&gt;USA&lt;/a&gt;, \n&lt;a href=\"#\" rel=\"tag\" class=\"EUR\"&gt;EUR&lt;/a&gt;, \n&lt;a href=\"#\" rel=\"tag\" class=\"JPN\"&gt;JPN&lt;/a&gt;, \n&lt;a href=\"#\" rel=\"tag\" class=\"Antarctica\"&gt;Antarctica&lt;/a&gt;\n</code></pre>\n\n<p>And you can style it with CSS. <a href=\"http://sass-lang.com/documentation/file.SASS_REFERENCE.html#each-directive\" rel=\"nofollow\">Using Sass, you can save yourself the duplication of writing a declaration for each region using the each directive</a> like so:</p>\n\n<pre><code>@each $flag in USA, EUR, JPN {\n\n a.#{$flag} {\n display:inline-block;\n overflow:hidden;\n width:0;\n height:11px;\n padding-left:16px;\n background:url('REPLACE-WITH-YOUR-PATH-TO-IMAGES/#{$flag}.gif');\n }\n}\n</code></pre>\n\n<p><a href=\"https://codepen.io/mrengy/pen/GqXqgV\" rel=\"nofollow\">Live demo on Codepen</a>. It will ignore any region names you don't specify in the SCSS and display the text for those, but for those it recognizes, it will hide the text and display the flag image instead. If you don't want to deal with Sass, you can change the option under CSS in Codepen to display the compiled CSS and use that instead. </p>\n" } ]
2016/08/02
[ "https://wordpress.stackexchange.com/questions/233793", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
i'm currently using this code to display a custom tag: ``` <?php echo get_the_term_list( $post->ID, 'region', 'Region: ', ', ', '<br>' ); ?> ``` The output of this looks like this: ``` Region: USA ``` What i want to do is display a flag instead of the words USA, EUR, JPN, etc like so: Region: [![enter image description here](https://i.stack.imgur.com/B2K4X.gif)](https://i.stack.imgur.com/B2K4X.gif) What's the easiest way to achieve this? In the past i used a very bloated method but i want to know an efficient way to do this, old method: ``` $posttags = get_the_tags(); // Get articles tags $home = get_bloginfo('url'); // Get homepage URL // Check tagslug.png exists and display it echo '<div class="entry-meta"><span class="tag-links">'; if ($posttags) { foreach($posttags as $tag) { $image = "/img/$tag->slug.gif"; if (file_exists("img/$tag->slug.gif")) { echo '<a href="' . $home . '/tag/' . $tag->slug . '/">Region:<img title="' . $tag->name . '" alt="' . $tag->name . '" src="' . $image . '"></a>'; // If no image found, output no flag version } else { echo '<a href="' . $home . '/tag/' . $tag->slug . '/">' . $tag->name . '</a>'; } } } echo "</span>"; echo "</div>"; ```
A clean and semantic way to do it would be with CSS. First, the PHP: ``` <div class="entry-meta"> <span class="term-links"> <?php foreach ( get_the_terms( $post->ID, 'region') as $term ) : ?> <a href="<?php echo esc_url( get_term_link( $term->term_id ) ) ?>">Region: <span class="<?php echo $term->slug ?>"><?php echo $term->name ?></span></a> <?php endforeach; ?> </span> </div> ``` Next, the CSS: ``` .term-links .usa { display: inline-block; width: 16px; height: 11px; background: url('http://i.stack.imgur.com/B2K4X.gif'); text-indent: 100%; white-space: nowrap; overflow: hidden; } ``` Just repeat the CSS for each region, changing the background URL.
233,841
<p>So I have a Custom Post Type with some Custom Taxonomies.</p> <p>On the <code>archive</code> page where I list all the Custom Post Types I have an refine search in the sidebar which allows you to tick a Taxonomy Term and then search for Post Types with that Term. (Image Below)</p> <p><a href="https://i.stack.imgur.com/BIe6p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BIe6p.png" alt="Redefine Search"></a></p> <p>When you click say 'Cellar' it reloads the page and shows you the result (in this instance it's only one Post Type)</p> <p>My question is: How do I update the numbers on the side of the names so if 'Cellar' is checked then the number next to 'Carpet' should update to say <code>(1)</code> because there is only 1 property with the 'Cellar' and 'Carpet' term together</p> <p>Here is the code controlling the output of the number but at the moment this is just static and is just count every Post Type with that term.</p> <pre><code>&lt;?php $all_features = get_terms('features'); /* Features in search query */ $required_features_slugs = array(); if( isset ( $_GET['features'] ) ) { $required_features_slugs = $_GET['features']; } $features_count = count ($all_features); if($features_count &gt; 0) { ?&gt; &lt;div class="more-options-wrapper clearfix"&gt; &lt;?php foreach ($all_features as $feature ) { ?&gt; &lt;div class="option-bar"&gt; &lt;input type="checkbox" id="feature-&lt;?php echo $feature-&gt;slug; ?&gt;" name="features[]" value="&lt;?php echo $feature-&gt;slug; ?&gt;" onclick="document.getElementById('refine-properties').submit();" &lt;?php if ( in_array( $feature-&gt;slug, $required_features_slugs ) ) { echo 'checked'; } ?&gt; /&gt; &lt;label for="feature-&lt;?php echo $feature-&gt;slug; ?&gt;"&gt;&lt;?php echo $feature-&gt;name; ?&gt; &lt;small&gt;(&lt;?php echo $feature-&gt;count; ?&gt;)&lt;/small&gt;&lt;/label&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I have put an example below:</p> <p><a href="https://i.stack.imgur.com/GAQiw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GAQiw.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/8z8lL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8z8lL.png" alt="enter image description here"></a></p> <p>The Images above represent what I am trying to do</p>
[ { "answer_id": 233871, "author": "Newtype", "author_id": 99352, "author_profile": "https://wordpress.stackexchange.com/users/99352", "pm_score": 1, "selected": false, "text": "<p>I have solved this. I just needed to add a title to the custom link in the options BEFORE adding it to the menu. How stupid is that?</p>\n" }, { "answer_id": 363477, "author": "Eje", "author_id": 149290, "author_profile": "https://wordpress.stackexchange.com/users/149290", "pm_score": 0, "selected": false, "text": "<blockquote>\n <ol>\n <li><p>Disable all plugins. Update your nav. If it works then we know a plugin is the cause.</p></li>\n <li><p>Switch to a theme by team WordPress (eg. TwentyTwenty). Update your nav. If it works then we know the theme is the cause.</p></li>\n <li><p>Switch to a different browser. Update your nav. If it works then a browser incompatibility issue or browser extension/plugin is the\n cause.</p></li>\n </ol>\n \n <p><a href=\"https://wordpress.org/support/topic/add-to-menu-now-not-working/#post-9522382\" rel=\"nofollow noreferrer\">Source</a></p>\n</blockquote>\n\n<p>In my case, solution #1 worked.</p>\n" } ]
2016/08/02
[ "https://wordpress.stackexchange.com/questions/233841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85776/" ]
So I have a Custom Post Type with some Custom Taxonomies. On the `archive` page where I list all the Custom Post Types I have an refine search in the sidebar which allows you to tick a Taxonomy Term and then search for Post Types with that Term. (Image Below) [![Redefine Search](https://i.stack.imgur.com/BIe6p.png)](https://i.stack.imgur.com/BIe6p.png) When you click say 'Cellar' it reloads the page and shows you the result (in this instance it's only one Post Type) My question is: How do I update the numbers on the side of the names so if 'Cellar' is checked then the number next to 'Carpet' should update to say `(1)` because there is only 1 property with the 'Cellar' and 'Carpet' term together Here is the code controlling the output of the number but at the moment this is just static and is just count every Post Type with that term. ``` <?php $all_features = get_terms('features'); /* Features in search query */ $required_features_slugs = array(); if( isset ( $_GET['features'] ) ) { $required_features_slugs = $_GET['features']; } $features_count = count ($all_features); if($features_count > 0) { ?> <div class="more-options-wrapper clearfix"> <?php foreach ($all_features as $feature ) { ?> <div class="option-bar"> <input type="checkbox" id="feature-<?php echo $feature->slug; ?>" name="features[]" value="<?php echo $feature->slug; ?>" onclick="document.getElementById('refine-properties').submit();" <?php if ( in_array( $feature->slug, $required_features_slugs ) ) { echo 'checked'; } ?> /> <label for="feature-<?php echo $feature->slug; ?>"><?php echo $feature->name; ?> <small>(<?php echo $feature->count; ?>)</small></label> </div> <?php } ?> </div> <?php } ?> ``` I have put an example below: [![enter image description here](https://i.stack.imgur.com/GAQiw.png)](https://i.stack.imgur.com/GAQiw.png) [![enter image description here](https://i.stack.imgur.com/8z8lL.png)](https://i.stack.imgur.com/8z8lL.png) The Images above represent what I am trying to do
I have solved this. I just needed to add a title to the custom link in the options BEFORE adding it to the menu. How stupid is that?
233,878
<p>I'm trying to count the number of live comments on each post. I would like to extract them on a custom page like <code>http://example.com/count.php</code> and have them output like this:</p> <pre><code>http://example.com/the-post-url-with-3-comments/ 3 http://example.com/the-post-url-with-no-comments/ 0 http://example.com/the-post-url-with-12-comments/ 12 </code></pre> <p>The spacing between all the posts don't matter quite as much, I just need the two columns with all my posts and number of approved comments. </p> <p>I have come close to doing this with <a href="https://wordpress.stackexchange.com/questions/99264/cant-show-comments-count-per-post-outside-loop">this post</a> and using <code>echo get_comment_count( 149 );</code> but it only uses one post at a time. I would like to extract all the posts.</p> <p>Thanks for your help.</p>
[ { "answer_id": 233859, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>It is totally essential to use <code>utf8mb4</code> for your site to be secure and bug free in all wordpress versions since 4.2 and probably before that. You need to upgrade your mysql software to a newer version, or change whatever is need in its configuration to support it.</p>\n" }, { "answer_id": 233861, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 1, "selected": false, "text": "<p>Mark is right, if your host does not support utf8mb4 you should not use them.</p>\n\n<p>However, you can run a search-and-replace inside your import file, look for \"utf8mb4\" and replace with \"utf8\". Note that this will not increase the index sizes meant to fit multibyte characters, and will also likely still fail (probably silently by stripping contents) on import if any of your post content contains multibyte characters, such as emoji .</p>\n" } ]
2016/08/02
[ "https://wordpress.stackexchange.com/questions/233878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99382/" ]
I'm trying to count the number of live comments on each post. I would like to extract them on a custom page like `http://example.com/count.php` and have them output like this: ``` http://example.com/the-post-url-with-3-comments/ 3 http://example.com/the-post-url-with-no-comments/ 0 http://example.com/the-post-url-with-12-comments/ 12 ``` The spacing between all the posts don't matter quite as much, I just need the two columns with all my posts and number of approved comments. I have come close to doing this with [this post](https://wordpress.stackexchange.com/questions/99264/cant-show-comments-count-per-post-outside-loop) and using `echo get_comment_count( 149 );` but it only uses one post at a time. I would like to extract all the posts. Thanks for your help.
It is totally essential to use `utf8mb4` for your site to be secure and bug free in all wordpress versions since 4.2 and probably before that. You need to upgrade your mysql software to a newer version, or change whatever is need in its configuration to support it.
233,886
<p>I am making a Wordpress theme with a custom admin page. What I did to make it save the settings was this:</p> <pre><code>&lt;form method="post" action="options.php"&gt; </code></pre> <p>When I hit the submit button, I got an error message saying that "options.php" was not found. I attempted to change the general settings and it worked. It was just with my settings page.</p> <p>Thanks!</p> <p>EDIT: I just found something on the <a href="https://codex.wordpress.org/Function_Reference/register_setting" rel="nofollow">Codex</a> about this. But I have no idea what it means. It is at the "Notes" section. If someone could help that would be great!</p> <p>My code:<a href="http://pastebin.com/bvXcXhCQ" rel="nofollow">http://pastebin.com/bvXcXhCQ</a></p>
[ { "answer_id": 233896, "author": "Shrikant D", "author_id": 74746, "author_profile": "https://wordpress.stackexchange.com/users/74746", "pm_score": 0, "selected": false, "text": "<p>Replace your form code as:</p>\n\n<p><code>&lt;form name=\"form1\" method=\"POST\" action=\"options.php\"&gt;</code></p>\n\n<p>Type is not a Form attribute. To know more form attribute please see: <a href=\"http://www.tutorialspoint.com/html/html_form_tag.htm\" rel=\"nofollow\">From attribute</a></p>\n" }, { "answer_id": 233928, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 1, "selected": false, "text": "<p>Your question lacks a lot of details which could clarify the source of the problem. For example, this error could be also triggered by a wrong call to an <code>add_settings_field</code> function or how <code>settings_fields</code> looks there. These things are essential.</p>\n\n<p>I could try a blind shot and believe that the <a href=\"https://codex.wordpress.org/Function_Reference/register_setting\" rel=\"nofollow\">register_setting</a> function has a different <code>$option_group</code> than <code>$option_name</code>. Try to make the first two parameters to be exactly the same.</p>\n\n<p>Also, you need to take care of your fields. <a href=\"https://codex.wordpress.org/Function_Reference/add_settings_field\" rel=\"nofollow\">add_settings_field</a> those params must match the <code>register_setting</code> ones</p>\n\n<p>Now if you are really unlucky you could have a problem with <code>whitelist_options</code> filter or some plugin you have installed may crash this.</p>\n\n<p>Personally, I've written a <a href=\"http://andrei-lupu.com/programming/error-options-page-not-found/\" rel=\"nofollow\">story</a> about how I've got this error and how I've solved it, but it was an isolated case</p>\n" }, { "answer_id": 234967, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 1, "selected": true, "text": "<p>Like @LupuAndrei said, we lack of details, especially the code where you call you form from.</p>\n\n<p>But I suspect, again like @LupuAndrei said, you might not be calling the <code>settings_fields</code>, <code>do_settings_fields</code> or <code>do_settings_sections</code> correctly.</p>\n\n<p>On the function where you build your form, try something like this</p>\n\n<pre><code>&lt;form method=\"post\" action=\"options.php\"&gt;\n &lt;table class=\"form-table\"&gt;\n &lt;?php \n\n settings_fields( 'animated-settings-group' ); // This will output the nonce, action, and option_page fields for a settings page.\n do_settings_sections( 'hoogleyboogley_animated' ); // This prints out the actual sections containing the settings fields for the page in parameter \n\n ?&gt;\n &lt;/table&gt;\n\n &lt;?php submit_button(); ?&gt;\n&lt;/form&gt;\n</code></pre>\n" } ]
2016/08/03
[ "https://wordpress.stackexchange.com/questions/233886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99390/" ]
I am making a Wordpress theme with a custom admin page. What I did to make it save the settings was this: ``` <form method="post" action="options.php"> ``` When I hit the submit button, I got an error message saying that "options.php" was not found. I attempted to change the general settings and it worked. It was just with my settings page. Thanks! EDIT: I just found something on the [Codex](https://codex.wordpress.org/Function_Reference/register_setting) about this. But I have no idea what it means. It is at the "Notes" section. If someone could help that would be great! My code:<http://pastebin.com/bvXcXhCQ>
Like @LupuAndrei said, we lack of details, especially the code where you call you form from. But I suspect, again like @LupuAndrei said, you might not be calling the `settings_fields`, `do_settings_fields` or `do_settings_sections` correctly. On the function where you build your form, try something like this ``` <form method="post" action="options.php"> <table class="form-table"> <?php settings_fields( 'animated-settings-group' ); // This will output the nonce, action, and option_page fields for a settings page. do_settings_sections( 'hoogleyboogley_animated' ); // This prints out the actual sections containing the settings fields for the page in parameter ?> </table> <?php submit_button(); ?> </form> ```
233,900
<p>I am in the process of adding an additional column to the Users admin screen to display the company for each user. I have been successful in getting this column to show in the table, but I am really struggling with making it sortable alphabetically.</p> <p>The column header does seem to be activated as sortable, but if i click it to reorganise the list order, the table actually rearranges alphabetically based on the username as opposed to the company.</p> <p>I have spent alot of time on the web looking for and adapting other solutions, but still no luck. I have seen plenty of examples of making custom columns sortable for post type admins screens but not the user admin screen.</p> <p>Below is the code I am currently using to generate a "Company" column on the users admin screen and it is pulling in the author meta data "company".</p> <pre><code>//MAKE THE COLUMN SORTABLE function user_sortable_columns( $columns ) { $columns['company'] = 'Company'; return $columns; } add_filter( 'manage_users_sortable_columns', 'user_sortable_columns' ); add_action( "pre_get_users", function ( $WP_User_Query ) { if ( isset( $WP_User_Query-&gt;query_vars["orderby"] ) &amp;&amp; ( "company" === $WP_User_Query-&gt;query_vars["orderby"] ) ) { $WP_User_Query-&gt;query_vars["meta_key"] = "company_name"; $WP_User_Query-&gt;query_vars["orderby"] = "meta_value"; } }, 10, 1 ); </code></pre>
[ { "answer_id": 233918, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 2, "selected": false, "text": "<p>the action <code>request</code> works with post. for user it's <code>pre_get_users</code> : </p>\n\n<pre><code>add_action(\"pre_get_users\", function ($WP_User_Query) {\n\n if ( isset($WP_User_Query-&gt;query_vars[\"orderby\"])\n &amp;&amp; (\"company\" === $WP_User_Query-&gt;query_vars[\"orderby\"])\n ) {\n $WP_User_Query-&gt;query_vars[\"meta_key\"] = \"company_name\";\n $WP_User_Query-&gt;query_vars[\"orderby\"] = \"meta_value\";\n }\n\n}, 10, 1);\n</code></pre>\n" }, { "answer_id": 294767, "author": "ban-geoengineering", "author_id": 44498, "author_profile": "https://wordpress.stackexchange.com/users/44498", "pm_score": 3, "selected": false, "text": "<p>This is my code which adds a sortable custom column (called <strong>Vendor ID</strong>) to the users table:</p>\n\n<pre><code>function fc_new_modify_user_table( $column ) {\n $column['vendor_id'] = 'Vendor ID';\n return $column;\n}\nadd_filter( 'manage_users_columns', 'fc_new_modify_user_table' );\n\nfunction fc_new_modify_user_table_row( $val, $column_name, $user_id ) {\n switch ($column_name) {\n case 'vendor_id' :\n return get_the_author_meta( 'vendor_id', $user_id );\n default:\n }\n return $val;\n}\nadd_filter( 'manage_users_custom_column', 'fc_new_modify_user_table_row', 10, 3 );\n\nfunction fc_my_sortable_cake_column( $columns ) {\n $columns['vendor_id'] = 'Vendor ID';\n\n //To make a column 'un-sortable' remove it from the array unset($columns['date']);\n\n return $columns;\n}\nadd_filter( 'manage_users_sortable_columns', 'fc_my_sortable_cake_column' );\n</code></pre>\n\n<p>Simple and works fine for me.</p>\n" } ]
2016/08/03
[ "https://wordpress.stackexchange.com/questions/233900", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91798/" ]
I am in the process of adding an additional column to the Users admin screen to display the company for each user. I have been successful in getting this column to show in the table, but I am really struggling with making it sortable alphabetically. The column header does seem to be activated as sortable, but if i click it to reorganise the list order, the table actually rearranges alphabetically based on the username as opposed to the company. I have spent alot of time on the web looking for and adapting other solutions, but still no luck. I have seen plenty of examples of making custom columns sortable for post type admins screens but not the user admin screen. Below is the code I am currently using to generate a "Company" column on the users admin screen and it is pulling in the author meta data "company". ``` //MAKE THE COLUMN SORTABLE function user_sortable_columns( $columns ) { $columns['company'] = 'Company'; return $columns; } add_filter( 'manage_users_sortable_columns', 'user_sortable_columns' ); add_action( "pre_get_users", function ( $WP_User_Query ) { if ( isset( $WP_User_Query->query_vars["orderby"] ) && ( "company" === $WP_User_Query->query_vars["orderby"] ) ) { $WP_User_Query->query_vars["meta_key"] = "company_name"; $WP_User_Query->query_vars["orderby"] = "meta_value"; } }, 10, 1 ); ```
This is my code which adds a sortable custom column (called **Vendor ID**) to the users table: ``` function fc_new_modify_user_table( $column ) { $column['vendor_id'] = 'Vendor ID'; return $column; } add_filter( 'manage_users_columns', 'fc_new_modify_user_table' ); function fc_new_modify_user_table_row( $val, $column_name, $user_id ) { switch ($column_name) { case 'vendor_id' : return get_the_author_meta( 'vendor_id', $user_id ); default: } return $val; } add_filter( 'manage_users_custom_column', 'fc_new_modify_user_table_row', 10, 3 ); function fc_my_sortable_cake_column( $columns ) { $columns['vendor_id'] = 'Vendor ID'; //To make a column 'un-sortable' remove it from the array unset($columns['date']); return $columns; } add_filter( 'manage_users_sortable_columns', 'fc_my_sortable_cake_column' ); ``` Simple and works fine for me.
233,903
<p>When I run &quot;themes check&quot; , it recommends not to use CDN. I am using Bootstrap CDN this way</p> <pre><code>function underscore_bootstrap_wp_scripts() { /* bootstrap and font awesome and animate css */ wp_enqueue_style( 'bootstrap_cdn', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' ); wp_enqueue_style( 'fontawesome_cdn', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); /* default underscores styles */ wp_enqueue_style( 'underscore_bootstrap_wp-style', get_stylesheet_uri() ); /* bootstrap js */ wp_enqueue_script('bootstrap_js_cdn', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js',array('jquery'),'',true); /* default underscores js */ //wp_enqueue_script( 'underscore_bootstrap_wp-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true ); wp_enqueue_script( 'underscore_bootstrap_wp-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); /* my stylesheet and js */ wp_enqueue_style( 'custom_style_css', get_template_directory_uri(). '/css/main.css' ); wp_enqueue_script('custom_js', get_template_directory_uri(). '/js/main.js',array('jquery','bootstrap_js_cdn'),'',true); if ( is_singular() &amp;&amp; comments_open() &amp;&amp; get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } </code></pre> <p>The &quot; Themes Check &quot; Plugin shows -</p> <blockquote> <p>RECOMMENDED: Found the URL of a CDN in the code: maxcdn.bootstrapcdn.com/font-awesome. You should not load CSS or Javascript resources from a CDN, please bundle them with the theme.</p> <p>RECOMMENDED: Found the URL of a CDN in the code: maxcdn.bootstrapcdn.com/bootstrap. You should not load CSS or Javascript resources from a CDN, please bundle them with the theme.</p> </blockquote>
[ { "answer_id": 233913, "author": "daniyalahmad", "author_id": 69626, "author_profile": "https://wordpress.stackexchange.com/users/69626", "pm_score": 4, "selected": true, "text": "<p>Your theme should not depends on any external link library. There is no guarantee when that library can be taken down. That's the reason all of your theme assets should be package with theme, to prevent the future risk.</p>\n" }, { "answer_id": 235018, "author": "Brian Jackson", "author_id": 28394, "author_profile": "https://wordpress.stackexchange.com/users/28394", "pm_score": 2, "selected": false, "text": "<p>As daniyalahmad said, it is better not to include links to external assets in your theme. A good example of this recently. I use a theme from MyThemeShop and they linked to external html5shim. Google just recently stopped hosting this and so I started to get a 404 on my website. It was easy for me to simply comment it out, but for typical users, this is a big problem.</p>\n<p>There are now 1.5M instances of a dead html5shim googlecode URL on GitHub:\n<a href=\"https://www.reddit.com/r/programming/comments/4u47ak/15m_instances_of_a_dead_html5shim_googlecode_url/\" rel=\"nofollow noreferrer\">https://www.reddit.com/r/programming/comments/4u47ak/15m_instances_of_a_dead_html5shim_googlecode_url/</a></p>\n<p>When packaging a theme, always package it with it. And if you don't want to include it, write a tutorial for your users on how to deploy it after the fact. If they want to link externally that is usually fine, but not in the base theme.</p>\n" } ]
2016/08/03
[ "https://wordpress.stackexchange.com/questions/233903", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98256/" ]
When I run "themes check" , it recommends not to use CDN. I am using Bootstrap CDN this way ``` function underscore_bootstrap_wp_scripts() { /* bootstrap and font awesome and animate css */ wp_enqueue_style( 'bootstrap_cdn', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' ); wp_enqueue_style( 'fontawesome_cdn', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' ); /* default underscores styles */ wp_enqueue_style( 'underscore_bootstrap_wp-style', get_stylesheet_uri() ); /* bootstrap js */ wp_enqueue_script('bootstrap_js_cdn', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js',array('jquery'),'',true); /* default underscores js */ //wp_enqueue_script( 'underscore_bootstrap_wp-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true ); wp_enqueue_script( 'underscore_bootstrap_wp-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true ); /* my stylesheet and js */ wp_enqueue_style( 'custom_style_css', get_template_directory_uri(). '/css/main.css' ); wp_enqueue_script('custom_js', get_template_directory_uri(). '/js/main.js',array('jquery','bootstrap_js_cdn'),'',true); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } ``` The " Themes Check " Plugin shows - > > RECOMMENDED: Found the URL of a CDN in the code: maxcdn.bootstrapcdn.com/font-awesome. You should not load CSS or Javascript resources from a CDN, please bundle them with the theme. > > > RECOMMENDED: Found the URL of a CDN in the code: maxcdn.bootstrapcdn.com/bootstrap. You should not load CSS or Javascript resources from a CDN, please bundle them with the theme. > > >
Your theme should not depends on any external link library. There is no guarantee when that library can be taken down. That's the reason all of your theme assets should be package with theme, to prevent the future risk.
235,031
<p>I'm searching for a way to display the current taxonomy slug in a post.</p> <p>Edited to make it more clearer here a more accurate example.</p> <p>I have the CPT activites. I have more than 200 article posts about activities, and I want to categorize these into different areas (taxonomy) and different kind of activites. To get more specific, here my example:</p> <pre><code>Activities (Custom Post Type) - running (Taxonomy) - watersports (Taxonomy) - swimming (Term) - article post about swimming 1 (Post) - article post about swimming 2 (Post) - article post about swimming 3 (Post) - article post about swimming 4 (Post) - diving (Term) - boating (Term) - Kiteboating (Term) - materials arts (Taxonomy) - teamsports (Taxonomy) </code></pre> <p>If I'm in one of these posts (post about swimming), I want to display the current taxonomy (watersports) inside the article. </p> <p>I have found a way to get display the current term (Term 1) but unfortunally I need the slug of the active taxonomy slug inside the post. The slug of this taxonomy is finally important, to display a list of more activies beside watersports. I'd try it like this way:</p> <pre><code> &lt;h4&gt;More activities beside "watersport":&lt;/h4&gt; &lt;?php $taxonomy = 'HERE THE SLUG OF CURRENT TAXONOMY'; $orderby = 'name'; $show_count = 0; $pad_counts = 0; $hierarchical = 1; $title = ''; $args = array( 'taxonomy' =&gt; $taxonomy, 'orderby' =&gt; $orderby, 'show_count' =&gt; $show_count, 'pad_counts' =&gt; $pad_counts, 'hierarchical' =&gt; $hierarchical, 'title_li' =&gt; $title ); ?&gt; &lt;ul&gt; &lt;?php wp_list_categories( $args ); ?&gt; &lt;/ul&gt; </code></pre> <p>Thanks for your help!</p>
[ { "answer_id": 233945, "author": "Nicole", "author_id": 99424, "author_profile": "https://wordpress.stackexchange.com/users/99424", "pm_score": 0, "selected": false, "text": "<p>Rather than going an integrated plugin route, in my opinion, it'd be easier to just modify your robots.txt to include both the sitemap generated from Magento and the one generated from Wordpress (IMO, I love All in One SEO, but any plugin will work)</p>\n\n<p>You can specify more than one Sitemap file per robots.txt file like so:</p>\n\n<pre><code>Sitemap: http://www.example.com/map1.xml\n\nSitemap: http://www.example.com/map2.xml\n</code></pre>\n\n<p>Reference: <a href=\"http://www.sitemaps.org/protocol.html\" rel=\"nofollow\">http://www.sitemaps.org/protocol.html</a></p>\n" }, { "answer_id": 233958, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Each one creates an HTML sitemap of the Magento store without any reference to blog or posts whatsoever.</p>\n</blockquote>\n\n<p>I think you are misunderstanding what is happening here. XML plugins for WP would not go and create arbitrary HTML sitemap. That's just not what they are meant to do.</p>\n\n<p>Since you have two different things in play here I tried to figure out what is what, using a basic check of looking at <code>body</code> tag:</p>\n\n<ul>\n<li>for <code>www.rissyroos.com/blog/</code> it is <code>&lt;body class=\" wordpress-index-index is-blog\"&gt;</code>. This doesn't look like <em>normal</em> WordPress tag, but I suppose it does confirm that this is a WP–driven page.</li>\n<li>for <code>www.rissyroos.com/blog/sitemap_index.xml</code> it is <code>&lt;body class=\" amseohtmlsitemap-index-index\"&gt;</code>. No mention of WordPress in sight.</li>\n</ul>\n\n<p>My educated guess that however your WP is integrated into Magento site simply interferes with its full functionality, especially that falls under rewrite and custom URLs.</p>\n" }, { "answer_id": 233966, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>sitemap and robots files are read only from the root directory of your domain. If wordpress is not located there, there is not much that you can do by manipulating wordpress by itself as right now they are controlled by magento.</p>\n\n<p>One solution for your problem is to move wordpress to a subdomain. This way wordpress is controlling the root of the subdomain and whatever plugins you use should give the expected result.</p>\n\n<p>The other option is to generate \"manual\" <code>robots.txt</code> and <code>sitemap.xml</code> files that will direct the search engines to include the relevant sitemaps of magento and wordpress (this is what nicole suggested in his answers, but IMO robots file is the wrong location for that and you should do it in the sitemap file) </p>\n" } ]
2016/08/04
[ "https://wordpress.stackexchange.com/questions/235031", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99035/" ]
I'm searching for a way to display the current taxonomy slug in a post. Edited to make it more clearer here a more accurate example. I have the CPT activites. I have more than 200 article posts about activities, and I want to categorize these into different areas (taxonomy) and different kind of activites. To get more specific, here my example: ``` Activities (Custom Post Type) - running (Taxonomy) - watersports (Taxonomy) - swimming (Term) - article post about swimming 1 (Post) - article post about swimming 2 (Post) - article post about swimming 3 (Post) - article post about swimming 4 (Post) - diving (Term) - boating (Term) - Kiteboating (Term) - materials arts (Taxonomy) - teamsports (Taxonomy) ``` If I'm in one of these posts (post about swimming), I want to display the current taxonomy (watersports) inside the article. I have found a way to get display the current term (Term 1) but unfortunally I need the slug of the active taxonomy slug inside the post. The slug of this taxonomy is finally important, to display a list of more activies beside watersports. I'd try it like this way: ``` <h4>More activities beside "watersport":</h4> <?php $taxonomy = 'HERE THE SLUG OF CURRENT TAXONOMY'; $orderby = 'name'; $show_count = 0; $pad_counts = 0; $hierarchical = 1; $title = ''; $args = array( 'taxonomy' => $taxonomy, 'orderby' => $orderby, 'show_count' => $show_count, 'pad_counts' => $pad_counts, 'hierarchical' => $hierarchical, 'title_li' => $title ); ?> <ul> <?php wp_list_categories( $args ); ?> </ul> ``` Thanks for your help!
> > Each one creates an HTML sitemap of the Magento store without any reference to blog or posts whatsoever. > > > I think you are misunderstanding what is happening here. XML plugins for WP would not go and create arbitrary HTML sitemap. That's just not what they are meant to do. Since you have two different things in play here I tried to figure out what is what, using a basic check of looking at `body` tag: * for `www.rissyroos.com/blog/` it is `<body class=" wordpress-index-index is-blog">`. This doesn't look like *normal* WordPress tag, but I suppose it does confirm that this is a WP–driven page. * for `www.rissyroos.com/blog/sitemap_index.xml` it is `<body class=" amseohtmlsitemap-index-index">`. No mention of WordPress in sight. My educated guess that however your WP is integrated into Magento site simply interferes with its full functionality, especially that falls under rewrite and custom URLs.
235,039
<p>I'm building a site with two separate CPTs <code>nominees</code> and <code>winners</code></p> <p>The idea is that we have a user submit a nomination in one of 7 categories ( <code>taxonomy</code> ) on the front end, and editors go in and approve nominations for display on the website.</p> <p>Once every quarter, a selection of 7 nominees ( one from each category ) are chosen as winners.</p> <p>Is there a way to copy the fields from a <code>nominee</code> CPT ( name, department, taxonomy, content ) to a <code>winner</code> CPT? Ideally, this would be done by a call in the Admin. </p>
[ { "answer_id": 235054, "author": "Armstrongest", "author_id": 37479, "author_profile": "https://wordpress.stackexchange.com/users/37479", "pm_score": 0, "selected": false, "text": "<p>Someone else posted a link to <a href=\"https://wordpress.org/support/view/plugin-reviews/post-type-switcher\" rel=\"nofollow\">this plug-in</a>, but the answer disappeared. I'm not sure why ( is it against the rules to post a link to a plug-in or something? ). </p>\n\n<p>Anyway, I have the link open, so I'm posting it. I think it may solve my issue. I don't know if it will handle Custom Fields yet, but it looks promising.</p>\n" }, { "answer_id": 235058, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You can update a posts type using <code>wp_update_post</code>:</p>\n<pre><code>$my_post = array(\n 'ID' =&gt; $post_id,\n 'post_type' =&gt; 'winner',\n);\n$result = wp_update_post( $my_post, true );\n\n// check if it failed and tell the user why\nif ( is_wp_error( $result ) ) {\n $errors = $result-&gt;get_error_messages();\n foreach ( $errors as $error ) {\n echo 'error: '.esc_html( $error );\n }\n}\n</code></pre>\n<p>Where <code>$post_id</code> is the ID of the post you're switching to, and <code>$result</code> is either a post ID or an error object</p>\n" } ]
2016/08/04
[ "https://wordpress.stackexchange.com/questions/235039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37479/" ]
I'm building a site with two separate CPTs `nominees` and `winners` The idea is that we have a user submit a nomination in one of 7 categories ( `taxonomy` ) on the front end, and editors go in and approve nominations for display on the website. Once every quarter, a selection of 7 nominees ( one from each category ) are chosen as winners. Is there a way to copy the fields from a `nominee` CPT ( name, department, taxonomy, content ) to a `winner` CPT? Ideally, this would be done by a call in the Admin.
You can update a posts type using `wp_update_post`: ``` $my_post = array( 'ID' => $post_id, 'post_type' => 'winner', ); $result = wp_update_post( $my_post, true ); // check if it failed and tell the user why if ( is_wp_error( $result ) ) { $errors = $result->get_error_messages(); foreach ( $errors as $error ) { echo 'error: '.esc_html( $error ); } } ``` Where `$post_id` is the ID of the post you're switching to, and `$result` is either a post ID or an error object
235,057
<p>how to check if the post id has a new comment? </p> <p>this is something goes on my mind</p> <pre><code>if (hasnewcomment(post-&gt;id)){ //echo something } </code></pre> <p>any suggestion or help will do. using get the total comment or anything</p> <p>please help</p> <p>thankyou</p>
[ { "answer_id": 235054, "author": "Armstrongest", "author_id": 37479, "author_profile": "https://wordpress.stackexchange.com/users/37479", "pm_score": 0, "selected": false, "text": "<p>Someone else posted a link to <a href=\"https://wordpress.org/support/view/plugin-reviews/post-type-switcher\" rel=\"nofollow\">this plug-in</a>, but the answer disappeared. I'm not sure why ( is it against the rules to post a link to a plug-in or something? ). </p>\n\n<p>Anyway, I have the link open, so I'm posting it. I think it may solve my issue. I don't know if it will handle Custom Fields yet, but it looks promising.</p>\n" }, { "answer_id": 235058, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You can update a posts type using <code>wp_update_post</code>:</p>\n<pre><code>$my_post = array(\n 'ID' =&gt; $post_id,\n 'post_type' =&gt; 'winner',\n);\n$result = wp_update_post( $my_post, true );\n\n// check if it failed and tell the user why\nif ( is_wp_error( $result ) ) {\n $errors = $result-&gt;get_error_messages();\n foreach ( $errors as $error ) {\n echo 'error: '.esc_html( $error );\n }\n}\n</code></pre>\n<p>Where <code>$post_id</code> is the ID of the post you're switching to, and <code>$result</code> is either a post ID or an error object</p>\n" } ]
2016/08/04
[ "https://wordpress.stackexchange.com/questions/235057", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
how to check if the post id has a new comment? this is something goes on my mind ``` if (hasnewcomment(post->id)){ //echo something } ``` any suggestion or help will do. using get the total comment or anything please help thankyou
You can update a posts type using `wp_update_post`: ``` $my_post = array( 'ID' => $post_id, 'post_type' => 'winner', ); $result = wp_update_post( $my_post, true ); // check if it failed and tell the user why if ( is_wp_error( $result ) ) { $errors = $result->get_error_messages(); foreach ( $errors as $error ) { echo 'error: '.esc_html( $error ); } } ``` Where `$post_id` is the ID of the post you're switching to, and `$result` is either a post ID or an error object
235,071
<p>I have a custom post type that I want to use an if/elseif/else statement with. If post count of post type is equal to 1 do X, elseif post count is greater than 1 do Y, else do Z.</p> <p>This is the code I've come up with so far, but when I add in the count post type the_content and the_title start to pull in normal pages, not custom post types. Also, I'm pretty sure it's not actually counting the posts either. If I remove the if/elseif/else the while loop works perfectly. </p> <p>PS. I stripped out the code in my while loop to make it more simplified. The normal code is much more complicated for the slider. The slider operates even with one slide so I need the first if statement to omit the slider if only one post. </p> <pre><code>function getTestimonial() { $args = array( 'post_type' =&gt; 'testimonial' ); $loop = new WP_Query( $args ); $count_posts = wp_count_posts( 'testimonial' ); if(count($count_posts) == 1) :?&gt; &lt;?php the_content(); ?&gt; &lt;?php the_title(); ?&gt; &lt;?php elseif(count($count_posts) &gt; 1) : ?&gt; &lt;?php if ($loop-&gt;have_posts()) : while ($loop-&gt;have_posts()) : $loop-&gt;the_post(); ?&gt; &lt;div id="slider"&gt; &lt;?php the_content(); ?&gt; &lt;?php the_title(); ?&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;?php else: ?&gt; &lt;p&gt;No listing found&lt;/p&gt; &lt;?php endif; } </code></pre>
[ { "answer_id": 235073, "author": "Annapurna", "author_id": 98322, "author_profile": "https://wordpress.stackexchange.com/users/98322", "pm_score": 1, "selected": false, "text": "<p>Can you just print_r( $loop ) &amp; print_r( $count_posts ) and see what the output is.</p>\n" }, { "answer_id": 235074, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 3, "selected": true, "text": "<p><code>WP_Query</code> provides some useful properties. There are two of them which you could use:</p>\n\n<ul>\n<li><code>$post_count</code> - The number of posts being displayed (if you not pass <code>posts_per_page</code> argument to WP_Query construct it will return at most 5 posts)</li>\n<li><code>$found_posts</code> - The total number of posts found matching the current query parameters (so if you have got 100 posts in database which will fit to the arguments then this property will return 100)</li>\n</ul>\n\n<p>Here is sample of code:</p>\n\n<pre><code>$args = array( 'post_type' =&gt; 'testimonial' );\n$loop = new WP_Query( $args );\n$numposts = $loop-&gt;post_count;\nif ($numposts == 1) {\n // do X\n} else if ($numposts &gt; 1) {\n // do Y\n} else {\n // do Z\n}\n</code></pre>\n" } ]
2016/08/05
[ "https://wordpress.stackexchange.com/questions/235071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62370/" ]
I have a custom post type that I want to use an if/elseif/else statement with. If post count of post type is equal to 1 do X, elseif post count is greater than 1 do Y, else do Z. This is the code I've come up with so far, but when I add in the count post type the\_content and the\_title start to pull in normal pages, not custom post types. Also, I'm pretty sure it's not actually counting the posts either. If I remove the if/elseif/else the while loop works perfectly. PS. I stripped out the code in my while loop to make it more simplified. The normal code is much more complicated for the slider. The slider operates even with one slide so I need the first if statement to omit the slider if only one post. ``` function getTestimonial() { $args = array( 'post_type' => 'testimonial' ); $loop = new WP_Query( $args ); $count_posts = wp_count_posts( 'testimonial' ); if(count($count_posts) == 1) :?> <?php the_content(); ?> <?php the_title(); ?> <?php elseif(count($count_posts) > 1) : ?> <?php if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post(); ?> <div id="slider"> <?php the_content(); ?> <?php the_title(); ?> </div> <?php endwhile; endif; ?> <?php else: ?> <p>No listing found</p> <?php endif; } ```
`WP_Query` provides some useful properties. There are two of them which you could use: * `$post_count` - The number of posts being displayed (if you not pass `posts_per_page` argument to WP\_Query construct it will return at most 5 posts) * `$found_posts` - The total number of posts found matching the current query parameters (so if you have got 100 posts in database which will fit to the arguments then this property will return 100) Here is sample of code: ``` $args = array( 'post_type' => 'testimonial' ); $loop = new WP_Query( $args ); $numposts = $loop->post_count; if ($numposts == 1) { // do X } else if ($numposts > 1) { // do Y } else { // do Z } ```
235,087
<p>I would like the create a link that point to the comment part. So when reader click on my link, it will scroll down to the place that they can leave a reply. </p> <p>I have read some tutorial which teach how to create tag #id for headings in a post. However, I don't know how to do this for the comment part.</p> <p>Please help! Thank you so much!</p>
[ { "answer_id": 235089, "author": "Stephen", "author_id": 85776, "author_profile": "https://wordpress.stackexchange.com/users/85776", "pm_score": 4, "selected": true, "text": "<p>The code below should be something similar to what you're looking for</p>\n\n<p>Inside the <code>loop template</code> you use for listing blogs (like <code>index.php</code>) you need something like this</p>\n\n<pre><code>&lt;a href=\"&lt;?php the_permalink(); ?&gt;/#respond\"&gt; &lt;!-- The blog permalink with the anchor ID after --&gt;\n &lt;i class=\"fa fa-comments-o\"&gt;&lt;/i&gt; Leave a Comment\n&lt;/a&gt;\n</code></pre>\n\n<p>Inside your <code>comments.php</code> file you could have this</p>\n\n<pre><code>&lt;?php if ('open' == $post-&gt;comment_status) : ?&gt;\n\n &lt;div id=\"respond\"&gt; &lt;!-- This is the element we are pointing to --&gt;\n &lt;!-- Code for comments... --&gt;\n &lt;/div&gt;\n\n&lt;?php endif; // if you delete this the sky will fall on your head ?&gt;\n</code></pre>\n" }, { "answer_id": 266888, "author": "Appledystopia", "author_id": 119666, "author_profile": "https://wordpress.stackexchange.com/users/119666", "pm_score": 0, "selected": false, "text": "<p>I found a simpler solution, based on CoderSte's. Delete the </p>\n\n<pre><code>&lt;?php the_permalink(); ?&gt;/\n</code></pre>\n\n<p>from the first block of code, and then put it where you desire. That's it. The comment form already has the \"respond\" id, so you won't need to add the second block of code.</p>\n\n<p>Removing the permalink part will prevent the site from reloading. It will simply jump to the comment section, which is the desired behavior.</p>\n\n<p>This is all I added to my site. Add your button image in the tag.</p>\n\n<pre><code>&lt;a href=\"#respond\"&gt;&lt;img src=\"\" alt=\"\" width=\"100\" height=\"100\" /&gt;&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 357311, "author": "Brooke.", "author_id": 2204, "author_profile": "https://wordpress.stackexchange.com/users/2204", "pm_score": 1, "selected": false, "text": "<p>If you are inside the loop you can also use the <a href=\"https://developer.wordpress.org/reference/functions/comments_link/\" rel=\"nofollow noreferrer\"><code>comments_link()</code></a> function to echo the link or <a href=\"https://developer.wordpress.org/reference/functions/get_comments_link/\" rel=\"nofollow noreferrer\"><code>get_comments_link()</code></a> to return.</p>\n" } ]
2016/08/05
[ "https://wordpress.stackexchange.com/questions/235087", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83156/" ]
I would like the create a link that point to the comment part. So when reader click on my link, it will scroll down to the place that they can leave a reply. I have read some tutorial which teach how to create tag #id for headings in a post. However, I don't know how to do this for the comment part. Please help! Thank you so much!
The code below should be something similar to what you're looking for Inside the `loop template` you use for listing blogs (like `index.php`) you need something like this ``` <a href="<?php the_permalink(); ?>/#respond"> <!-- The blog permalink with the anchor ID after --> <i class="fa fa-comments-o"></i> Leave a Comment </a> ``` Inside your `comments.php` file you could have this ``` <?php if ('open' == $post->comment_status) : ?> <div id="respond"> <!-- This is the element we are pointing to --> <!-- Code for comments... --> </div> <?php endif; // if you delete this the sky will fall on your head ?> ```
235,088
<p>I have a custom post type called Portfolio. It is associated with three custom taxonomies. This is all working fine.</p> <p>For the archive page, however, I need to add a few custom settings. Due to a limitation in the project, I can't write a plugin—all changes have to be done in the theme.</p> <p>I've got the settings sub menu page appearing (easy enough) following <a href="http://www.billrobbinsdesign.com/custom-post-type-admin-page/" rel="nofollow">this guide</a>, and the settings appear on the page without issue. The problem now is that they're not saving. </p> <p>I've only added one setting (<code>header_text</code>) until I can figure out the saving problem.</p> <p>I imagine that <code>$option_group</code> is probably the problem.</p> <p>If I <code>var_dump($_POST)</code> I get: </p> <pre><code>array (size=6) 'option_page' =&gt; string 'edit.php?post_type=rushhour_projects&amp;page=projects_archive' (length=58) 'action' =&gt; string 'update' (length=6) '_wpnonce' =&gt; string '23c70a3029' (length=10) '_wp_http_referer' =&gt; string '/wp-admin/edit.php?post_type=rushhour_projects&amp;page=projects_archive' (length=68) 'rushhour_projects_archive' =&gt; array (size=1) 'header_text' =&gt; string 'asdf' (length=4) 'submit' =&gt; string 'Save Changes' (length=12) </code></pre> <p>Here's the custom post type registration:</p> <pre><code>if ( ! function_exists('rushhour_post_type_projects') ) : // Add Portfolio Projects to WordPress add_action( 'init', 'rushhour_post_type_projects', 0 ); // Register Portfolio Projects Custom Post Type function rushhour_post_type_projects() { $labels = array( 'name' =&gt; _x( 'Portfolio', 'Post Type General Name', 'rushhour' ), 'singular_name' =&gt; _x( 'Project', 'Post Type Singular Name', 'rushhour' ), 'menu_name' =&gt; __( 'Portfolio Projects', 'rushhour' ), 'name_admin_bar' =&gt; __( 'Portfolio Project', 'rushhour' ), 'archives' =&gt; __( 'Portfolio Archives', 'rushhour' ), 'parent_item_colon' =&gt; __( 'Parent Project:', 'rushhour' ), 'all_items' =&gt; __( 'All Projects', 'rushhour' ), 'add_new_item' =&gt; __( 'Add New Project', 'rushhour' ), 'add_new' =&gt; __( 'Add New', 'rushhour' ), 'new_item' =&gt; __( 'New Project', 'rushhour' ), 'edit_item' =&gt; __( 'Edit Project', 'rushhour' ), 'update_item' =&gt; __( 'Update Project', 'rushhour' ), 'view_item' =&gt; __( 'View Project', 'rushhour' ), 'search_items' =&gt; __( 'Search Projects', 'rushhour' ), 'not_found' =&gt; __( 'Not found', 'rushhour' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'rushhour' ), 'featured_image' =&gt; __( 'Featured Image', 'rushhour' ), 'set_featured_image' =&gt; __( 'Set featured image', 'rushhour' ), 'remove_featured_image' =&gt; __( 'Remove featured image', 'rushhour' ), 'use_featured_image' =&gt; __( 'Use as featured image', 'rushhour' ), 'insert_into_item' =&gt; __( 'Insert into project', 'rushhour' ), 'uploaded_to_this_item' =&gt; __( 'Uploaded to this project', 'rushhour' ), 'items_list' =&gt; __( 'Projects list', 'rushhour' ), 'items_list_navigation' =&gt; __( 'Projects list navigation', 'rushhour' ), 'filter_items_list' =&gt; __( 'Filter projects list', 'rushhour' ), ); $rewrite = array( 'slug' =&gt; 'portfolio', 'with_front' =&gt; true, 'pages' =&gt; true, 'feeds' =&gt; true, ); $args = array( 'label' =&gt; __( 'Project', 'rushhour' ), 'description' =&gt; __( 'Portfolio projects for Global VDC.', 'rushhour' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', ), 'taxonomies' =&gt; array( 'rushhour_clients', 'rushhour_locations', 'rushhour_project_type' ), 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'menu_position' =&gt; 5, 'menu_icon' =&gt; 'dashicons-portfolio', 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; true, 'can_export' =&gt; true, 'has_archive' =&gt; 'portfolio', 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'rewrite' =&gt; $rewrite, 'capability_type' =&gt; 'page', ); register_post_type( 'rushhour_projects', $args ); } endif; </code></pre> <p>Then I've got a function for setting up the admin sub menu page.</p> <pre><code>if ( ! function_exists('rushhour_projects_admin_page') ) : add_action( 'admin_menu' , 'rushhour_projects_admin_page' ); /** * Generate sub menu page for settings * * @uses rushhour_projects_options_display() */ function rushhour_projects_admin_page() { add_submenu_page( 'edit.php?post_type=rushhour_projects', __('Portfolio Projects Options', 'rushhour'), __('Portfolio Options', 'rushhour'), 'manage_options', 'projects_archive', 'rushhour_projects_options_display'); } endif; </code></pre> <p>So the above two items work without trouble.</p> <p>The problem, I think, is somewhere in the functions below for registering and saving the settings:</p> <pre><code>if ( ! function_exists('rushhour_projects_options_display') ) : /** * Display the form on the Rush Hour Projects Settings sub menu page. * * Used by 'rushhour_projects_admin_page'. */ function rushhour_projects_options_display() { // Create a header in the default WordPress 'wrap' container echo '&lt;div class="wrap"&gt;'; settings_errors(); echo '&lt;form method="post" action=""&gt;'; var_dump( get_option('rushhour_projects_archive') ); settings_fields( 'edit.php?post_type=rushhour_projects&amp;page=projects_archive' ); do_settings_sections( 'edit.php?post_type=rushhour_projects&amp;page=projects_archive' ); submit_button(); echo '&lt;/form&gt;&lt;/div&gt;&lt;!-- .wrap --&gt;'; } endif; add_action( 'admin_init', 'rushhour_projects_settings' ); /** * Register settings and add settings sections and fields to the admin page. */ function rushhour_projects_settings() { if ( false == get_option( 'rushhour_projects_archive' ) ) add_option( 'rushhour_projects_archive' ); add_settings_section( 'projects_archive_header', // Section $id __('Portfolio Project Archive Page Settings', 'rushhour'), 'rushhour_project_settings_section_title', // Callback 'edit.php?post_type=rushhour_projects&amp;page=projects_archive' // Settings Page Slug ); add_settings_field( 'header_text', // Field $id __('Header Text', 'rushhour'), // Setting $title 'projects_archive_header_text_callback', 'edit.php?post_type=rushhour_projects&amp;page=projects_archive', // Settings Page Slug 'projects_archive_header', // Section $id array('Text to display in the archive header.') ); register_setting( 'edit.php?post_type=rushhour_projects&amp;page=projects_archive', // $option_group 'rushhour_projects_archive', // $option_name 'rushhour_projects_archive_save_options' ); } /** * Callback for settings section. * * Commented out until settings are working. * * @param array $args Gets the $id, $title and $callback. */ function rushhour_project_settings_section_title( $args ) { // printf( '&lt;h2&gt;%s&lt;/h2&gt;', apply_filters( 'the_title', $args['title'] ) ); } /** * Settings fields callbacks. */ function projects_archive_header_text_callback($args) { $options = get_option('rushhour_projects_archive'); printf( '&lt;input class="widefat" id="header_text" name="rushhour_projects_archive[header_text]" type="textarea" value="%1$s" /&gt;', $options ); } /** * Save options. */ function rushhour_projects_archive_save_options() { if ( isset( $_POST['rushhour_projects_archive[header_text]'] ) ) { update_option( 'rushhour_projects_archive', $_POST['rushhour_projects_archive[header_text]'] ); } } </code></pre>
[ { "answer_id": 235093, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p>This should do the trick. Change</p>\n\n<pre><code>function rushhour_projects_archive_save_options()\n{\n if ( isset( $_POST['rushhour_projects_archive[header_text]'] ) )\n {\n update_option( 'rushhour_projects_archive', $_POST['rushhour_projects_archive[header_text]'] );\n }\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>function rushhour_projects_archive_save_options()\n{\n if ( isset( $_POST['rushhour_projects_archive']['header_text'] ) )\n {\n update_option( 'rushhour_projects_archive', $_POST['rushhour_projects_archive']['header_text'] );\n }\n}\n</code></pre>\n" }, { "answer_id": 235276, "author": "dotZak", "author_id": 83386, "author_profile": "https://wordpress.stackexchange.com/users/83386", "pm_score": 3, "selected": true, "text": "<p>Ok, so I got annoyed with it not working and decided to just rewrite it. I'm not <em>sure</em> what the solution was, but I suspect two things: the wrong endpoint for the form (should be <em>options.php</em>) and the wrong <code>$option_group</code> and <code>$option_name</code> (they were probably not matched correctly).</p>\n\n<p>For posterity, I'll leave my rewrite here and hopefully it helps others. A few differences between this and the previous version. </p>\n\n<ol>\n<li>This is now in it's own file so you won't see the custom post type registered. </li>\n<li>I used an object for the page per <a href=\"https://codex.wordpress.org/Creating_Options_Pages#Example_.232\" rel=\"nofollow\">example 2 from the WordPress codex</a>.</li>\n<li><p>I added a second option for a media uploader using <a href=\"http://jeroensormani.com/how-to-include-the-wordpress-media-selector-in-your-plugin/\" rel=\"nofollow\">this tutorial</a>, which I updated to use <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow\"><code>wp_localize_script()</code></a> to inject a JSON object to get some PHP data.</p>\n\n<p>\n\n<pre><code>public function __construct()\n{\n add_action( 'admin_menu', array( $this, 'add_submenu_page_to_post_type' ) );\n add_action( 'admin_init', array( $this, 'sub_menu_page_init' ) );\n add_action( 'admin_init', array( $this, 'media_selector_scripts' ) );\n}\n\n/**\n * Add sub menu page to the custom post type\n */\npublic function add_submenu_page_to_post_type()\n{\n add_submenu_page(\n 'edit.php?post_type=rushhour_projects',\n __('Portfolio Projects Options', 'rushhour'),\n __('Portfolio Options', 'rushhour'),\n 'manage_options',\n 'projects_archive',\n array($this, 'rushhour_projects_options_display'));\n}\n\n/**\n * Options page callback\n */\npublic function rushhour_projects_options_display()\n{\n $this-&gt;options = get_option( 'rushhour_projects_archive' );\n\n wp_enqueue_media();\n\n echo '&lt;div class=\"wrap\"&gt;';\n\n printf( '&lt;h1&gt;%s&lt;/h1&gt;', __('Portfolio Options', 'rushhour' ) ); \n\n echo '&lt;form method=\"post\" action=\"options.php\"&gt;';\n\n settings_fields( 'projects_archive' );\n\n do_settings_sections( 'projects-archive-page' );\n\n submit_button();\n\n echo '&lt;/form&gt;&lt;/div&gt;';\n}\n\n/**\n * Register and add settings\n */\npublic function sub_menu_page_init()\n{\n register_setting(\n 'projects_archive', // Option group\n 'rushhour_projects_archive', // Option name\n array( $this, 'sanitize' ) // Sanitize\n );\n\n add_settings_section(\n 'header_settings_section', // ID\n __('Header Settings', 'rushhour'), // Title\n array( $this, 'print_section_info' ), // Callback\n 'projects-archive-page' // Page\n );\n\n add_settings_field(\n 'archive_description', // ID\n __('Archive Description', 'rushhour'), // Title\n array( $this, 'archive_description_callback' ), // Callback\n 'projects-archive-page', // Page\n 'header_settings_section' // Section\n );\n\n add_settings_field(\n 'image_attachment_id',\n __('Header Background Image', 'rushhour'),\n array( $this, 'header_bg_image_callback' ),\n 'projects-archive-page',\n 'header_settings_section'\n );\n}\n\n/**\n * Sanitize each setting field as needed\n *\n * @param array $input Contains all settings fields as array keys\n */\npublic function sanitize( $input )\n{\n $new_input = array();\n\n if( isset( $input['archive_description'] ) )\n $new_input['archive_description'] = sanitize_text_field( $input['archive_description'] );\n\n if( isset( $input['image_attachment_id'] ) )\n $new_input['image_attachment_id'] = absint( $input['image_attachment_id'] );\n\n return $new_input;\n}\n\n/**\n * Print the Section text\n */\npublic function print_section_info()\n{\n print 'Select options for the archive page header.';\n}\n\n/**\n * Get the settings option array and print one of its values\n */\npublic function archive_description_callback()\n{\n printf(\n '&lt;input type=\"text\" id=\"archive_description\" name=\"rushhour_projects_archive[archive_description]\" value=\"%s\" /&gt;',\n isset( $this-&gt;options['archive_description'] ) ? esc_attr( $this-&gt;options['archive_description']) : ''\n );\n}\n\n/**\n * Get the settings option array and print one of its values\n */\npublic function header_bg_image_callback()\n{\n $attachment_id = $this-&gt;options['image_attachment_id'];\n\n // Image Preview\n printf('&lt;div class=\"image-preview-wrapper\"&gt;&lt;img id=\"image-preview\" src=\"%s\" &gt;&lt;/div&gt;', wp_get_attachment_url( $attachment_id ) );\n\n // Image Upload Button\n printf( '&lt;input id=\"upload_image_button\" type=\"button\" class=\"button\" value=\"%s\" /&gt;',\n __( 'Upload image', 'rushhour' ) );\n\n // Hidden field containing the value of the image attachment id\n printf( '&lt;input type=\"hidden\" name=\"rushhour_projects_archive[image_attachment_id]\" id=\"image_attachment_id\" value=\"%s\"&gt;',\n $attachment_id );\n}\n\npublic function media_selector_scripts()\n{\n $my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );\n\n wp_register_script( 'sub_menu_media_selector_scripts', get_template_directory_uri() . '/admin/js/media-selector.js', array('jquery'), false, true );\n\n $selector_data = array(\n 'attachment_id' =&gt; get_option( 'media_selector_attachment_id', 0 )\n );\n\n wp_localize_script( 'sub_menu_media_selector_scripts', 'selector_data', $selector_data );\n\n wp_enqueue_script( 'sub_menu_media_selector_scripts' );\n}\n</code></pre>\n\n<p>}</p></li>\n</ol>\n\n<p>Then simply call the object on if <code>is_admin()</code> is true:</p>\n\n<pre><code>if ( is_admin() )\n $my_settings_page = new RushHourProjectArchivesAdminPage();\n</code></pre>\n" } ]
2016/08/05
[ "https://wordpress.stackexchange.com/questions/235088", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83386/" ]
I have a custom post type called Portfolio. It is associated with three custom taxonomies. This is all working fine. For the archive page, however, I need to add a few custom settings. Due to a limitation in the project, I can't write a plugin—all changes have to be done in the theme. I've got the settings sub menu page appearing (easy enough) following [this guide](http://www.billrobbinsdesign.com/custom-post-type-admin-page/), and the settings appear on the page without issue. The problem now is that they're not saving. I've only added one setting (`header_text`) until I can figure out the saving problem. I imagine that `$option_group` is probably the problem. If I `var_dump($_POST)` I get: ``` array (size=6) 'option_page' => string 'edit.php?post_type=rushhour_projects&page=projects_archive' (length=58) 'action' => string 'update' (length=6) '_wpnonce' => string '23c70a3029' (length=10) '_wp_http_referer' => string '/wp-admin/edit.php?post_type=rushhour_projects&page=projects_archive' (length=68) 'rushhour_projects_archive' => array (size=1) 'header_text' => string 'asdf' (length=4) 'submit' => string 'Save Changes' (length=12) ``` Here's the custom post type registration: ``` if ( ! function_exists('rushhour_post_type_projects') ) : // Add Portfolio Projects to WordPress add_action( 'init', 'rushhour_post_type_projects', 0 ); // Register Portfolio Projects Custom Post Type function rushhour_post_type_projects() { $labels = array( 'name' => _x( 'Portfolio', 'Post Type General Name', 'rushhour' ), 'singular_name' => _x( 'Project', 'Post Type Singular Name', 'rushhour' ), 'menu_name' => __( 'Portfolio Projects', 'rushhour' ), 'name_admin_bar' => __( 'Portfolio Project', 'rushhour' ), 'archives' => __( 'Portfolio Archives', 'rushhour' ), 'parent_item_colon' => __( 'Parent Project:', 'rushhour' ), 'all_items' => __( 'All Projects', 'rushhour' ), 'add_new_item' => __( 'Add New Project', 'rushhour' ), 'add_new' => __( 'Add New', 'rushhour' ), 'new_item' => __( 'New Project', 'rushhour' ), 'edit_item' => __( 'Edit Project', 'rushhour' ), 'update_item' => __( 'Update Project', 'rushhour' ), 'view_item' => __( 'View Project', 'rushhour' ), 'search_items' => __( 'Search Projects', 'rushhour' ), 'not_found' => __( 'Not found', 'rushhour' ), 'not_found_in_trash' => __( 'Not found in Trash', 'rushhour' ), 'featured_image' => __( 'Featured Image', 'rushhour' ), 'set_featured_image' => __( 'Set featured image', 'rushhour' ), 'remove_featured_image' => __( 'Remove featured image', 'rushhour' ), 'use_featured_image' => __( 'Use as featured image', 'rushhour' ), 'insert_into_item' => __( 'Insert into project', 'rushhour' ), 'uploaded_to_this_item' => __( 'Uploaded to this project', 'rushhour' ), 'items_list' => __( 'Projects list', 'rushhour' ), 'items_list_navigation' => __( 'Projects list navigation', 'rushhour' ), 'filter_items_list' => __( 'Filter projects list', 'rushhour' ), ); $rewrite = array( 'slug' => 'portfolio', 'with_front' => true, 'pages' => true, 'feeds' => true, ); $args = array( 'label' => __( 'Project', 'rushhour' ), 'description' => __( 'Portfolio projects for Global VDC.', 'rushhour' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'revisions', ), 'taxonomies' => array( 'rushhour_clients', 'rushhour_locations', 'rushhour_project_type' ), 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-portfolio', 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => 'portfolio', 'exclude_from_search' => false, 'publicly_queryable' => true, 'rewrite' => $rewrite, 'capability_type' => 'page', ); register_post_type( 'rushhour_projects', $args ); } endif; ``` Then I've got a function for setting up the admin sub menu page. ``` if ( ! function_exists('rushhour_projects_admin_page') ) : add_action( 'admin_menu' , 'rushhour_projects_admin_page' ); /** * Generate sub menu page for settings * * @uses rushhour_projects_options_display() */ function rushhour_projects_admin_page() { add_submenu_page( 'edit.php?post_type=rushhour_projects', __('Portfolio Projects Options', 'rushhour'), __('Portfolio Options', 'rushhour'), 'manage_options', 'projects_archive', 'rushhour_projects_options_display'); } endif; ``` So the above two items work without trouble. The problem, I think, is somewhere in the functions below for registering and saving the settings: ``` if ( ! function_exists('rushhour_projects_options_display') ) : /** * Display the form on the Rush Hour Projects Settings sub menu page. * * Used by 'rushhour_projects_admin_page'. */ function rushhour_projects_options_display() { // Create a header in the default WordPress 'wrap' container echo '<div class="wrap">'; settings_errors(); echo '<form method="post" action="">'; var_dump( get_option('rushhour_projects_archive') ); settings_fields( 'edit.php?post_type=rushhour_projects&page=projects_archive' ); do_settings_sections( 'edit.php?post_type=rushhour_projects&page=projects_archive' ); submit_button(); echo '</form></div><!-- .wrap -->'; } endif; add_action( 'admin_init', 'rushhour_projects_settings' ); /** * Register settings and add settings sections and fields to the admin page. */ function rushhour_projects_settings() { if ( false == get_option( 'rushhour_projects_archive' ) ) add_option( 'rushhour_projects_archive' ); add_settings_section( 'projects_archive_header', // Section $id __('Portfolio Project Archive Page Settings', 'rushhour'), 'rushhour_project_settings_section_title', // Callback 'edit.php?post_type=rushhour_projects&page=projects_archive' // Settings Page Slug ); add_settings_field( 'header_text', // Field $id __('Header Text', 'rushhour'), // Setting $title 'projects_archive_header_text_callback', 'edit.php?post_type=rushhour_projects&page=projects_archive', // Settings Page Slug 'projects_archive_header', // Section $id array('Text to display in the archive header.') ); register_setting( 'edit.php?post_type=rushhour_projects&page=projects_archive', // $option_group 'rushhour_projects_archive', // $option_name 'rushhour_projects_archive_save_options' ); } /** * Callback for settings section. * * Commented out until settings are working. * * @param array $args Gets the $id, $title and $callback. */ function rushhour_project_settings_section_title( $args ) { // printf( '<h2>%s</h2>', apply_filters( 'the_title', $args['title'] ) ); } /** * Settings fields callbacks. */ function projects_archive_header_text_callback($args) { $options = get_option('rushhour_projects_archive'); printf( '<input class="widefat" id="header_text" name="rushhour_projects_archive[header_text]" type="textarea" value="%1$s" />', $options ); } /** * Save options. */ function rushhour_projects_archive_save_options() { if ( isset( $_POST['rushhour_projects_archive[header_text]'] ) ) { update_option( 'rushhour_projects_archive', $_POST['rushhour_projects_archive[header_text]'] ); } } ```
Ok, so I got annoyed with it not working and decided to just rewrite it. I'm not *sure* what the solution was, but I suspect two things: the wrong endpoint for the form (should be *options.php*) and the wrong `$option_group` and `$option_name` (they were probably not matched correctly). For posterity, I'll leave my rewrite here and hopefully it helps others. A few differences between this and the previous version. 1. This is now in it's own file so you won't see the custom post type registered. 2. I used an object for the page per [example 2 from the WordPress codex](https://codex.wordpress.org/Creating_Options_Pages#Example_.232). 3. I added a second option for a media uploader using [this tutorial](http://jeroensormani.com/how-to-include-the-wordpress-media-selector-in-your-plugin/), which I updated to use [`wp_localize_script()`](https://developer.wordpress.org/reference/functions/wp_localize_script/) to inject a JSON object to get some PHP data. ``` public function __construct() { add_action( 'admin_menu', array( $this, 'add_submenu_page_to_post_type' ) ); add_action( 'admin_init', array( $this, 'sub_menu_page_init' ) ); add_action( 'admin_init', array( $this, 'media_selector_scripts' ) ); } /** * Add sub menu page to the custom post type */ public function add_submenu_page_to_post_type() { add_submenu_page( 'edit.php?post_type=rushhour_projects', __('Portfolio Projects Options', 'rushhour'), __('Portfolio Options', 'rushhour'), 'manage_options', 'projects_archive', array($this, 'rushhour_projects_options_display')); } /** * Options page callback */ public function rushhour_projects_options_display() { $this->options = get_option( 'rushhour_projects_archive' ); wp_enqueue_media(); echo '<div class="wrap">'; printf( '<h1>%s</h1>', __('Portfolio Options', 'rushhour' ) ); echo '<form method="post" action="options.php">'; settings_fields( 'projects_archive' ); do_settings_sections( 'projects-archive-page' ); submit_button(); echo '</form></div>'; } /** * Register and add settings */ public function sub_menu_page_init() { register_setting( 'projects_archive', // Option group 'rushhour_projects_archive', // Option name array( $this, 'sanitize' ) // Sanitize ); add_settings_section( 'header_settings_section', // ID __('Header Settings', 'rushhour'), // Title array( $this, 'print_section_info' ), // Callback 'projects-archive-page' // Page ); add_settings_field( 'archive_description', // ID __('Archive Description', 'rushhour'), // Title array( $this, 'archive_description_callback' ), // Callback 'projects-archive-page', // Page 'header_settings_section' // Section ); add_settings_field( 'image_attachment_id', __('Header Background Image', 'rushhour'), array( $this, 'header_bg_image_callback' ), 'projects-archive-page', 'header_settings_section' ); } /** * Sanitize each setting field as needed * * @param array $input Contains all settings fields as array keys */ public function sanitize( $input ) { $new_input = array(); if( isset( $input['archive_description'] ) ) $new_input['archive_description'] = sanitize_text_field( $input['archive_description'] ); if( isset( $input['image_attachment_id'] ) ) $new_input['image_attachment_id'] = absint( $input['image_attachment_id'] ); return $new_input; } /** * Print the Section text */ public function print_section_info() { print 'Select options for the archive page header.'; } /** * Get the settings option array and print one of its values */ public function archive_description_callback() { printf( '<input type="text" id="archive_description" name="rushhour_projects_archive[archive_description]" value="%s" />', isset( $this->options['archive_description'] ) ? esc_attr( $this->options['archive_description']) : '' ); } /** * Get the settings option array and print one of its values */ public function header_bg_image_callback() { $attachment_id = $this->options['image_attachment_id']; // Image Preview printf('<div class="image-preview-wrapper"><img id="image-preview" src="%s" ></div>', wp_get_attachment_url( $attachment_id ) ); // Image Upload Button printf( '<input id="upload_image_button" type="button" class="button" value="%s" />', __( 'Upload image', 'rushhour' ) ); // Hidden field containing the value of the image attachment id printf( '<input type="hidden" name="rushhour_projects_archive[image_attachment_id]" id="image_attachment_id" value="%s">', $attachment_id ); } public function media_selector_scripts() { $my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 ); wp_register_script( 'sub_menu_media_selector_scripts', get_template_directory_uri() . '/admin/js/media-selector.js', array('jquery'), false, true ); $selector_data = array( 'attachment_id' => get_option( 'media_selector_attachment_id', 0 ) ); wp_localize_script( 'sub_menu_media_selector_scripts', 'selector_data', $selector_data ); wp_enqueue_script( 'sub_menu_media_selector_scripts' ); } ``` } Then simply call the object on if `is_admin()` is true: ``` if ( is_admin() ) $my_settings_page = new RushHourProjectArchivesAdminPage(); ```
235,103
<p>Currently I'm using the the_excerpt on my frontpage which works perfectly. When the visiter goes to the post it first needs to read the first part of the story, see a featured image and then load the rest of the content.</p> <p>Currently I have this:</p> <pre><code>&lt;?php the_excerpt(); ?&gt; &lt;?php the_post_thumbnail( 'blog-full', array( 'class' =&gt; 'img-responsive img-blog' ) ); ?&gt; &lt;?php the_content(); ?&gt; </code></pre> <p>The problem is, the_excerpt loads the same first lines as the_content (it's a duplicate). I inserted a read more tag in WP backend, but it won't cut of the top and start after the tag line. </p> <p>How do I get this working?</p> <p>Thanks in advance</p>
[ { "answer_id": 235105, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>You could do this without having to code anything special. Enter your first piece of text into the Excerpt field in the admin edit screen for the post. Enter only the remaining text into the visual editor. </p>\n\n<p>That way you can have the excerpt text on the site's front page and the \"rest\" of the text after the thumbnail on the post's single page.</p>\n" }, { "answer_id": 235115, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p>As <a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"nofollow\">Documentation</a> says about <code>the_content</code> function, it accepts two arguments. We don't need first, but the second will strip post excerpt from post content (everything before <code>&lt;!-- more --&gt;</code> tag). Your code should looks like this:</p>\n\n<pre><code>&lt;?php the_excerpt(); ?&gt;\n&lt;?php the_post_thumbnail( 'blog-full', array( 'class' =&gt; 'img-responsive img-blog' ) ); ?&gt;\n&lt;?php the_content(null, true); ?&gt;\n</code></pre>\n" } ]
2016/08/05
[ "https://wordpress.stackexchange.com/questions/235103", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20548/" ]
Currently I'm using the the\_excerpt on my frontpage which works perfectly. When the visiter goes to the post it first needs to read the first part of the story, see a featured image and then load the rest of the content. Currently I have this: ``` <?php the_excerpt(); ?> <?php the_post_thumbnail( 'blog-full', array( 'class' => 'img-responsive img-blog' ) ); ?> <?php the_content(); ?> ``` The problem is, the\_excerpt loads the same first lines as the\_content (it's a duplicate). I inserted a read more tag in WP backend, but it won't cut of the top and start after the tag line. How do I get this working? Thanks in advance
You could do this without having to code anything special. Enter your first piece of text into the Excerpt field in the admin edit screen for the post. Enter only the remaining text into the visual editor. That way you can have the excerpt text on the site's front page and the "rest" of the text after the thumbnail on the post's single page.
235,120
<p>I created an external script to import json data into a custom post type that uses wp-load.php. Everything works fine but after every update I get the message </p> <pre><code>Notice: map_meta_cap was called incorrectly. The post type EXAMPLE is not registered, so it may not be reliable to check the capability "edit_post" against a post of that type. </code></pre> <p>Im calling the script inside a child theme and post_type_exists returns false but works fine...</p> <p>Ive seen a similar notice in a core track thread but it talks about comments being the issue and my post type doesnt have any comment functionality.</p> <pre><code>function child_post_types() { $labels = array( 'name' =&gt; _x( 'Courses', 'Post Type General Name', 'test' ), 'singular_name' =&gt; _x( 'Course', 'Post Type Singular Name', 'test' ), 'menu_name' =&gt; __( 'Courses', 'test' ), 'parent_item_colon' =&gt; __( 'Parent Course:', 'test' ), 'all_items' =&gt; __( 'All Courses', 'test' ), 'view_item' =&gt; __( 'View Course', 'test' ), 'add_new_item' =&gt; __( 'Add New Course', 'test' ), 'add_new' =&gt; __( 'Add New', 'test' ), 'edit_item' =&gt; __( 'Edit Course', 'test' ), 'update_item' =&gt; __( 'Update Course', 'test' ), 'search_items' =&gt; __( 'Search Courses', 'test' ), 'not_found' =&gt; __( 'Not found', 'test' ), 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'test' ), ); $args = array( 'label' =&gt; __( 'Course', 'test' ), 'description' =&gt; __( 'Courses', 'test' ), 'labels' =&gt; $labels, 'supports' =&gt; array( 'title', 'thumbnail', 'editor', 'revisions', 'author' ), //editor, thumbnail, title, author, excerpt, trackpacks, custom-fields, comments, revisions, page-attributes, post-formats 'hierarchical' =&gt; false, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_in_admin_bar' =&gt; true, 'menu_position' =&gt; 5, 'can_export' =&gt; true, 'has_archive' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'rewrite' =&gt;array('slug'=&gt;'courses'), 'capability_type' =&gt; 'page', ); register_post_type( 'course', $args ); } add_action( 'init', 'child_post_types', 0 ); </code></pre> <p>And the script is sitting in my child theme just getting a local json file and looping through courses with wp_update_post()</p> <pre><code>require('../../../wp-load.php'); $data = json_decode( file_get_contents( 'wp-content/themes/_theme/courses.json' ), true ); foreach($data as $key =&gt; $c){ $course = wp_update_post( array( 'ID' =&gt; $courseID, 'post_title' =&gt; $c['CourseTitle'], 'post_content' =&gt; $c['Description'], ), true ); } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 310409, "author": "Bjorn", "author_id": 83707, "author_profile": "https://wordpress.stackexchange.com/users/83707", "pm_score": 1, "selected": false, "text": "<p>Today i got exactly the same behaviour when adding a custom post type. I also noticed some admin post search tools stopped working. My debug_log showed exactly the same notice.</p>\n\n<p>The problem turned out to be some text before the <code>&lt;?php</code> opening tag (top file) were I register the CPT.</p>\n\n<p>Example<br></p>\n\n<pre><code>some text here&lt;?php\n/**\n * @class My_Cpt_Class\n */\n.......\n</code></pre>\n\n<p>The CPT does get registered correctly. I can add posts etc. But a few default post actions (from other plugins aswell) stop working for ALL post types. I have no idea why this happens with this error.</p>\n" }, { "answer_id": 342456, "author": "ShelðÔn Alag", "author_id": 162523, "author_profile": "https://wordpress.stackexchange.com/users/162523", "pm_score": -1, "selected": false, "text": "<p>This answer might be old on this post but I hope it can help others:</p>\n\n<p>I had this trouble and I solved it using this.</p>\n\n<p>For example: \nI used <code>add_action('init', 'register_posttype');</code>\nand that gives me the error map_meta_cap incorrectly called. so I changed it to <code>admin_init</code> instead of <code>init</code>.</p>\n" }, { "answer_id": 346373, "author": "alexg", "author_id": 17616, "author_profile": "https://wordpress.stackexchange.com/users/17616", "pm_score": 0, "selected": false, "text": "<p>You get this error if a post is encountered with a post type that you haven't registered on the <code>init</code> event.</p>\n\n<p>I always call <code>register_post_type()</code> on <code>init</code>, as instructed in the <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">docs</a>. However, in my dev build process I use <code>wp-cli</code> to deactivate my plugin, and re-install the new iteration of the plugin. In the brief moment when the plugin is deactivated, this message appears because WP runs without the post type being registered.</p>\n\n<p>In short, WordPress shows this error whenever it sees a post with a post type that's not properly registered.</p>\n" }, { "answer_id": 402223, "author": "Vijay Hardaha", "author_id": 218789, "author_profile": "https://wordpress.stackexchange.com/users/218789", "pm_score": 0, "selected": false, "text": "<p>There are many reasons for this kind of error.</p>\n<p>One of the reasons that I faced was when I had data saved in comments tables but those plugins that created those data wasn't activated so the debugging tool was showing this kind of error after activating the plugin the error was gone.</p>\n<p>By looking into your case I think it's the priority issue. Instead of using priority 0, try the default priority 10</p>\n<p><code>add_action( 'init', 'child_post_types', 10 );</code></p>\n<p>That might solve things.</p>\n" } ]
2016/08/05
[ "https://wordpress.stackexchange.com/questions/235120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47348/" ]
I created an external script to import json data into a custom post type that uses wp-load.php. Everything works fine but after every update I get the message ``` Notice: map_meta_cap was called incorrectly. The post type EXAMPLE is not registered, so it may not be reliable to check the capability "edit_post" against a post of that type. ``` Im calling the script inside a child theme and post\_type\_exists returns false but works fine... Ive seen a similar notice in a core track thread but it talks about comments being the issue and my post type doesnt have any comment functionality. ``` function child_post_types() { $labels = array( 'name' => _x( 'Courses', 'Post Type General Name', 'test' ), 'singular_name' => _x( 'Course', 'Post Type Singular Name', 'test' ), 'menu_name' => __( 'Courses', 'test' ), 'parent_item_colon' => __( 'Parent Course:', 'test' ), 'all_items' => __( 'All Courses', 'test' ), 'view_item' => __( 'View Course', 'test' ), 'add_new_item' => __( 'Add New Course', 'test' ), 'add_new' => __( 'Add New', 'test' ), 'edit_item' => __( 'Edit Course', 'test' ), 'update_item' => __( 'Update Course', 'test' ), 'search_items' => __( 'Search Courses', 'test' ), 'not_found' => __( 'Not found', 'test' ), 'not_found_in_trash' => __( 'Not found in Trash', 'test' ), ); $args = array( 'label' => __( 'Course', 'test' ), 'description' => __( 'Courses', 'test' ), 'labels' => $labels, 'supports' => array( 'title', 'thumbnail', 'editor', 'revisions', 'author' ), //editor, thumbnail, title, author, excerpt, trackpacks, custom-fields, comments, revisions, page-attributes, post-formats 'hierarchical' => false, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'show_in_admin_bar' => true, 'menu_position' => 5, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'rewrite' =>array('slug'=>'courses'), 'capability_type' => 'page', ); register_post_type( 'course', $args ); } add_action( 'init', 'child_post_types', 0 ); ``` And the script is sitting in my child theme just getting a local json file and looping through courses with wp\_update\_post() ``` require('../../../wp-load.php'); $data = json_decode( file_get_contents( 'wp-content/themes/_theme/courses.json' ), true ); foreach($data as $key => $c){ $course = wp_update_post( array( 'ID' => $courseID, 'post_title' => $c['CourseTitle'], 'post_content' => $c['Description'], ), true ); } ``` Any ideas?
Today i got exactly the same behaviour when adding a custom post type. I also noticed some admin post search tools stopped working. My debug\_log showed exactly the same notice. The problem turned out to be some text before the `<?php` opening tag (top file) were I register the CPT. Example ``` some text here<?php /** * @class My_Cpt_Class */ ....... ``` The CPT does get registered correctly. I can add posts etc. But a few default post actions (from other plugins aswell) stop working for ALL post types. I have no idea why this happens with this error.
235,135
<p>So on this Custom Post Type list page there is a list of Properties.</p> <p>I have a custom search feature where they can search for Properties with certain Taxonomy Terms - but they can also search for Multiple Taxonomy Terms.</p> <p><strong>Question</strong>: If someone selects 2 terms then the only Properties that should display in the list are Properties with <code>term_one</code> <code>AND</code> <code>term_two</code></p> <p>So I tried this below:</p> <pre><code>$required_features_slugs = array(); if( isset ( $_GET['features'] ) ) { $features_slugs = $_GET['features']; } $feature = get_terms('features'); $tmp_required = $required_features_slugs; $property = array( 'post_type' =&gt; 'properties', 'paged' =&gt; $paged, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'features', 'field' =&gt; 'slug', 'terms' =&gt; $tmp_required, 'operator' =&gt; 'AND', ) ), ); </code></pre> <p>The URL looks like this:</p> <pre><code>features%5B%5D=accredited-landlord&amp;features%5B%5D=cellarbasement </code></pre> <p>Now because these two Features are selected it should only return one Property because there is only one Property with <code>term_one</code> <code>AND</code> <code>term_two</code> together</p> <p>However I don't get this result instead I get 4 Properties because there are 4 Properties. 3 with <code>term_one</code> and 1 with <code>term_two</code>.</p> <p>What I want to happen is for 1 Property to be returned because there is only one Property with <code>term_once</code> <code>AND</code> <code>term_two</code> together.</p> <p>Is there something wrong that I am doing in the Query?</p> <p><strong>Edit</strong>: Updated <code>PHP</code> file</p> <pre><code>$required_features_slugs = array(); if( isset ( $_GET['features'] ) ) { $required_features_slugs = $_GET['features']; } $all_features = get_terms('features'); if( ! empty( $required_features_slugs ) ) { foreach ( $all_features as $feature ) { $tmp_required = $required_features_slugs; if( ! in_array($feature-&gt;slug, $required_features_slugs) ) { array_push( $tmp_required, $feature-&gt;slug ); } $property = array( 'post_type' =&gt; 'properties', 'paged' =&gt; $paged, 'tax_query' =&gt; array( 'taxonomy' =&gt; 'features', 'field' =&gt; 'slug', 'terms' =&gt; $tmp_required, 'operator' =&gt; 'AND', ), ); } } </code></pre> <p><strong>Edit #2</strong>: So here is the <code>var_dump</code> to the Query:</p> <pre><code>array(3) { ["post_type"]=&gt; string(10) "properties" ["paged"]=&gt; int(1) ["tax_query"]=&gt; array(4) { ["taxonomy"]=&gt; string(8) "features" ["field"]=&gt; string(4) "slug" ["terms"]=&gt; array(2) { [0]=&gt; string(19) "accredited-landlord" [1]=&gt; string(14) "cellarbasement" } ["operator"]=&gt; string(3) "AND" } } </code></pre> <p>And here is the <code>var_dump</code> to the terms:</p> <pre><code>array(2) { [0]=&gt; string(19) "accredited-landlord" [1]=&gt; string(14) "cellarbasement" } </code></pre>
[ { "answer_id": 235283, "author": "Nefro", "author_id": 86801, "author_profile": "https://wordpress.stackexchange.com/users/86801", "pm_score": 1, "selected": false, "text": "<p>Try change operator to <code>'operator' =&gt; 'IN'</code>, or try use code something like this:</p>\n\n<pre><code>$required_features_slugs = array();\nif( isset ( $_GET['features'] ) ) {\n $required_features_slugs = $_GET['features'];\n}\n\n if( ! empty( $required_features_slugs ) ) {\n\n $property = array(\n 'post_type' =&gt; 'properties',\n 'paged' =&gt; $paged,\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n ),\n );\n\n\nforeach ( $required_features_slugs as $feature ) {\n $property['tax_query'][] = array(\n 'taxonomy' =&gt; 'features',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $feature,\n );\n }\n\n\n}\n}\n</code></pre>\n" }, { "answer_id": 235304, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p><strong>Query Arguments:</strong></p>\n\n<p>If <code>$input_terms</code> is the input array of term slugs, then you should be able to use (if I understand the question correctly):</p>\n\n<pre><code>$property = [\n 'post_type' =&gt; 'properties',\n 'paged' =&gt; $paged,\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; 'features',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $input_terms,\n 'operator' =&gt; 'AND',\n ]\n ],\n];\n</code></pre>\n\n<p>where we added a missing array in the tax query.</p>\n\n<p><strong>Validation:</strong></p>\n\n<p>We should <strong>validate</strong> the input terms first. </p>\n\n<p>Here are some examples:</p>\n\n<ul>\n<li><p>Check the maximum number of allowed terms:</p>\n\n<pre><code>$valid_input_terms_max_count = count( $input_terms ) &lt;= 4;\n</code></pre></li>\n<li><p>Check the minimum number of allowed terms:</p>\n\n<pre><code>$valid_input_terms_min_count = count( $input_terms ) &gt;= 1;\n</code></pre></li>\n<li><p>Check if they input terms slugs exists (assumes non-empty input array):</p>\n\n<pre><code>$valid_input_terms_slugs = array_reduce( \n (array) $input_terms, \n function( $carry, $item ) { \n return $carry &amp;&amp; null !== term_exists( $item, 'features' ); \n }, \n true \n);\n</code></pre>\n\n<p>where we collect <a href=\"https://developer.wordpress.org/reference/functions/term_exists/\" rel=\"nofollow\"><code>term_exists()</code></a> for all the terms into a single boolean value. </p></li>\n<li><p>We could also match the input slugs against a predefined array of slugs </p></li>\n</ul>\n\n<p><strong>Generated SQL:</strong></p>\n\n<p>Here's a generated SQL query for two existing term slugs in <code>$input_terms</code>:</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID \nFROM wp_posts \nWHERE 1=1 AND ( \n (\n SELECT COUNT(1)\n FROM wp_term_relationships\n WHERE term_taxonomy_id IN (160,161)\n AND object_id = wp_posts.ID\n ) = 2\n) \nAND wp_posts.post_type = 'properties' \nAND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') \nGROUP BY wp_posts.ID \nORDER BY wp_posts.post_date DESC \nLIMIT 0, 10\n</code></pre>\n\n<p>Hope you can adjust this to your needs.</p>\n" }, { "answer_id": 235308, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p>Maybe this will work:</p>\n\n<pre><code>$property = array(\n 'post_type' =&gt; 'properties',\n 'paged' =&gt; $paged,\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND', \n ),\n);\n\n$features = $_GET['features'];\n\nforeach ($features as $feature) {\n $property['tax_query'][] = array(\n 'taxonomy' =&gt; 'features',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $feature, \n );\n}\n</code></pre>\n" } ]
2016/08/05
[ "https://wordpress.stackexchange.com/questions/235135", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85776/" ]
So on this Custom Post Type list page there is a list of Properties. I have a custom search feature where they can search for Properties with certain Taxonomy Terms - but they can also search for Multiple Taxonomy Terms. **Question**: If someone selects 2 terms then the only Properties that should display in the list are Properties with `term_one` `AND` `term_two` So I tried this below: ``` $required_features_slugs = array(); if( isset ( $_GET['features'] ) ) { $features_slugs = $_GET['features']; } $feature = get_terms('features'); $tmp_required = $required_features_slugs; $property = array( 'post_type' => 'properties', 'paged' => $paged, 'tax_query' => array( array( 'taxonomy' => 'features', 'field' => 'slug', 'terms' => $tmp_required, 'operator' => 'AND', ) ), ); ``` The URL looks like this: ``` features%5B%5D=accredited-landlord&features%5B%5D=cellarbasement ``` Now because these two Features are selected it should only return one Property because there is only one Property with `term_one` `AND` `term_two` together However I don't get this result instead I get 4 Properties because there are 4 Properties. 3 with `term_one` and 1 with `term_two`. What I want to happen is for 1 Property to be returned because there is only one Property with `term_once` `AND` `term_two` together. Is there something wrong that I am doing in the Query? **Edit**: Updated `PHP` file ``` $required_features_slugs = array(); if( isset ( $_GET['features'] ) ) { $required_features_slugs = $_GET['features']; } $all_features = get_terms('features'); if( ! empty( $required_features_slugs ) ) { foreach ( $all_features as $feature ) { $tmp_required = $required_features_slugs; if( ! in_array($feature->slug, $required_features_slugs) ) { array_push( $tmp_required, $feature->slug ); } $property = array( 'post_type' => 'properties', 'paged' => $paged, 'tax_query' => array( 'taxonomy' => 'features', 'field' => 'slug', 'terms' => $tmp_required, 'operator' => 'AND', ), ); } } ``` **Edit #2**: So here is the `var_dump` to the Query: ``` array(3) { ["post_type"]=> string(10) "properties" ["paged"]=> int(1) ["tax_query"]=> array(4) { ["taxonomy"]=> string(8) "features" ["field"]=> string(4) "slug" ["terms"]=> array(2) { [0]=> string(19) "accredited-landlord" [1]=> string(14) "cellarbasement" } ["operator"]=> string(3) "AND" } } ``` And here is the `var_dump` to the terms: ``` array(2) { [0]=> string(19) "accredited-landlord" [1]=> string(14) "cellarbasement" } ```
**Query Arguments:** If `$input_terms` is the input array of term slugs, then you should be able to use (if I understand the question correctly): ``` $property = [ 'post_type' => 'properties', 'paged' => $paged, 'tax_query' => [ [ 'taxonomy' => 'features', 'field' => 'slug', 'terms' => $input_terms, 'operator' => 'AND', ] ], ]; ``` where we added a missing array in the tax query. **Validation:** We should **validate** the input terms first. Here are some examples: * Check the maximum number of allowed terms: ``` $valid_input_terms_max_count = count( $input_terms ) <= 4; ``` * Check the minimum number of allowed terms: ``` $valid_input_terms_min_count = count( $input_terms ) >= 1; ``` * Check if they input terms slugs exists (assumes non-empty input array): ``` $valid_input_terms_slugs = array_reduce( (array) $input_terms, function( $carry, $item ) { return $carry && null !== term_exists( $item, 'features' ); }, true ); ``` where we collect [`term_exists()`](https://developer.wordpress.org/reference/functions/term_exists/) for all the terms into a single boolean value. * We could also match the input slugs against a predefined array of slugs **Generated SQL:** Here's a generated SQL query for two existing term slugs in `$input_terms`: ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND ( ( SELECT COUNT(1) FROM wp_term_relationships WHERE term_taxonomy_id IN (160,161) AND object_id = wp_posts.ID ) = 2 ) AND wp_posts.post_type = 'properties' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10 ``` Hope you can adjust this to your needs.
235,165
<p>I want to add thumbnail to WordPress default recent posts widget, and I want to do it using any available filter. Is there any filter know to this subject/topic</p>
[ { "answer_id": 235166, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>Here's one way to do it through the <code>the_title</code> filter. We can limit the scope to the <em>Recent Posts</em> widget, by initialize it within the <code>widget_posts_args</code> filter and then remove it again after the loop. </p>\n\n<pre><code>/**\n * Recent Posts Widget: Append Thumbs\n */\nadd_filter( 'widget_posts_args', function( array $args )\n{\n add_filter( 'the_title', 'wpse_prepend_thumbnail', 10, 2 );\n add_action( 'loop_end', 'wpse_clean_up' );\n return $args;\n} );\n</code></pre>\n\n<p>where we define</p>\n\n<pre><code>function wpse_prepend_thumbnail( $title, $post_id )\n{\n static $instance = 0;\n\n // Append thumbnail every second time (odd)\n if( 1 === $instance++ % 2 &amp;&amp; has_post_thumbnail( $post_id ) )\n $title = get_the_post_thumbnail( $post_id ) . $title;\n\n return $title;\n} \n</code></pre>\n\n<p>and</p>\n\n<pre><code>function wpse_clean_up( \\WP_Query $q )\n{\n remove_filter( current_filter(), __FUNCTION__ );\n remove_filter( 'the_title', 'wpse_add_thumnail', 10 );\n} \n</code></pre>\n\n<p>Note that because of this check in the <code>WP_Widget_Recent_Posts::widget()</code> method:</p>\n\n<pre><code>get_the_title() ? the_title() : the_ID()\n</code></pre>\n\n<p>the <code>the_title</code> filter is applied two times for each item. That's why we only apply the thumbnail appending for the odd cases. </p>\n\n<p>Also note that this approach assumes non empty titles.</p>\n\n<p>Otherwise it's more flexible to just create/extend a new widget to our needs instead.</p>\n" }, { "answer_id": 235168, "author": "bravokeyl", "author_id": 43098, "author_profile": "https://wordpress.stackexchange.com/users/43098", "pm_score": 0, "selected": false, "text": "<p><strong>No</strong> filter available.</p>\n\n<hr>\n\n<p>Checking the <a href=\"https://developer.wordpress.org/reference/classes/wp_widget_recent_posts/widget/\" rel=\"nofollow\"><code>/wp-includes/widgets/class-wp-recent-posts-widget.php</code></a> the following is the code that outputs the widget</p>\n\n<pre><code>$r = new WP_Query( apply_filters( 'widget_posts_args', array(\n 'posts_per_page' =&gt; $number,\n 'no_found_rows' =&gt; true,\n 'post_status' =&gt; 'publish',\n 'ignore_sticky_posts' =&gt; true\n) ) );\n\nif ($r-&gt;have_posts()) :\n?&gt;\n&lt;?php echo $args['before_widget']; ?&gt;\n&lt;?php if ( $title ) {\n echo $args['before_title'] . $title . $args['after_title'];\n} ?&gt;\n&lt;ul&gt;\n&lt;?php while ( $r-&gt;have_posts() ) : $r-&gt;the_post(); ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php get_the_title() ? the_title() : the_ID(); ?&gt;&lt;/a&gt;\n &lt;?php if ( $show_date ) : ?&gt;\n &lt;span class=\"post-date\"&gt;&lt;?php echo get_the_date(); ?&gt;&lt;/span&gt;\n &lt;?php endif; ?&gt;\n &lt;/li&gt;\n&lt;?php endwhile; ?&gt;\n&lt;/ul&gt;\n&lt;?php echo $args['after_widget']; ?&gt;\n&lt;?php\n// Reset the global $the_post as this query will have stomped on it\nwp_reset_postdata();\n\nendif;\n</code></pre>\n\n<p>Which obviously has no filter to insert some thumbnail or anything in the loop.</p>\n" } ]
2016/08/06
[ "https://wordpress.stackexchange.com/questions/235165", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100562/" ]
I want to add thumbnail to WordPress default recent posts widget, and I want to do it using any available filter. Is there any filter know to this subject/topic
Here's one way to do it through the `the_title` filter. We can limit the scope to the *Recent Posts* widget, by initialize it within the `widget_posts_args` filter and then remove it again after the loop. ``` /** * Recent Posts Widget: Append Thumbs */ add_filter( 'widget_posts_args', function( array $args ) { add_filter( 'the_title', 'wpse_prepend_thumbnail', 10, 2 ); add_action( 'loop_end', 'wpse_clean_up' ); return $args; } ); ``` where we define ``` function wpse_prepend_thumbnail( $title, $post_id ) { static $instance = 0; // Append thumbnail every second time (odd) if( 1 === $instance++ % 2 && has_post_thumbnail( $post_id ) ) $title = get_the_post_thumbnail( $post_id ) . $title; return $title; } ``` and ``` function wpse_clean_up( \WP_Query $q ) { remove_filter( current_filter(), __FUNCTION__ ); remove_filter( 'the_title', 'wpse_add_thumnail', 10 ); } ``` Note that because of this check in the `WP_Widget_Recent_Posts::widget()` method: ``` get_the_title() ? the_title() : the_ID() ``` the `the_title` filter is applied two times for each item. That's why we only apply the thumbnail appending for the odd cases. Also note that this approach assumes non empty titles. Otherwise it's more flexible to just create/extend a new widget to our needs instead.
235,200
<p>I understand Wordpress concept "primary category", but <strong>I do not understand how to fetch the name of the highest category in the hierarchy</strong> for a specific post?</p> <p>Having this code:</p> <pre><code>$category_obj = get_the_category( $post_id ); $category_name = $category_obj[0]-&gt;cat_name; </code></pre> <p>would fetch the category's name of the post, but this category is only the first category listed for the post and that category is not always the primary category.</p> <p>I'm using this outside of "the loop".</p>
[ { "answer_id": 235202, "author": "bestprogrammerintheworld", "author_id": 38848, "author_profile": "https://wordpress.stackexchange.com/users/38848", "pm_score": 0, "selected": false, "text": "<p>I figured this out. I couldn't find any core functionaliy for this in Wordpress, but to retrieve the primary category you could use the get permalink function:</p>\n\n<pre><code>$site_url = get_site_url();\n$post_slug = get_permalink( $post_id );\n$post_slug_remove_siteurl = str_replace( $site_url, '', $post_slug); \n$category_from_slug = explode ('/', $post_slug_remove_siteurl);\n$category_name = $category_from_slug[1];\n</code></pre>\n\n<p>This requires you to have category included in your permalink. The reason why this is possible is that when changing primary category the permalink is changed as well:</p>\n\n<pre><code>&lt;site-url&gt; / &lt;primary category&gt; / &lt;post name&gt;\n</code></pre>\n\n<p>Please tell me if there are any better of achieving this!</p>\n" }, { "answer_id": 283780, "author": "Ravi Patel", "author_id": 35477, "author_profile": "https://wordpress.stackexchange.com/users/35477", "pm_score": 0, "selected": false, "text": "<p><strong>Display Primary Category (Yoast's WordPress SEO)</strong> </p>\n\n<pre><code>&lt;?php\n // SHOW YOAST PRIMARY CATEGORY, OR FIRST CATEGORY\n $category = get_the_category();\n $useCatLink = true;\n // If post has a category assigned.\n if ($category) {\n $category_display = '';\n $category_link = '';\n if (class_exists('WPSEO_Primary_Term')) {\n // Show the post's 'Primary' category, if this Yoast feature is available, &amp; one is set\n $wpseo_primary_term = new WPSEO_Primary_Term('category', get_the_id());\n $wpseo_primary_term = $wpseo_primary_term-&gt;get_primary_term();\n $term = get_term($wpseo_primary_term);\n if (is_wp_error($term)) {\n // Default to first category (not Yoast) if an error is returned\n $category_display = $category[0]-&gt;name;\n $category_link = get_category_link($category[0]-&gt;term_id);\n } else {\n // Yoast Primary category\n $category_display = $term-&gt;name;\n $category_link = get_category_link($term-&gt;term_id);\n }\n } else {\n // Default, display the first category in WP's list of assigned categories\n $category_display = $category[0]-&gt;name;\n $category_link = get_category_link($category[0]-&gt;term_id);\n }\n // Display category\n if (!empty($category_display)) {\n if ($useCatLink == true &amp;&amp; !empty($category_link)) {\n echo '&lt;span class=\"post-category\"&gt;';\n echo '&lt;a href=\"' . $category_link . '\"&gt;' . htmlspecialchars($category_display) . '&lt;/a&gt;';\n echo '&lt;/span&gt;';\n } else {\n echo '&lt;span class=\"post-category\"&gt;' . htmlspecialchars($category_display) . '&lt;/span&gt;';\n }\n }\n }\n ?&gt;\n</code></pre>\n" }, { "answer_id": 395275, "author": "LWS-Mo", "author_id": 88895, "author_profile": "https://wordpress.stackexchange.com/users/88895", "pm_score": 1, "selected": false, "text": "<p>Another idea (which heavily depends on what you are viewing [single or archive] and also your taxonomy-structure) is to look for the term parent.</p>\n<p>Maybe this can help you aswell ...</p>\n<p>You were asking about &quot;highest category in the hierarchy for a specific post&quot;.</p>\n<p>Example:<br />\nA post is associated with <strong>3 terms</strong> of an taxonomy which are <strong>hierachical</strong>:</p>\n<pre><code>Parent Term\n-First-Child Term\n--Second-Child Term\n</code></pre>\n<p>You could get all the associated terms of this post:</p>\n<pre><code>$all_terms = get_the_terms( $post_id, $taxonomy );\n</code></pre>\n<p>And than find the term which has a <strong>parent</strong> of <strong>0</strong>:</p>\n<pre><code>foreach($all_terms as $term) {\n\n if($term-&gt;parent == 0){\n //here you have the data of the topmost parent, e.g. &quot;Parent Term&quot;\n\n // get parent term ID\n $parent_id = $term-&gt;term_id; \n\n // get term obj from ID to get term name\n $parent_obj = get_term_by( 'id', $parent_id, $taxonomy );\n \n // show parent term name\n echo $parent_obj-&gt;name; // &quot;Parent Term&quot;\n\n // show parent term permalink URL\n echo = get_term_link( $parent_id );\n }\n\n}\n</code></pre>\n<p>As you see, this will only work if the post has only one parent and than child-terms assiciated. For other setups this will not work!</p>\n" } ]
2016/08/07
[ "https://wordpress.stackexchange.com/questions/235200", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38848/" ]
I understand Wordpress concept "primary category", but **I do not understand how to fetch the name of the highest category in the hierarchy** for a specific post? Having this code: ``` $category_obj = get_the_category( $post_id ); $category_name = $category_obj[0]->cat_name; ``` would fetch the category's name of the post, but this category is only the first category listed for the post and that category is not always the primary category. I'm using this outside of "the loop".
Another idea (which heavily depends on what you are viewing [single or archive] and also your taxonomy-structure) is to look for the term parent. Maybe this can help you aswell ... You were asking about "highest category in the hierarchy for a specific post". Example: A post is associated with **3 terms** of an taxonomy which are **hierachical**: ``` Parent Term -First-Child Term --Second-Child Term ``` You could get all the associated terms of this post: ``` $all_terms = get_the_terms( $post_id, $taxonomy ); ``` And than find the term which has a **parent** of **0**: ``` foreach($all_terms as $term) { if($term->parent == 0){ //here you have the data of the topmost parent, e.g. "Parent Term" // get parent term ID $parent_id = $term->term_id; // get term obj from ID to get term name $parent_obj = get_term_by( 'id', $parent_id, $taxonomy ); // show parent term name echo $parent_obj->name; // "Parent Term" // show parent term permalink URL echo = get_term_link( $parent_id ); } } ``` As you see, this will only work if the post has only one parent and than child-terms assiciated. For other setups this will not work!
235,227
<p>I'm kinda stuck. I want to show 3 sections on an author page. Section one shows all uploaded images by author based on tag Tattoo. Section two shows all uploaded images by author based on tag Piercing. Section three shows all uploaded images by author based on tag Modification. So far so good. This is the code I'm using to do this for one section:</p> <pre><code>&lt;!--- start test ---&gt; &lt;div class="uk-grid" data-uk-grid-margin&gt; &lt;div class="uk-width-1-1"&gt; &lt;h2&gt;Tattoo Work by &lt;span style="text-transform: capitalize;"&gt;&lt;?php the_author_meta('user_nicename'); ?&gt;&lt;/span&gt;:&lt;/h2&gt; &lt;ul id="switcher-content" class="uk-switcher"&gt; &lt;li class="uk-active"&gt; &lt;div class="uk-grid" data-uk-grid-margin&gt; &lt;?php // Loop Tattoo $first_query = new WP_Query('cat=1&amp;author=' . $post-&gt;post_author . '&amp;order=DESC&amp;tag=Tattoo&amp;posts_per_page=1000'); while($first_query-&gt;have_posts()) : $first_query-&gt;the_post(); ?&gt; &lt;div class="uk-width-medium-1-4"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;?MediaTag=Tattoo"&gt; &lt;?php if ( has_post_thumbnail() ) { the_post_thumbnail('artiststhumbnailsize'); } ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;!--- end test ---&gt;` </code></pre> <p>BUT, I want to display the h2 title per section only if the section has images. To prevent the h2 title is displayed without ever having images below. So I kinda need to pre check the query and I can't find any thing to make this happen. The other two queries are $second_query and $third_query with each their own tag definition. Thanks for the help in advance!</p>
[ { "answer_id": 235229, "author": "guido", "author_id": 98339, "author_profile": "https://wordpress.stackexchange.com/users/98339", "pm_score": 3, "selected": true, "text": "<p>You can use the function <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_pluck\" rel=\"nofollow\">wp_list_pluck</a> to get the ID of the posts retrieved from the query.</p>\n\n<p>Just move the query before the h2 element and get the posts ID's:</p>\n\n<pre><code>// Set a bool to know if at least one post has post thumbnail.\n$has_thumb = false;\n$first_query = new WP_Query('cat=1&amp;author=' . $post-&gt;post_author . '&amp;order=DESC&amp;tag=Tattoo&amp;posts_per_page=1000');\n\n// Check if the query have posts.\nif ( $first_query-&gt;have_posts() ) {\n // Get the posts id's.\n $ids = wp_list_pluck($first_query-&gt;posts, 'ID');\n\n foreach( $ids as $id ) {\n if ( has_post_thumbnail($id) ) {\n $has_thumb = true;\n break; // If at least we have a post thubmnail we don't need to continue.\n }\n }\n}\n</code></pre>\n\n<p>Then you can check if there are thumbnails and show the h2 if so.</p>\n\n<pre><code>&lt;?php if ( $has_thumb ) : ?&gt;\n &lt;h2&gt;Tattoo Work by &lt;span style=\"text-transform: capitalize;\"&gt;&lt;?php the_author_meta('user_nicename'); ?&gt;&lt;/span&gt;:&lt;/h2&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 235230, "author": "jgraup", "author_id": 84219, "author_profile": "https://wordpress.stackexchange.com/users/84219", "pm_score": 1, "selected": false, "text": "<p>Set a variable like <code>$has_images = false;</code> then loop through your posts to only check <code>$has_images = $has_images || has_post_thumbnail()</code>. Now only generate the section <code>if ( $has_images ) { }</code>. Just be sure to rewind the posts before you loop through the query again - <a href=\"https://codex.wordpress.org/Function_Reference/rewind_posts\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/rewind_posts</a></p>\n" } ]
2016/08/07
[ "https://wordpress.stackexchange.com/questions/235227", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9442/" ]
I'm kinda stuck. I want to show 3 sections on an author page. Section one shows all uploaded images by author based on tag Tattoo. Section two shows all uploaded images by author based on tag Piercing. Section three shows all uploaded images by author based on tag Modification. So far so good. This is the code I'm using to do this for one section: ``` <!--- start test ---> <div class="uk-grid" data-uk-grid-margin> <div class="uk-width-1-1"> <h2>Tattoo Work by <span style="text-transform: capitalize;"><?php the_author_meta('user_nicename'); ?></span>:</h2> <ul id="switcher-content" class="uk-switcher"> <li class="uk-active"> <div class="uk-grid" data-uk-grid-margin> <?php // Loop Tattoo $first_query = new WP_Query('cat=1&author=' . $post->post_author . '&order=DESC&tag=Tattoo&posts_per_page=1000'); while($first_query->have_posts()) : $first_query->the_post(); ?> <div class="uk-width-medium-1-4"> <a href="<?php the_permalink() ?>?MediaTag=Tattoo"> <?php if ( has_post_thumbnail() ) { the_post_thumbnail('artiststhumbnailsize'); } ?> </a> </div> <?php endwhile; wp_reset_postdata(); ?> </div> </li> </ul> </div> </div> <!--- end test --->` ``` BUT, I want to display the h2 title per section only if the section has images. To prevent the h2 title is displayed without ever having images below. So I kinda need to pre check the query and I can't find any thing to make this happen. The other two queries are $second\_query and $third\_query with each their own tag definition. Thanks for the help in advance!
You can use the function [wp\_list\_pluck](https://codex.wordpress.org/Function_Reference/wp_list_pluck) to get the ID of the posts retrieved from the query. Just move the query before the h2 element and get the posts ID's: ``` // Set a bool to know if at least one post has post thumbnail. $has_thumb = false; $first_query = new WP_Query('cat=1&author=' . $post->post_author . '&order=DESC&tag=Tattoo&posts_per_page=1000'); // Check if the query have posts. if ( $first_query->have_posts() ) { // Get the posts id's. $ids = wp_list_pluck($first_query->posts, 'ID'); foreach( $ids as $id ) { if ( has_post_thumbnail($id) ) { $has_thumb = true; break; // If at least we have a post thubmnail we don't need to continue. } } } ``` Then you can check if there are thumbnails and show the h2 if so. ``` <?php if ( $has_thumb ) : ?> <h2>Tattoo Work by <span style="text-transform: capitalize;"><?php the_author_meta('user_nicename'); ?></span>:</h2> <?php endif; ?> ```
235,241
<p>Code:</p> <pre><code>&lt;?php do_action('post_footer'); ?&gt; </code></pre> <p><a href="https://developer.wordpress.org/reference/functions/do_action/" rel="nofollow">Based on some reading</a>, this appears to call a hook action. So, I went through all of the PHP files in the <code>Editor</code> and I don't find <code>post_footer</code> anywhere. I also noticed it call these hooks elsewhere, so it would be useful to know where these are stored. What files are these hook actions stored in?</p> <p>What I searched for using is <code>add_action</code> in each file to discover the <code>post_footer</code> as one of the parameters, but never found anything for <code>post_footer</code> as an action. Where else would these action hooks be, if not in the php files?</p>
[ { "answer_id": 235248, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>Anywhere within the code that WordPress runs to generate a page, <code>do_action()</code> and <code>do_filter()</code> define a hook. These hook definitions can be in core, in plugins or in themes.</p>\n\n<p>I'm guessing that your <code>do_action('post_footer')</code> is within a theme, simply as I don't recognise it as a standard hook from core. The theme's author has put that there so that authors of plugins or child themes can use it to easily hook in their own code.</p>\n\n<p>While there are guides to hooks around the web, sometimes you're best digging into core code to find the ones you need, as they do change with time.</p>\n" }, { "answer_id": 235249, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Hooks/actions are better thought of as events.</p>\n\n<p>When you run this code:</p>\n\n<pre><code>add_action( 'post_footer', 'toms_footer_stuff' );\n</code></pre>\n\n<p>You're saying that when the <code>post_footer</code> event happens, run the <code>toms_footer_stuff</code> function.</p>\n\n<p>These functions take the form of:</p>\n\n<pre><code>add_action( name_of_action, php_callable );\n</code></pre>\n\n<p>A PHP callable is something that can be called represented as an object. It can be any of these:</p>\n\n<pre><code>add_action( 'post_footer', 'toms_footer_stuff' ); // a function\nadd_action( 'post_footer', array( 'toms_class', 'toms_footer_stuff' ); // a static method on a class\nadd_action( 'post_footer', array( $toms_class, 'toms_footer_stuff' ); // a method on an object\nadd_action( 'post_footer', function() { echo \"hello world\"; } ); // an anonymous function\nadd_action( 'post_footer', $toms_closure ); // a Closure\n</code></pre>\n\n<p>When you call <code>do_action('post_footer')</code>, you're saying that the <code>post_footer</code> event is happening, call all the things that have hooked into it. There's no <code>post_footer</code> function to call ( unless you define one yourself but that would just be a coincidence, it wouldn't run unless you called <code>add_action</code> ).</p>\n\n<p><code>post_footer</code> has more in common with a key in an array.</p>\n\n<p>Filters are similar, except they take a value as their first function argument, and return it.</p>\n\n<p>Internally they use the same system as actions, as such these 2 calls should do the same thing:</p>\n\n<pre><code>do_action( 'init' );\napply_filters( 'init', null ); // not recommended/tested\n</code></pre>\n\n<p>Actions are for doing work, filters are for adjusting or modifying data/content. If you do work in a filter, your site will slow down. Filters get called a lot more than actions and tend to happen multiple times ). Actions on the other hand tend to happen once at a specific time.</p>\n" } ]
2016/08/07
[ "https://wordpress.stackexchange.com/questions/235241", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100605/" ]
Code: ``` <?php do_action('post_footer'); ?> ``` [Based on some reading](https://developer.wordpress.org/reference/functions/do_action/), this appears to call a hook action. So, I went through all of the PHP files in the `Editor` and I don't find `post_footer` anywhere. I also noticed it call these hooks elsewhere, so it would be useful to know where these are stored. What files are these hook actions stored in? What I searched for using is `add_action` in each file to discover the `post_footer` as one of the parameters, but never found anything for `post_footer` as an action. Where else would these action hooks be, if not in the php files?
Hooks/actions are better thought of as events. When you run this code: ``` add_action( 'post_footer', 'toms_footer_stuff' ); ``` You're saying that when the `post_footer` event happens, run the `toms_footer_stuff` function. These functions take the form of: ``` add_action( name_of_action, php_callable ); ``` A PHP callable is something that can be called represented as an object. It can be any of these: ``` add_action( 'post_footer', 'toms_footer_stuff' ); // a function add_action( 'post_footer', array( 'toms_class', 'toms_footer_stuff' ); // a static method on a class add_action( 'post_footer', array( $toms_class, 'toms_footer_stuff' ); // a method on an object add_action( 'post_footer', function() { echo "hello world"; } ); // an anonymous function add_action( 'post_footer', $toms_closure ); // a Closure ``` When you call `do_action('post_footer')`, you're saying that the `post_footer` event is happening, call all the things that have hooked into it. There's no `post_footer` function to call ( unless you define one yourself but that would just be a coincidence, it wouldn't run unless you called `add_action` ). `post_footer` has more in common with a key in an array. Filters are similar, except they take a value as their first function argument, and return it. Internally they use the same system as actions, as such these 2 calls should do the same thing: ``` do_action( 'init' ); apply_filters( 'init', null ); // not recommended/tested ``` Actions are for doing work, filters are for adjusting or modifying data/content. If you do work in a filter, your site will slow down. Filters get called a lot more than actions and tend to happen multiple times ). Actions on the other hand tend to happen once at a specific time.
235,245
<p>I am trying to have multiple separate style sheets load for each page (page specific) for a WordPress website. I am converting an HTML website to a WordPress website for a client. For example; <code>home.css</code> &amp; <code>consol.css</code> for the home page (<code>home.php</code>) and <code>pricing-hours.css</code> &amp; <code>consoltwo.css</code> for <code>pricing-hours.php</code>. I am trying to do this using the <code>functions.php</code> file, with code I have so far below:</p> <pre><code>function everydaytherapy_script_enqueue() { if ( is_page_template( 'home.php' ) ) { wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://d1azc1qln24ryf.cloudfront.net/47089/SocialIconsNCD/style-cf.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/baile.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/consolidated-0.css', array(), '1.0.0', 'all'); wp_enqueue_script('customjs', get_template_directory_uri() . '/js/javascript.js', array() '1.0.0', bool $in_true); } elseif ( is_page_template( 'pricing-hours.php' ) ) { wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://d1azc1qln24ryf.cloudfront.net/47089/SocialIconsNCD/style-cf.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/pricing-hours.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/consolidated-0.css', array(), '1.0.0', 'all'); wp_enqueue_script('customjs', get_template_directory_uri() . '/js/javascript.js', array() '1.0.0', bool $in_true); } } else { </code></pre>
[ { "answer_id": 235248, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>Anywhere within the code that WordPress runs to generate a page, <code>do_action()</code> and <code>do_filter()</code> define a hook. These hook definitions can be in core, in plugins or in themes.</p>\n\n<p>I'm guessing that your <code>do_action('post_footer')</code> is within a theme, simply as I don't recognise it as a standard hook from core. The theme's author has put that there so that authors of plugins or child themes can use it to easily hook in their own code.</p>\n\n<p>While there are guides to hooks around the web, sometimes you're best digging into core code to find the ones you need, as they do change with time.</p>\n" }, { "answer_id": 235249, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Hooks/actions are better thought of as events.</p>\n\n<p>When you run this code:</p>\n\n<pre><code>add_action( 'post_footer', 'toms_footer_stuff' );\n</code></pre>\n\n<p>You're saying that when the <code>post_footer</code> event happens, run the <code>toms_footer_stuff</code> function.</p>\n\n<p>These functions take the form of:</p>\n\n<pre><code>add_action( name_of_action, php_callable );\n</code></pre>\n\n<p>A PHP callable is something that can be called represented as an object. It can be any of these:</p>\n\n<pre><code>add_action( 'post_footer', 'toms_footer_stuff' ); // a function\nadd_action( 'post_footer', array( 'toms_class', 'toms_footer_stuff' ); // a static method on a class\nadd_action( 'post_footer', array( $toms_class, 'toms_footer_stuff' ); // a method on an object\nadd_action( 'post_footer', function() { echo \"hello world\"; } ); // an anonymous function\nadd_action( 'post_footer', $toms_closure ); // a Closure\n</code></pre>\n\n<p>When you call <code>do_action('post_footer')</code>, you're saying that the <code>post_footer</code> event is happening, call all the things that have hooked into it. There's no <code>post_footer</code> function to call ( unless you define one yourself but that would just be a coincidence, it wouldn't run unless you called <code>add_action</code> ).</p>\n\n<p><code>post_footer</code> has more in common with a key in an array.</p>\n\n<p>Filters are similar, except they take a value as their first function argument, and return it.</p>\n\n<p>Internally they use the same system as actions, as such these 2 calls should do the same thing:</p>\n\n<pre><code>do_action( 'init' );\napply_filters( 'init', null ); // not recommended/tested\n</code></pre>\n\n<p>Actions are for doing work, filters are for adjusting or modifying data/content. If you do work in a filter, your site will slow down. Filters get called a lot more than actions and tend to happen multiple times ). Actions on the other hand tend to happen once at a specific time.</p>\n" } ]
2016/08/07
[ "https://wordpress.stackexchange.com/questions/235245", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100619/" ]
I am trying to have multiple separate style sheets load for each page (page specific) for a WordPress website. I am converting an HTML website to a WordPress website for a client. For example; `home.css` & `consol.css` for the home page (`home.php`) and `pricing-hours.css` & `consoltwo.css` for `pricing-hours.php`. I am trying to do this using the `functions.php` file, with code I have so far below: ``` function everydaytherapy_script_enqueue() { if ( is_page_template( 'home.php' ) ) { wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://d1azc1qln24ryf.cloudfront.net/47089/SocialIconsNCD/style-cf.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/baile.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/consolidated-0.css', array(), '1.0.0', 'all'); wp_enqueue_script('customjs', get_template_directory_uri() . '/js/javascript.js', array() '1.0.0', bool $in_true); } elseif ( is_page_template( 'pricing-hours.php' ) ) { wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . 'https://d1azc1qln24ryf.cloudfront.net/47089/SocialIconsNCD/style-cf.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/pricing-hours.css', array(), '1.0.0', 'all'); wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/consolidated-0.css', array(), '1.0.0', 'all'); wp_enqueue_script('customjs', get_template_directory_uri() . '/js/javascript.js', array() '1.0.0', bool $in_true); } } else { ```
Hooks/actions are better thought of as events. When you run this code: ``` add_action( 'post_footer', 'toms_footer_stuff' ); ``` You're saying that when the `post_footer` event happens, run the `toms_footer_stuff` function. These functions take the form of: ``` add_action( name_of_action, php_callable ); ``` A PHP callable is something that can be called represented as an object. It can be any of these: ``` add_action( 'post_footer', 'toms_footer_stuff' ); // a function add_action( 'post_footer', array( 'toms_class', 'toms_footer_stuff' ); // a static method on a class add_action( 'post_footer', array( $toms_class, 'toms_footer_stuff' ); // a method on an object add_action( 'post_footer', function() { echo "hello world"; } ); // an anonymous function add_action( 'post_footer', $toms_closure ); // a Closure ``` When you call `do_action('post_footer')`, you're saying that the `post_footer` event is happening, call all the things that have hooked into it. There's no `post_footer` function to call ( unless you define one yourself but that would just be a coincidence, it wouldn't run unless you called `add_action` ). `post_footer` has more in common with a key in an array. Filters are similar, except they take a value as their first function argument, and return it. Internally they use the same system as actions, as such these 2 calls should do the same thing: ``` do_action( 'init' ); apply_filters( 'init', null ); // not recommended/tested ``` Actions are for doing work, filters are for adjusting or modifying data/content. If you do work in a filter, your site will slow down. Filters get called a lot more than actions and tend to happen multiple times ). Actions on the other hand tend to happen once at a specific time.
235,277
<p>I'm using a Custom Theme to re-design our website. However, I'm getting an issue where the Menu jumps around and shows all links, before quickly collapsing them under the parent options, in the menu. </p> <p>Here is the staging site: <a href="http://volocommerce.staging.wpengine.com/" rel="nofollow noreferrer">http://volocommerce.staging.wpengine.com/</a> </p> <p>However, this is the code I'm using:</p> <pre><code> &lt;nav class="navbar navbar-default" role="navigation"&gt; &lt;div class="container-fluid"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar bar-1"&gt;&lt;/span&gt; &lt;span class="icon-bar bar-2"&gt;&lt;/span&gt; &lt;span class="icon-bar bar-3"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"&gt; &lt;div class="navbar navbar-default navbar-fixed-top"&gt; &lt;div class="container"&gt; &lt;div id="" class=""&gt; &lt;?php //$walker = new Menu_With_Description; wp_nav_menu (array ('theme_location' =&gt; 'header_menu', 'container' =&gt; 'div', 'container_class' =&gt; '', 'container_id' =&gt; '', 'menu_class' =&gt; 'menu', 'menu_id' =&gt; '', 'echo' =&gt; true, 'fallback_cb' =&gt; 'wp_page_menu', 'before' =&gt; '', 'after' =&gt; '', 'link_before' =&gt; '', 'link_after' =&gt; '', 'items_wrap' =&gt; '&lt;ul class="nav navbar-nav top_items"&gt;%3$s&lt;/ul&gt;', 'depth' =&gt; 0, //'walker' =&gt; $walker, )); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; </code></pre> <p>And here is the script for the mobile menu/scroll menu:</p> <pre><code> &lt;script&gt; $(function(){ $('.navbar ul li:has(ul)').addClass('dropdown'); $('.navbar navbar-collapse ul:has(li)').addClass('dropdown-menu'); $('.navbar ul li ul:has(li)').addClass('dropdown-menu'); $('.navbar ul li ul li:has(div)').addClass('yamm-content'); $('.navbar .lang_drop ul li ul:has(li)').addClass('single_drop'); $('.navbar .lang_drop ul li:has(ul)').removeClass(''); //yamm-fw $('.dropdown:has(a)').addClass('dropdown-toggle'); $('.more_menu').addClass('yamm-fw'); }); $(window).scroll(function(e){ $el = $('.head_con'); if ($(this).scrollTop() &gt; 150 ){ $('.head_con').addClass('head_con_scroll'); $('.logo_con').addClass('logo_con_scroll'); $('.menu-item').addClass('menu-item_scroll'); $('.head_phone_con').addClass('head_phone_con_scroll'); $('.head_call_us').addClass('head_call_us_scroll'); $('.ceo_message').addClass('ceo_message_scroll'); } if ($(this).scrollTop() &lt; 150 ) { $('.head_con').removeClass('head_con_scroll'); $('.logo_con').removeClass('logo_con_scroll'); $('.menu-item').removeClass('menu-item_scroll'); $('.head_phone_con').removeClass('head_phone_con_scroll'); $('.head_call_us').removeClass('head_call_us_scroll'); $('.ceo_message').removeClass('ceo_message_scroll'); } }); &lt;/script&gt; </code></pre> <p>What I'm trying to stop occurring is this, which happens everytime the page is loading - and it's very frustrating: <a href="https://i.stack.imgur.com/fUuIR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fUuIR.jpg" alt="Jumping Menu"></a></p> <p>I've since tried using jQuery to hide the elements on page load, then remove the hide class once the page load is complete - this failed too :( </p> <pre><code>&lt;script&gt; $(document).on("pagecontainerbeforeload",function(){ $('.dropdown-menu').addClass('hidden-element'); }); $(document).on("pageload",function(){ $('.dropdown-menu').removeClass('hidden-element'); }); &lt;/script&gt; &lt;style&gt; .hidden-element {display:none!important;} &lt;/style&gt; </code></pre>
[ { "answer_id": 235248, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>Anywhere within the code that WordPress runs to generate a page, <code>do_action()</code> and <code>do_filter()</code> define a hook. These hook definitions can be in core, in plugins or in themes.</p>\n\n<p>I'm guessing that your <code>do_action('post_footer')</code> is within a theme, simply as I don't recognise it as a standard hook from core. The theme's author has put that there so that authors of plugins or child themes can use it to easily hook in their own code.</p>\n\n<p>While there are guides to hooks around the web, sometimes you're best digging into core code to find the ones you need, as they do change with time.</p>\n" }, { "answer_id": 235249, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Hooks/actions are better thought of as events.</p>\n\n<p>When you run this code:</p>\n\n<pre><code>add_action( 'post_footer', 'toms_footer_stuff' );\n</code></pre>\n\n<p>You're saying that when the <code>post_footer</code> event happens, run the <code>toms_footer_stuff</code> function.</p>\n\n<p>These functions take the form of:</p>\n\n<pre><code>add_action( name_of_action, php_callable );\n</code></pre>\n\n<p>A PHP callable is something that can be called represented as an object. It can be any of these:</p>\n\n<pre><code>add_action( 'post_footer', 'toms_footer_stuff' ); // a function\nadd_action( 'post_footer', array( 'toms_class', 'toms_footer_stuff' ); // a static method on a class\nadd_action( 'post_footer', array( $toms_class, 'toms_footer_stuff' ); // a method on an object\nadd_action( 'post_footer', function() { echo \"hello world\"; } ); // an anonymous function\nadd_action( 'post_footer', $toms_closure ); // a Closure\n</code></pre>\n\n<p>When you call <code>do_action('post_footer')</code>, you're saying that the <code>post_footer</code> event is happening, call all the things that have hooked into it. There's no <code>post_footer</code> function to call ( unless you define one yourself but that would just be a coincidence, it wouldn't run unless you called <code>add_action</code> ).</p>\n\n<p><code>post_footer</code> has more in common with a key in an array.</p>\n\n<p>Filters are similar, except they take a value as their first function argument, and return it.</p>\n\n<p>Internally they use the same system as actions, as such these 2 calls should do the same thing:</p>\n\n<pre><code>do_action( 'init' );\napply_filters( 'init', null ); // not recommended/tested\n</code></pre>\n\n<p>Actions are for doing work, filters are for adjusting or modifying data/content. If you do work in a filter, your site will slow down. Filters get called a lot more than actions and tend to happen multiple times ). Actions on the other hand tend to happen once at a specific time.</p>\n" } ]
2016/08/08
[ "https://wordpress.stackexchange.com/questions/235277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94390/" ]
I'm using a Custom Theme to re-design our website. However, I'm getting an issue where the Menu jumps around and shows all links, before quickly collapsing them under the parent options, in the menu. Here is the staging site: <http://volocommerce.staging.wpengine.com/> However, this is the code I'm using: ``` <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar bar-1"></span> <span class="icon-bar bar-2"></span> <span class="icon-bar bar-3"></span> </button> </div> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <div class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div id="" class=""> <?php //$walker = new Menu_With_Description; wp_nav_menu (array ('theme_location' => 'header_menu', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul class="nav navbar-nav top_items">%3$s</ul>', 'depth' => 0, //'walker' => $walker, )); ?> </div> </div> </div> </div> </nav> ``` And here is the script for the mobile menu/scroll menu: ``` <script> $(function(){ $('.navbar ul li:has(ul)').addClass('dropdown'); $('.navbar navbar-collapse ul:has(li)').addClass('dropdown-menu'); $('.navbar ul li ul:has(li)').addClass('dropdown-menu'); $('.navbar ul li ul li:has(div)').addClass('yamm-content'); $('.navbar .lang_drop ul li ul:has(li)').addClass('single_drop'); $('.navbar .lang_drop ul li:has(ul)').removeClass(''); //yamm-fw $('.dropdown:has(a)').addClass('dropdown-toggle'); $('.more_menu').addClass('yamm-fw'); }); $(window).scroll(function(e){ $el = $('.head_con'); if ($(this).scrollTop() > 150 ){ $('.head_con').addClass('head_con_scroll'); $('.logo_con').addClass('logo_con_scroll'); $('.menu-item').addClass('menu-item_scroll'); $('.head_phone_con').addClass('head_phone_con_scroll'); $('.head_call_us').addClass('head_call_us_scroll'); $('.ceo_message').addClass('ceo_message_scroll'); } if ($(this).scrollTop() < 150 ) { $('.head_con').removeClass('head_con_scroll'); $('.logo_con').removeClass('logo_con_scroll'); $('.menu-item').removeClass('menu-item_scroll'); $('.head_phone_con').removeClass('head_phone_con_scroll'); $('.head_call_us').removeClass('head_call_us_scroll'); $('.ceo_message').removeClass('ceo_message_scroll'); } }); </script> ``` What I'm trying to stop occurring is this, which happens everytime the page is loading - and it's very frustrating: [![Jumping Menu](https://i.stack.imgur.com/fUuIR.jpg)](https://i.stack.imgur.com/fUuIR.jpg) I've since tried using jQuery to hide the elements on page load, then remove the hide class once the page load is complete - this failed too :( ``` <script> $(document).on("pagecontainerbeforeload",function(){ $('.dropdown-menu').addClass('hidden-element'); }); $(document).on("pageload",function(){ $('.dropdown-menu').removeClass('hidden-element'); }); </script> <style> .hidden-element {display:none!important;} </style> ```
Hooks/actions are better thought of as events. When you run this code: ``` add_action( 'post_footer', 'toms_footer_stuff' ); ``` You're saying that when the `post_footer` event happens, run the `toms_footer_stuff` function. These functions take the form of: ``` add_action( name_of_action, php_callable ); ``` A PHP callable is something that can be called represented as an object. It can be any of these: ``` add_action( 'post_footer', 'toms_footer_stuff' ); // a function add_action( 'post_footer', array( 'toms_class', 'toms_footer_stuff' ); // a static method on a class add_action( 'post_footer', array( $toms_class, 'toms_footer_stuff' ); // a method on an object add_action( 'post_footer', function() { echo "hello world"; } ); // an anonymous function add_action( 'post_footer', $toms_closure ); // a Closure ``` When you call `do_action('post_footer')`, you're saying that the `post_footer` event is happening, call all the things that have hooked into it. There's no `post_footer` function to call ( unless you define one yourself but that would just be a coincidence, it wouldn't run unless you called `add_action` ). `post_footer` has more in common with a key in an array. Filters are similar, except they take a value as their first function argument, and return it. Internally they use the same system as actions, as such these 2 calls should do the same thing: ``` do_action( 'init' ); apply_filters( 'init', null ); // not recommended/tested ``` Actions are for doing work, filters are for adjusting or modifying data/content. If you do work in a filter, your site will slow down. Filters get called a lot more than actions and tend to happen multiple times ). Actions on the other hand tend to happen once at a specific time.
235,288
<p>There are quite a few threads going on regarding this but they all seem to say the same thing (which I tried) but I keep getting a redirect loop. I already tried changing the WordPress Address (URL) and Site Address (URL) in the General settings (my admin panel is already on https)</p> <p>My .htaccess looks like:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On # start https redirect RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # end https redirect RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Anyone an idea?</p>
[ { "answer_id": 235302, "author": "Tejas Dixit", "author_id": 80791, "author_profile": "https://wordpress.stackexchange.com/users/80791", "pm_score": -1, "selected": false, "text": "<p>Can you try this?</p>\n\n<pre>\n# BEGIN WordPress\n\nRewriteEngine On\n\n# start https redirect\nRewriteCond %{HTTP_HOST} !^www\\.\nRewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]\n# end https redirect\n\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\n\n# END WordPress\n</pre>\n" }, { "answer_id": 236765, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": true, "text": "<p>I'd steer clear on editing the <code>.htaccess</code> if you're just updating your website from HTTP to HTTPS. Try an alternative route:</p>\n<p>First, revert your <code>.htaccess</code> back to the default settings:</p>\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n<p>Next, you need to ensures that all of the URLs for your website are up-to-date, try the following steps using the <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Search Replace DB tool</a>:</p>\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search &amp; Replace Script here</a></li>\n<li>Unzip the file and drop the folder in your <strong>localhost</strong> where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://web.site/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>It should be pretty self-explanatory up to this point: enter your HTTPS link in the <strong><code>search for…</code></strong> field and the new HTTPS link in the <strong><code>replace with…</code></strong> field</li>\n</ol>\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder.</p>\n<h3>However...</h3>\n<p>If you still insist on having your HTTP redirect to HTTPS via the <code>.htaccess</code> add the following in between the <code>&lt;IfModule mod_rewrite.c&gt;</code> tag:</p>\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n</code></pre>\n<p>It should look like the following:</p>\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n# Rewrite HTTP to HTTPS\nRewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2016/08/08
[ "https://wordpress.stackexchange.com/questions/235288", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98525/" ]
There are quite a few threads going on regarding this but they all seem to say the same thing (which I tried) but I keep getting a redirect loop. I already tried changing the WordPress Address (URL) and Site Address (URL) in the General settings (my admin panel is already on https) My .htaccess looks like: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On # start https redirect RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # end https redirect RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` Anyone an idea?
I'd steer clear on editing the `.htaccess` if you're just updating your website from HTTP to HTTPS. Try an alternative route: First, revert your `.htaccess` back to the default settings: ``` # 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 ``` Next, you need to ensures that all of the URLs for your website are up-to-date, try the following steps using the [Search Replace DB tool](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/): 1. Go and download [Interconnect IT's Database Search & Replace Script here](https://github.com/interconnectit/Search-Replace-DB/archive/master.zip) 2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** ([screenshot](https://i.stack.imgur.com/J9Ga5.png)) 3. Navigate to the new folder you created in your browser (ex: `http://web.site/replace`) and [you will see the search/replace tool](https://i.stack.imgur.com/pbED1.png) 4. It should be pretty self-explanatory up to this point: enter your HTTPS link in the **`search for…`** field and the new HTTPS link in the **`replace with…`** field You can click the *dry run* button under *actions* to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder. ### However... If you still insist on having your HTTP redirect to HTTPS via the `.htaccess` add the following in between the `<IfModule mod_rewrite.c>` tag: ``` RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] ``` It should look like the following: ``` # 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] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] </IfModule> # END WordPress ```
235,298
<p>I have a search page where if the main search returns 0 results then the following query will be used.</p> <p>The code is </p> <pre><code>$num_res = $wp_query-&gt;post_count; $get_search_term = get_search_query(); if($num_res == 0) { $args = array( 'post_type' =&gt; 'resources', 'meta_key' =&gt; 'resource_txt', 'meta_value' =&gt; $get_search_term, 'meta_compare' =&gt; 'LIKE' ); $custom_query = new WP_Query( $args ); } </code></pre> <p>Now I am getting an error which says <strong>"Not unique table/alias: 'wp_postmeta'"</strong></p> <p>When I print the second query in browser it says,</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'resource_txt' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%insurance claim%' ) ) AND wp_posts.post_type = 'resources' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10 </code></pre> <p>Is it like, I have to close the previous query and then run the custom query. Any help is highly appreciated.</p>
[ { "answer_id": 235302, "author": "Tejas Dixit", "author_id": 80791, "author_profile": "https://wordpress.stackexchange.com/users/80791", "pm_score": -1, "selected": false, "text": "<p>Can you try this?</p>\n\n<pre>\n# BEGIN WordPress\n\nRewriteEngine On\n\n# start https redirect\nRewriteCond %{HTTP_HOST} !^www\\.\nRewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]\n# end https redirect\n\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\n\n# END WordPress\n</pre>\n" }, { "answer_id": 236765, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 1, "selected": true, "text": "<p>I'd steer clear on editing the <code>.htaccess</code> if you're just updating your website from HTTP to HTTPS. Try an alternative route:</p>\n<p>First, revert your <code>.htaccess</code> back to the default settings:</p>\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n<p>Next, you need to ensures that all of the URLs for your website are up-to-date, try the following steps using the <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Search Replace DB tool</a>:</p>\n<ol>\n<li>Go and download <a href=\"https://github.com/interconnectit/Search-Replace-DB/archive/master.zip\" rel=\"nofollow noreferrer\">Interconnect IT's Database Search &amp; Replace Script here</a></li>\n<li>Unzip the file and drop the folder in your <strong>localhost</strong> where your WordPress is installed (the root) and rename the folder to <strong><code>replace</code></strong> (<a href=\"https://i.stack.imgur.com/J9Ga5.png\" rel=\"nofollow noreferrer\">screenshot</a>)</li>\n<li>Navigate to the new folder you created in your browser (ex: <code>http://web.site/replace</code>) and <a href=\"https://i.stack.imgur.com/pbED1.png\" rel=\"nofollow noreferrer\">you will see the search/replace tool</a></li>\n<li>It should be pretty self-explanatory up to this point: enter your HTTPS link in the <strong><code>search for…</code></strong> field and the new HTTPS link in the <strong><code>replace with…</code></strong> field</li>\n</ol>\n<p>You can click the <em>dry run</em> button under <em>actions</em> to see what it will be replacing before you execute the script. Once you're done be sure to remove the <code>/replace/</code> folder.</p>\n<h3>However...</h3>\n<p>If you still insist on having your HTTP redirect to HTTPS via the <code>.htaccess</code> add the following in between the <code>&lt;IfModule mod_rewrite.c&gt;</code> tag:</p>\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n</code></pre>\n<p>It should look like the following:</p>\n<pre><code># BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n# Rewrite HTTP to HTTPS\nRewriteCond %{HTTPS} !=on\nRewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]\n&lt;/IfModule&gt;\n# END WordPress\n</code></pre>\n" } ]
2016/08/02
[ "https://wordpress.stackexchange.com/questions/235298", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96815/" ]
I have a search page where if the main search returns 0 results then the following query will be used. The code is ``` $num_res = $wp_query->post_count; $get_search_term = get_search_query(); if($num_res == 0) { $args = array( 'post_type' => 'resources', 'meta_key' => 'resource_txt', 'meta_value' => $get_search_term, 'meta_compare' => 'LIKE' ); $custom_query = new WP_Query( $args ); } ``` Now I am getting an error which says **"Not unique table/alias: 'wp\_postmeta'"** When I print the second query in browser it says, ``` SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'resource_txt' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%insurance claim%' ) ) AND wp_posts.post_type = 'resources' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10 ``` Is it like, I have to close the previous query and then run the custom query. Any help is highly appreciated.
I'd steer clear on editing the `.htaccess` if you're just updating your website from HTTP to HTTPS. Try an alternative route: First, revert your `.htaccess` back to the default settings: ``` # 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 ``` Next, you need to ensures that all of the URLs for your website are up-to-date, try the following steps using the [Search Replace DB tool](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/): 1. Go and download [Interconnect IT's Database Search & Replace Script here](https://github.com/interconnectit/Search-Replace-DB/archive/master.zip) 2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** ([screenshot](https://i.stack.imgur.com/J9Ga5.png)) 3. Navigate to the new folder you created in your browser (ex: `http://web.site/replace`) and [you will see the search/replace tool](https://i.stack.imgur.com/pbED1.png) 4. It should be pretty self-explanatory up to this point: enter your HTTPS link in the **`search for…`** field and the new HTTPS link in the **`replace with…`** field You can click the *dry run* button under *actions* to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder. ### However... If you still insist on having your HTTP redirect to HTTPS via the `.htaccess` add the following in between the `<IfModule mod_rewrite.c>` tag: ``` RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] ``` It should look like the following: ``` # 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] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] </IfModule> # END WordPress ```
235,331
<p>I installed BuddyPress which created additional user roles but even after deleting BuddyPress those roles are still there. How can I delete these roles? I have tried the <code>remove_role()</code> command but it did not work.</p>
[ { "answer_id": 235339, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<pre><code>$wp_roles = new WP_Roles(); // create new role object\n$wp_roles-&gt;remove_role('name_of_role');\n</code></pre>\n\n<p>If you need to check the <strong>name_of_role</strong> use</p>\n\n<pre><code>$wp_roles-&gt;get_names();\n</code></pre>\n\n<p>you will get an array of <strong>name_of_role</strong> => <strong>Nicename of Role</strong> </p>\n\n<p>Alternatively, you could use the global object <strong>$wp_roles</strong></p>\n\n<pre><code>global $wp_roles;\n</code></pre>\n" }, { "answer_id": 235341, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": false, "text": "<p>A nice, user-friendly way of deleting your custom roles is using the <a href=\"https://wordpress.org/plugins/members/\" rel=\"nofollow noreferrer\">Members</a> plugin.</p>\n\n<p>Once you install and activate it, go to <strong>Users</strong> > <strong>Roles</strong> and here you can delete an custom roles that you do not need, which you can see here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/av6H7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/av6H7.png\" alt=\"enter image description here\"></a></p>\n\n<p>Once you've remove the unwanted roles, you can simply delete the <strong>Members</strong> plugin.</p>\n" } ]
2016/08/08
[ "https://wordpress.stackexchange.com/questions/235331", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100572/" ]
I installed BuddyPress which created additional user roles but even after deleting BuddyPress those roles are still there. How can I delete these roles? I have tried the `remove_role()` command but it did not work.
``` $wp_roles = new WP_Roles(); // create new role object $wp_roles->remove_role('name_of_role'); ``` If you need to check the **name\_of\_role** use ``` $wp_roles->get_names(); ``` you will get an array of **name\_of\_role** => **Nicename of Role** Alternatively, you could use the global object **$wp\_roles** ``` global $wp_roles; ```
235,349
<p>I need a way not to load the comments form when previewing a post, is there a way to achieve this? How?</p> <p>If you need a reason to help: I use disqus and it generates a url for the "discussion" the first time the comment form loads, if this is the preview then it will look something like site.com/?post_type=food&amp;p=41009 And this is a problem because afterwards when the post is published under a real url disqus will not recognize the comments count. The only way is to manually change the discussion url. I've already contacted disqus and they say, "not a bug" if you do not want disqus to pick the preview url, don't load disqus on the preview page, the only way i know is to completely remove the comments form, so how would i go about this? Is there some sort of conditional for the preview page?</p>
[ { "answer_id": 235353, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>I took a quick peek at the disqus plugin. This works in disabling the option before the plugin decides to print out the form. </p>\n\n<pre><code>add_filter( 'pre_option_disqus_active', 'wpse_conditional_disqus_load' );\nfunction wpse_conditional_disqus_load( $disqus_active ) {\n if( is_preview() ){\n return '0';\n }\n\n return $disqus_active;\n\n}\n</code></pre>\n\n<p>You could also try something like this (not tested)</p>\n\n<pre><code>add_filter( 'the_content', 'wpse_load_disqus');\nfunction wpse_load_disqus( $content ){\n if( is_preview() ){\n return $content;\n }\n\n if( is_singular() ) { // displays on all single post types. use is_single for posts only, is_page for pages only\n\n $content .= ?&gt;\n // You disqus script here\n &lt;?php ;\n }\n\n return $content;\n\n}\n</code></pre>\n" }, { "answer_id": 235360, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>Here's one suggestion: Close the comments when <em>previewing</em>:</p>\n\n<pre><code>add_filter( 'template_redirect', function()\n{\n if( is_preview() )\n add_filter( 'comments_open', '__return_false' );\n} );\n</code></pre>\n\n<p>This should stop the <code>comments_template()</code> from loading if it's e.g. wrapped with </p>\n\n<pre><code>if( comments_open() ) \n comments_template();\n</code></pre>\n\n<p>in your theme. There's also a <code>comments_open()</code> check within <code>comment_form()</code> to prevent the form from displaying if the comments are closed.</p>\n\n<p>We could also do it manually in our child theme:</p>\n\n<pre><code>if( ! is_preview() ) \n comments_template();\n</code></pre>\n\n<p><em>But I'm not sure though how it works with plugins like Disqus.</em></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/228266/prevent-comments-template-to-load-comments-php\">Here</a> are some very interesting suggestions on how to interfere with the loading of <code>comments_template()</code>.</p>\n\n<p>PS: I noticed the the <code>disqus_active</code> option check in the <code>dsq_can_replace()</code> function:</p>\n\n<pre><code>if (get_option('disqus_active') === '0'){ return false; }\n</code></pre>\n\n<p>so we might try something like:</p>\n\n<pre><code>add_filter( 'template_redirect', function()\n{\n is_preview() &amp;&amp; add_filter( 'pre_option_disqus_active', \n function( $value ) { return '0'; }\n );\n} );\n</code></pre>\n\n<p>but note that this is untested!</p>\n" } ]
2016/08/08
[ "https://wordpress.stackexchange.com/questions/235349", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77283/" ]
I need a way not to load the comments form when previewing a post, is there a way to achieve this? How? If you need a reason to help: I use disqus and it generates a url for the "discussion" the first time the comment form loads, if this is the preview then it will look something like site.com/?post\_type=food&p=41009 And this is a problem because afterwards when the post is published under a real url disqus will not recognize the comments count. The only way is to manually change the discussion url. I've already contacted disqus and they say, "not a bug" if you do not want disqus to pick the preview url, don't load disqus on the preview page, the only way i know is to completely remove the comments form, so how would i go about this? Is there some sort of conditional for the preview page?
I took a quick peek at the disqus plugin. This works in disabling the option before the plugin decides to print out the form. ``` add_filter( 'pre_option_disqus_active', 'wpse_conditional_disqus_load' ); function wpse_conditional_disqus_load( $disqus_active ) { if( is_preview() ){ return '0'; } return $disqus_active; } ``` You could also try something like this (not tested) ``` add_filter( 'the_content', 'wpse_load_disqus'); function wpse_load_disqus( $content ){ if( is_preview() ){ return $content; } if( is_singular() ) { // displays on all single post types. use is_single for posts only, is_page for pages only $content .= ?> // You disqus script here <?php ; } return $content; } ```
235,368
<p>Ok so I have this code to Query posts from a certain ID: </p> <pre><code> &lt;?php $valid_post_types = array ('agencies','pro-awards-winners','marcawards','topshops'); $args = array( 'post_type' =&gt; $valid_post_types, 'post_status' =&gt; 'publish', 'pagename' =&gt; 210639, 'posts_per_page' =&gt; -1 ); $query = new WP_Query( $args ); // The Query query_posts( $args ); //The Loop while ( have_posts() ) : the_post(); echo ' &lt;li&gt;'; the_title(); echo '&lt;/li&gt;'; endwhile; // Reset Query wp_reset_query(); ?&gt; </code></pre> <p>The posts aren't displaying of course...Is there something I'm doing wrong? </p>
[ { "answer_id": 235353, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>I took a quick peek at the disqus plugin. This works in disabling the option before the plugin decides to print out the form. </p>\n\n<pre><code>add_filter( 'pre_option_disqus_active', 'wpse_conditional_disqus_load' );\nfunction wpse_conditional_disqus_load( $disqus_active ) {\n if( is_preview() ){\n return '0';\n }\n\n return $disqus_active;\n\n}\n</code></pre>\n\n<p>You could also try something like this (not tested)</p>\n\n<pre><code>add_filter( 'the_content', 'wpse_load_disqus');\nfunction wpse_load_disqus( $content ){\n if( is_preview() ){\n return $content;\n }\n\n if( is_singular() ) { // displays on all single post types. use is_single for posts only, is_page for pages only\n\n $content .= ?&gt;\n // You disqus script here\n &lt;?php ;\n }\n\n return $content;\n\n}\n</code></pre>\n" }, { "answer_id": 235360, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 0, "selected": false, "text": "<p>Here's one suggestion: Close the comments when <em>previewing</em>:</p>\n\n<pre><code>add_filter( 'template_redirect', function()\n{\n if( is_preview() )\n add_filter( 'comments_open', '__return_false' );\n} );\n</code></pre>\n\n<p>This should stop the <code>comments_template()</code> from loading if it's e.g. wrapped with </p>\n\n<pre><code>if( comments_open() ) \n comments_template();\n</code></pre>\n\n<p>in your theme. There's also a <code>comments_open()</code> check within <code>comment_form()</code> to prevent the form from displaying if the comments are closed.</p>\n\n<p>We could also do it manually in our child theme:</p>\n\n<pre><code>if( ! is_preview() ) \n comments_template();\n</code></pre>\n\n<p><em>But I'm not sure though how it works with plugins like Disqus.</em></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/228266/prevent-comments-template-to-load-comments-php\">Here</a> are some very interesting suggestions on how to interfere with the loading of <code>comments_template()</code>.</p>\n\n<p>PS: I noticed the the <code>disqus_active</code> option check in the <code>dsq_can_replace()</code> function:</p>\n\n<pre><code>if (get_option('disqus_active') === '0'){ return false; }\n</code></pre>\n\n<p>so we might try something like:</p>\n\n<pre><code>add_filter( 'template_redirect', function()\n{\n is_preview() &amp;&amp; add_filter( 'pre_option_disqus_active', \n function( $value ) { return '0'; }\n );\n} );\n</code></pre>\n\n<p>but note that this is untested!</p>\n" } ]
2016/08/08
[ "https://wordpress.stackexchange.com/questions/235368", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99056/" ]
Ok so I have this code to Query posts from a certain ID: ``` <?php $valid_post_types = array ('agencies','pro-awards-winners','marcawards','topshops'); $args = array( 'post_type' => $valid_post_types, 'post_status' => 'publish', 'pagename' => 210639, 'posts_per_page' => -1 ); $query = new WP_Query( $args ); // The Query query_posts( $args ); //The Loop while ( have_posts() ) : the_post(); echo ' <li>'; the_title(); echo '</li>'; endwhile; // Reset Query wp_reset_query(); ?> ``` The posts aren't displaying of course...Is there something I'm doing wrong?
I took a quick peek at the disqus plugin. This works in disabling the option before the plugin decides to print out the form. ``` add_filter( 'pre_option_disqus_active', 'wpse_conditional_disqus_load' ); function wpse_conditional_disqus_load( $disqus_active ) { if( is_preview() ){ return '0'; } return $disqus_active; } ``` You could also try something like this (not tested) ``` add_filter( 'the_content', 'wpse_load_disqus'); function wpse_load_disqus( $content ){ if( is_preview() ){ return $content; } if( is_singular() ) { // displays on all single post types. use is_single for posts only, is_page for pages only $content .= ?> // You disqus script here <?php ; } return $content; } ```
235,379
<p>Got stuck trying to remove the post format slug, so i could have i.e. example.com/video for the video section instead of example.com/type/video.</p> <p>Usually it's done like this:</p> <pre><code>add_action( 'init', 'custom_format_permalinks', 1 ); function custom_format_permalinks() { $taxonomy = 'post_format'; $post_format_rewrite = array( 'slug' =&gt; NULL, ); add_permastruct( $taxonomy, "%$taxonomy%", $post_format_rewrite ); } </code></pre> <p>Or simply:</p> <pre><code>add_filter('post_format_rewrite_base', 'post_format_base'); function post_format_base($slug) {return '/';} </code></pre> <p>These are the typical answers given elsewhere for this question. And they both get the job done, except that... pagination and feeds are no longer working.</p> <p>Then I tried this route...</p> <pre><code>add_filter('post_format_rewrite_base', 'no_format_base_rewrite_rules'); function no_format_base_rewrite_rules($format_rewrite) { $format_rewrite = array(); $formats = get_post_format_slugs(); foreach($formats as $format_nicename =&gt; $key) { $format_rewrite['('.$format_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?post_format=$matches[1]&amp;feed=$matches[2]'; $format_rewrite['('.$format_nicename.')/?([0-9]{1,})/?$'] = 'index.php?post_format=$matches[1]&amp;paged=$matches[2]'; $format_rewrite['('.$format_nicename.')/?$'] = 'index.php?post_format=$matches[1]'; } return $format_rewrite; } </code></pre> <p>This sort of approach is proven to work perfectly with categories, tags or authors, but for some reason it doesn't do the job this time. What could be wrong?</p>
[ { "answer_id": 235620, "author": "David", "author_id": 31323, "author_profile": "https://wordpress.stackexchange.com/users/31323", "pm_score": 2, "selected": false, "text": "<p>In your last code example, you're returning a wrong type for the <code>post_format_rewrite_base</code>. It should be a string, not an array. However, your idea goes in the right direction.</p>\n\n<p>You have to take care about all the «routes» that are implied by the default rewrite rules, WordPress creates for post formats:</p>\n\n<pre><code>type/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$ =&gt; index.php?post_format=$matches[1]&amp;feed=$matches[2]\ntype/([^/]+)/(feed|rdf|rss|rss2|atom)/?$ =&gt; index.php?post_format=$matches[1]&amp;feed=$matches[2]\ntype/([^/]+)/embed/?$ =&gt; index.php?post_format=$matches[1]&amp;embed=true\ntype/([^/]+)/page/?([0-9]{1,})/?$ =&gt; index.php?post_format=$matches[1]&amp;paged=$matches[2]\ntype/([^/]+)/?$ =&gt; index.php?post_format=$matches[1] \n</code></pre>\n\n<p>How about using <a href=\"https://github.com/Brain-WP/Cortex\" rel=\"nofollow\">Cortex</a>? It allows you to map routes directly to query parameters. Here's an example how to use it.</p>\n\n<pre><code>&lt;?php\n\nuse\n Brain\\Cortex,\n Brain\\Cortex\\Route;\n\n\nadd_action( 'wp_loaded', function() {\n\n Cortex::boot();\n\n $post_format_slugs = get_post_format_slugs();\n $post_format_slugs_pattern = implode( '|', $post_format_slugs );\n add_action(\n 'cortex.routes',\n function ( Route\\RouteCollectionInterface $collection ) use ( $post_format_slugs_pattern ) {\n /**\n * Default route for post format slugs\n *\n * /(standard|aside|chat|gallery|...)\n */\n $collection-&gt;addRoute(\n new Route\\QueryRoute(\n \"/{slug:{$post_format_slugs_pattern}}\",\n function( $matches ) {\n\n return [\n 'post_format' =&gt; $matches[ 'slug' ]\n ];\n }\n )\n );\n /**\n * Route for feed endpoints 1\n *\n * /(standard|aside|chat|gallery|...)/feed/(feed/rdf/rss/rss2/atom)\n */\n $collection-&gt;addRoute(\n new Route\\QueryRoute(\n \"/{slug:{$post_format_slugs_pattern}}/feed/{feed:feed|rdf|rss|rss2|atom}\",\n function( $matches ) {\n\n return [\n 'post_format' =&gt; $matches[ 'slug' ],\n 'feed' =&gt; $matches[ 'feed' ]\n ];\n }\n )\n );\n /**\n * Route for feed endpoints 2\n *\n * /(standard|aside|chat|gallery|...)/(feed/rdf/rss/rss2/atom)\n */\n $collection-&gt;addRoute(\n new Route\\QueryRoute(\n \"/{slug:{$post_format_slugs_pattern}}/{feed:feed|rdf|rss|rss2|atom}\",\n function( $matches ) {\n\n return [\n 'post_format' =&gt; $matches[ 'slug' ],\n 'feed' =&gt; $matches[ 'feed' ]\n ];\n }\n )\n );\n /**\n * Route for embed\n *\n * /(standard|aside|chat|gallery|...)/embed\n */\n $collection-&gt;addRoute(\n new Route\\QueryRoute(\n \"/{slug:{$post_format_slugs_pattern}}/embed\",\n function( $matches ) {\n\n return [\n 'post_format' =&gt; $matches[ 'slug' ],\n 'embed' =&gt; TRUE\n ];\n }\n )\n );\n /**\n * Route for pagination\n *\n * ^/(standard|aside|chat|gallery|...)/page/(\\d+)$\n */\n $collection-&gt;addRoute(\n new Route\\QueryRoute(\n \"/{slug:{$post_format_slugs_pattern}}/page/{page:[0-9]+}\",\n function( $matches ) {\n\n return [\n 'post_format' =&gt; $matches[ 'slug' ],\n 'paged' =&gt; $matches[ 'page' ]\n ];\n }\n )\n );\n }\n );\n} );\n</code></pre>\n\n<p>Cortex has the advantage that you don't have to flush rewrite rules. Internally it uses <a href=\"https://github.com/nikic/FastRoute\" rel=\"nofollow\">FastRoute</a> to match the patterns, so you can use any of the pattern language, <a href=\"https://github.com/nikic/FastRoute#usage\" rel=\"nofollow\">FastRoute</a> provides. Cortext does not overwrite the internal routing process of WordPress, it just acts right before and will pass the request through to WordPress if no route matches.</p>\n\n<p>The example shows just the essence of how to use Cortex. Some routes could possibly combined or even removed as they are only for backward compatibility (especially the redundant feed routes).</p>\n\n<p>Remember that your concept requires overlapping routes, that means you won't be able to create pages with any of the slugs of the post format terms: standard, aside, chat, gallery, link, image, quote, status, video, audio.</p>\n\n<p>You might want to implement an automated check that affects the unique post slug generation:</p>\n\n<pre><code>add_filter( 'wp_unique_post_slug_is_bad_hierarchical_slug', function( $is_bad, $slug, $post_type, $post_parent ) {\n if ( 'page' !== $post_type ) \n return $is_bad;\n\n return in_array( $slug, get_post_format_slugs() );\n} );\n</code></pre>\n\n<p>Another optimization would be to only use the post format slugs, the current theme actually supports. But this will invalidate existing URLs in case the theme changes.</p>\n\n<p>If you don't want to use Cortex, the principle would be pretty much the same but you would have to manually remove the default post format rules and replace it with <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow\">custom rewrite rules</a> that follows the schema of the routes mentioned above. Remember to do this only on an activation hook and flush rewrite rules afterwards as they get cached in the database. </p>\n" }, { "answer_id": 235760, "author": "lucian", "author_id": 70333, "author_profile": "https://wordpress.stackexchange.com/users/70333", "pm_score": 2, "selected": true, "text": "<p>Excellent answer above, well worth the bounty. For the record, this is what it led to:</p>\n\n<pre><code>add_filter( 'post_format_rewrite_rules', 'no_format_base_rewrite_rules' );\nfunction no_format_base_rewrite_rules( $format_rewrite ) {\n\n $format_rewrite = array(); \n $formats = get_post_format_slugs();\n\n foreach($formats as $format_nicename) {\n $format_rewrite['(' . $format_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?post_format=$matches[1]&amp;feed=$matches[2]';\n $format_rewrite['(' . $format_nicename . ')/?([0-9]{1,})/?$'] = 'index.php?post_format=$matches[1]&amp;paged=$matches[2]';\n $format_rewrite['(' . $format_nicename . ')/?$'] = 'index.php?post_format=$matches[1]';\n }\n\n return $format_rewrite;\n}\n</code></pre>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70333/" ]
Got stuck trying to remove the post format slug, so i could have i.e. example.com/video for the video section instead of example.com/type/video. Usually it's done like this: ``` add_action( 'init', 'custom_format_permalinks', 1 ); function custom_format_permalinks() { $taxonomy = 'post_format'; $post_format_rewrite = array( 'slug' => NULL, ); add_permastruct( $taxonomy, "%$taxonomy%", $post_format_rewrite ); } ``` Or simply: ``` add_filter('post_format_rewrite_base', 'post_format_base'); function post_format_base($slug) {return '/';} ``` These are the typical answers given elsewhere for this question. And they both get the job done, except that... pagination and feeds are no longer working. Then I tried this route... ``` add_filter('post_format_rewrite_base', 'no_format_base_rewrite_rules'); function no_format_base_rewrite_rules($format_rewrite) { $format_rewrite = array(); $formats = get_post_format_slugs(); foreach($formats as $format_nicename => $key) { $format_rewrite['('.$format_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?post_format=$matches[1]&feed=$matches[2]'; $format_rewrite['('.$format_nicename.')/?([0-9]{1,})/?$'] = 'index.php?post_format=$matches[1]&paged=$matches[2]'; $format_rewrite['('.$format_nicename.')/?$'] = 'index.php?post_format=$matches[1]'; } return $format_rewrite; } ``` This sort of approach is proven to work perfectly with categories, tags or authors, but for some reason it doesn't do the job this time. What could be wrong?
Excellent answer above, well worth the bounty. For the record, this is what it led to: ``` add_filter( 'post_format_rewrite_rules', 'no_format_base_rewrite_rules' ); function no_format_base_rewrite_rules( $format_rewrite ) { $format_rewrite = array(); $formats = get_post_format_slugs(); foreach($formats as $format_nicename) { $format_rewrite['(' . $format_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?post_format=$matches[1]&feed=$matches[2]'; $format_rewrite['(' . $format_nicename . ')/?([0-9]{1,})/?$'] = 'index.php?post_format=$matches[1]&paged=$matches[2]'; $format_rewrite['(' . $format_nicename . ')/?$'] = 'index.php?post_format=$matches[1]'; } return $format_rewrite; } ```
235,406
<p>I have written a plugin in which you have a small chat icon in the bottom right corner, however I want the user to be able to choose an image as the icon from the <code>Media Library</code>. How can I do this with the Wordpress API? The image is a setting in the plugin (only changable by the admin)</p>
[ { "answer_id": 235977, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>Since you want the icon to be different for every user, you will have to store the image in the user profile. This means you need to add an extra user field:</p>\n\n<pre><code>// create the field\nadd_action( 'show_user_profile', 'wpse_235406_chaticon' );\nadd_action( 'edit_user_profile', 'wpse_235406_chaticon' );\n\nfunction wpse_235406_chaticon ($user) { \n echo '\n &lt;h3&gt;Chat Icon&lt;/h3&gt;\n &lt;table class=\"form-table\"&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;label for=\"chaticon\"&gt;Chat Icon&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=\"file\" name=\"chaticon\" id=\"chaticon\" value=\"' . esc_attr (get_the_author_meta ('chaticon', $user-&gt;ID)) . '\" class=\"file-upload\" /&gt;&lt;br /&gt;\n &lt;span class=\"description\"&gt;Please select your chat icon.&lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;';\n}\n\n// save the field\nadd_action( 'personal_options_update', 'wpse_235406_chaticon_save' );\nadd_action( 'edit_user_profile_update', 'wpse_235406_chaticon_save' );\n\nfunction wpse_235406_chaticon_save ($user_id) {\n if (current_user_can ('edit_user', $user_id)) \n update_usermeta ($user_id, 'chaticon', $_POST['chaticon']);\n}\n</code></pre>\n\n<p>Now, this gives you the possibility to upload a file from the user's computer. If you want the user to select the file frome existing images, things become more complicated, because then you need to call the media library in stead of the default file upload. <a href=\"http://stevenslack.com/add-image-uploader-to-profile-admin-page-wordpress/\" rel=\"nofollow\">Steven Slack has written an excellent post</a> how to do this, which I don't want to take credit for by copy-pasting his code here.</p>\n\n<p>In your template you must distinguish three possibilities: user not logged in, user logged in but has no icon, user logged in and has icon. Roughly, include this:</p>\n\n<pre><code>$current_user = wp_get_current_user();\nif ( 0 == $current_user-&gt;ID ) {\n ... do what you want to do for not logged in users ...\n }\nelse {\n $icon = get_user_meta ($current_user-&gt;ID, 'chaticon');\n if (empty($icon)) {\n ... default icon with link to upload possibility ...\n }\n else {\n ... display $icon ...\n }\n</code></pre>\n" }, { "answer_id": 236092, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 2, "selected": false, "text": "<p>Use <code>wordpress-settings-api-class</code> by Tareq Hasan, Url: <a href=\"https://github.com/tareq1988/wordpress-settings-api-class\" rel=\"nofollow\">https://github.com/tareq1988/wordpress-settings-api-class</a></p>\n\n<ul>\n<li>Include the main class <code>class.settings-api.php\n</code> in your plugin. ( this file <a href=\"https://github.com/tareq1988/wordpress-settings-api-class/blob/master/src/class.settings-api.php\" rel=\"nofollow\">https://github.com/tareq1988/wordpress-settings-api-class/blob/master/src/class.settings-api.php</a>)</li>\n<li>Define your options. You need to use <code>'type' =&gt; 'file'</code> as you want to add a media uploader. (See this example for better understanding <a href=\"https://github.com/tareq1988/wordpress-settings-api-class/blob/master/example/procedural-example.php\" rel=\"nofollow\">https://github.com/tareq1988/wordpress-settings-api-class/blob/master/example/procedural-example.php</a>)</li>\n</ul>\n" }, { "answer_id": 236094, "author": "Thomas", "author_id": 99302, "author_profile": "https://wordpress.stackexchange.com/users/99302", "pm_score": 0, "selected": false, "text": "<p>I used this solution (without using the Media Library itself):</p>\n\n<p>Using <a href=\"https://rvera.github.io/image-picker/\" rel=\"nofollow\">image-picker-lib</a> inside a modal that set a hidden input's value, which is posted to the options. By getting all the media and echoing it as options I can let the user select an img.</p>\n\n<p>HTML</p>\n\n<pre><code>&lt;input id=\"image\" name=\"image\" class=\"validate\" type=\"image\" src=\"&lt;?php echo esc_attr(get_option('image_url')); ?&gt;\" id=\"image_url\" width=\"48\" height=\"48\" /&gt;\n&lt;br&gt;\n&lt;a href=\"#imageModal\" class=\"waves-effect waves-light btn modal-trigger\"&gt;\n change\n&lt;/a&gt;\n&lt;input id=\"image_url\" name=\"image_url\" type=\"text\" value=\"\" hidden /&gt;\n</code></pre>\n\n<p>PHP/HTML</p>\n\n<pre><code>&lt;div id=\"imageModal\" class=\"modal\"&gt;\n &lt;div class=\"modal-content\"&gt;\n &lt;select class=\"image-picker show-html\"&gt;\n &lt;option data-img-src=\"&lt;?php echo CM_PATH . \"/img/chat_general.png\" ?&gt;\" value=\"0\"&gt;&lt;/option&gt;\n &lt;?php\n $query_images_args = array(\n 'post_type' =&gt; 'attachment',\n 'post_mime_type' =&gt; 'image',\n 'post_status' =&gt; 'inherit',\n 'posts_per_page' =&gt; - 1,\n );\n\n $query_images = new WP_Query( $query_images_args );\n $i = 1;\n foreach ( $query_images-&gt;posts as $image ) {\n ?&gt;\n &lt;option data-img-src=\"&lt;?php echo wp_get_attachment_url($image-&gt;ID); ?&gt;\" value=\"&lt;?php echo $i; ?&gt;\"&gt;&lt;/option&gt;\n &lt;?php\n $i ;\n }\n ?&gt;\n &lt;/select&gt;\n &lt;/div&gt;\n &lt;div class=\"modal-footer\"&gt;\n &lt;a class=\"waves-effect waves-light btn change\"&gt;Choose&lt;/a&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>JS</p>\n\n<pre><code> $(\".change\").on(\"click\", function() {\n + var url = $(\".image-picker &gt; option:selected\").attr(\"data-img-src\");\n + $(\"#image\").attr(\"src\", url);\n + $(\"#image_url\").attr(\"value\", url);\n + $(\"#imageModal\").closeModal();\n + });\n</code></pre>\n" }, { "answer_id": 236296, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 6, "selected": true, "text": "<p>You should use <code>wp.media</code> to use the WordPress Media Manager dialog.</p>\n<p>First, you need to enqueue the scritps:</p>\n<pre><code>// As you are dealing with plugin settings,\n// I assume you are in admin side\nadd_action( 'admin_enqueue_scripts', 'load_wp_media_files' );\nfunction load_wp_media_files( $page ) {\n // change to the $page where you want to enqueue the script\n if( $page == 'options-general.php' ) {\n // Enqueue WordPress media scripts\n wp_enqueue_media();\n // Enqueue custom script that will interact with wp.media\n wp_enqueue_script( 'myprefix_script', plugins_url( '/js/myscript.js' , __FILE__ ), array('jquery'), '0.1' );\n }\n}\n</code></pre>\n<p>Your HTML could be something like this (note my code use attachment ID in the plugin setting instead of image url as you did in your answer, I think it is much better. For example, using ID allows you to get different images sizes when you need them):</p>\n<pre><code>$image_id = get_option( 'myprefix_image_id' );\nif( intval( $image_id ) &gt; 0 ) {\n // Change with the image size you want to use\n $image = wp_get_attachment_image( $image_id, 'medium', false, array( 'id' =&gt; 'myprefix-preview-image' ) );\n} else {\n // Some default image\n $image = '&lt;img id=&quot;myprefix-preview-image&quot; src=&quot;https://some.default.image.jpg&quot; /&gt;';\n}\n\n echo $image; ?&gt;\n &lt;input type=&quot;hidden&quot; name=&quot;myprefix_image_id&quot; id=&quot;myprefix_image_id&quot; value=&quot;&lt;?php echo esc_attr( $image_id ); ?&gt;&quot; class=&quot;regular-text&quot; /&gt;\n &lt;input type='button' class=&quot;button-primary&quot; value=&quot;&lt;?php esc_attr_e( 'Select a image', 'mytextdomain' ); ?&gt;&quot; id=&quot;myprefix_media_manager&quot;/&gt;\n</code></pre>\n<p>myscript.js</p>\n<pre><code>jQuery(document).ready( function($) {\n\n jQuery('input#myprefix_media_manager').click(function(e) {\n\n e.preventDefault();\n var image_frame;\n if(image_frame){\n image_frame.open();\n }\n // Define image_frame as wp.media object\n image_frame = wp.media({\n title: 'Select Media',\n multiple : false,\n library : {\n type : 'image',\n }\n });\n\n image_frame.on('close',function() {\n // On close, get selections and save to the hidden input\n // plus other AJAX stuff to refresh the image preview\n var selection = image_frame.state().get('selection');\n var gallery_ids = new Array();\n var my_index = 0;\n selection.each(function(attachment) {\n gallery_ids[my_index] = attachment['id'];\n my_index++;\n });\n var ids = gallery_ids.join(&quot;,&quot;);\n if(ids.length === 0) return true;//if closed withput selecting an image\n jQuery('input#myprefix_image_id').val(ids);\n Refresh_Image(ids);\n });\n\n image_frame.on('open',function() {\n // On open, get the id from the hidden input\n // and select the appropiate images in the media manager\n var selection = image_frame.state().get('selection');\n var ids = jQuery('input#myprefix_image_id').val().split(',');\n ids.forEach(function(id) {\n var attachment = wp.media.attachment(id);\n attachment.fetch();\n selection.add( attachment ? [ attachment ] : [] );\n });\n\n });\n \n image_frame.open();\n });\n\n});\n\n// Ajax request to refresh the image preview\nfunction Refresh_Image(the_id){\n var data = {\n action: 'myprefix_get_image',\n id: the_id\n };\n\n jQuery.get(ajaxurl, data, function(response) {\n\n if(response.success === true) {\n jQuery('#myprefix-preview-image').replaceWith( response.data.image );\n }\n });\n}\n</code></pre>\n<p>And the Ajax action to refresh the image preview:</p>\n<pre><code>// Ajax action to refresh the user image\nadd_action( 'wp_ajax_myprefix_get_image', 'myprefix_get_image' );\nfunction myprefix_get_image() {\n if(isset($_GET['id']) ){\n $image = wp_get_attachment_image( filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT ), 'medium', false, array( 'id' =&gt; 'myprefix-preview-image' ) );\n $data = array(\n 'image' =&gt; $image,\n );\n wp_send_json_success( $data );\n } else {\n wp_send_json_error();\n }\n}\n</code></pre>\n<p>PD: it is a quick sample written here based on <a href=\"https://wordpress.stackexchange.com/questions/233199/get-attachment-id-of-author-meta-image-attachment-metadata/233212#233212\">other answer</a>. Not tested because you didn't provide enough information about the exact context the code will be used or the exact problems you have.</p>\n" }, { "answer_id": 290287, "author": "Rohit Kaushik", "author_id": 125084, "author_profile": "https://wordpress.stackexchange.com/users/125084", "pm_score": 3, "selected": false, "text": "<p>Easy for use just only copy paste the code in your required place</p>\n<pre><code>&lt;?php\nif ( isset( $_POST['submit_image_selector'] ) &amp;&amp; isset( $_POST['image_attachment_id'] ) ) :\n update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );\n endif;\n wp_enqueue_media();\n ?&gt;&lt;form method='post'&gt;\n &lt;div class='image-preview-wrapper'&gt;\n &lt;img id='image-preview' src='&lt;?php echo wp_get_attachment_url( get_option( 'media_selector_attachment_id' ) ); ?&gt;' width='200'&gt;\n &lt;/div&gt;\n &lt;input id=&quot;upload_image_button&quot; type=&quot;button&quot; class=&quot;button&quot; value=&quot;&lt;?php _e( 'Upload image' ); ?&gt;&quot; /&gt;\n &lt;input type='hidden' name='image_attachment_id' id='image_attachment_id' value='&lt;?php echo get_option( 'media_selector_attachment_id' ); ?&gt;'&gt;\n &lt;input type=&quot;submit&quot; name=&quot;submit_image_selector&quot; value=&quot;Save&quot; class=&quot;button-primary&quot;&gt;\n &lt;/form&gt;\n&lt;?php\n$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );\n ?&gt;&lt;script type='text/javascript'&gt;\n jQuery( document ).ready( function( $ ) {\n // Uploading files\n var file_frame;\n var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id\n var set_to_post_id = &lt;?php echo $my_saved_attachment_post_id; ?&gt;; // Set this\n jQuery('#upload_image_button').on('click', function( event ){\n event.preventDefault();\n // If the media frame already exists, reopen it.\n if ( file_frame ) {\n // Set the post ID to what we want\n file_frame.uploader.uploader.param( 'post_id', set_to_post_id );\n // Open frame\n file_frame.open();\n return;\n } else {\n // Set the wp.media post id so the uploader grabs the ID we want when initialised\n wp.media.model.settings.post.id = set_to_post_id;\n }\n // Create the media frame.\n file_frame = wp.media.frames.file_frame = wp.media({\n title: 'Select a image to upload',\n button: {\n text: 'Use this image',\n },\n multiple: false // Set to true to allow multiple files to be selected\n });\n // When an image is selected, run a callback.\n file_frame.on( 'select', function() {\n // We set multiple to false so only get one image from the uploader\n attachment = file_frame.state().get('selection').first().toJSON();\n // Do something with attachment.id and/or attachment.url here\n $( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );\n $( '#image_attachment_id' ).val( attachment.id );\n // Restore the main post ID\n wp.media.model.settings.post.id = wp_media_post_id;\n });\n // Finally, open the modal\n file_frame.open();\n });\n // Restore the main ID when the add media button is pressed\n jQuery( 'a.add_media' ).on( 'click', function() {\n wp.media.model.settings.post.id = wp_media_post_id;\n });\n });\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 363944, "author": "Overcomer", "author_id": 160093, "author_profile": "https://wordpress.stackexchange.com/users/160093", "pm_score": 2, "selected": false, "text": "<p>So <a href=\"https://wordpress.stackexchange.com/a/236296/160093\">this answer</a> worked perfectly. But in order to make it reusable, I converted the code to a function. So, to use this, you have to first <a href=\"https://wordpress.stackexchange.com/a/236296/160093\">check this out</a> to <code>enqueue</code> the script. And then declare <code>wpOpenGallery</code> like this:</p>\n\n<pre><code>(function($) {\n $(document).ready(function() {\n const wpOpenGallery = function(o, callback) {\n const options = (typeof o === 'object') ? o : {};\n\n // Predefined settings\n const defaultOptions = {\n title: 'Select Media',\n fileType: 'image',\n multiple: false,\n currentValue: '',\n };\n\n const opt = { ...defaultOptions, ...options };\n\n let image_frame;\n\n if(image_frame){\n image_frame.open();\n }\n\n // Define image_frame as wp.media object\n image_frame = wp.media({\n title: opt.title,\n multiple : opt.multiple,\n library : {\n type : opt.fileType,\n }\n });\n\n image_frame.on('open',function() {\n // On open, get the id from the hidden input\n // and select the appropiate images in the media manager\n const selection = image_frame.state().get('selection');\n const ids = opt.currentValue.split(',');\n\n ids.forEach(function(id) {\n const attachment = wp.media.attachment(id);\n attachment.fetch();\n selection.add( attachment ? [ attachment ] : [] );\n });\n });\n\n image_frame.on('close',function() {\n // On close, get selections and save to the hidden input\n // plus other AJAX stuff to refresh the image preview\n const selection = image_frame.state().get('selection');\n const files = [];\n\n selection.each(function(attachment) {\n files.push({\n id: attachment.attributes.id,\n filename: attachment.attributes.filename,\n url: attachment.attributes.url,\n type: attachment.attributes.type,\n subtype: attachment.attributes.subtype,\n sizes: attachment.attributes.sizes,\n });\n });\n\n callback(files);\n });\n\n image_frame.open();\n }\n })\n}(jQuery));\n</code></pre>\n\n<p>And call it like this:</p>\n\n<pre><code>wpOpenGallery(null, function(data) {\n console.log(data);\n});\n</code></pre>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235406", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99302/" ]
I have written a plugin in which you have a small chat icon in the bottom right corner, however I want the user to be able to choose an image as the icon from the `Media Library`. How can I do this with the Wordpress API? The image is a setting in the plugin (only changable by the admin)
You should use `wp.media` to use the WordPress Media Manager dialog. First, you need to enqueue the scritps: ``` // As you are dealing with plugin settings, // I assume you are in admin side add_action( 'admin_enqueue_scripts', 'load_wp_media_files' ); function load_wp_media_files( $page ) { // change to the $page where you want to enqueue the script if( $page == 'options-general.php' ) { // Enqueue WordPress media scripts wp_enqueue_media(); // Enqueue custom script that will interact with wp.media wp_enqueue_script( 'myprefix_script', plugins_url( '/js/myscript.js' , __FILE__ ), array('jquery'), '0.1' ); } } ``` Your HTML could be something like this (note my code use attachment ID in the plugin setting instead of image url as you did in your answer, I think it is much better. For example, using ID allows you to get different images sizes when you need them): ``` $image_id = get_option( 'myprefix_image_id' ); if( intval( $image_id ) > 0 ) { // Change with the image size you want to use $image = wp_get_attachment_image( $image_id, 'medium', false, array( 'id' => 'myprefix-preview-image' ) ); } else { // Some default image $image = '<img id="myprefix-preview-image" src="https://some.default.image.jpg" />'; } echo $image; ?> <input type="hidden" name="myprefix_image_id" id="myprefix_image_id" value="<?php echo esc_attr( $image_id ); ?>" class="regular-text" /> <input type='button' class="button-primary" value="<?php esc_attr_e( 'Select a image', 'mytextdomain' ); ?>" id="myprefix_media_manager"/> ``` myscript.js ``` jQuery(document).ready( function($) { jQuery('input#myprefix_media_manager').click(function(e) { e.preventDefault(); var image_frame; if(image_frame){ image_frame.open(); } // Define image_frame as wp.media object image_frame = wp.media({ title: 'Select Media', multiple : false, library : { type : 'image', } }); image_frame.on('close',function() { // On close, get selections and save to the hidden input // plus other AJAX stuff to refresh the image preview var selection = image_frame.state().get('selection'); var gallery_ids = new Array(); var my_index = 0; selection.each(function(attachment) { gallery_ids[my_index] = attachment['id']; my_index++; }); var ids = gallery_ids.join(","); if(ids.length === 0) return true;//if closed withput selecting an image jQuery('input#myprefix_image_id').val(ids); Refresh_Image(ids); }); image_frame.on('open',function() { // On open, get the id from the hidden input // and select the appropiate images in the media manager var selection = image_frame.state().get('selection'); var ids = jQuery('input#myprefix_image_id').val().split(','); ids.forEach(function(id) { var attachment = wp.media.attachment(id); attachment.fetch(); selection.add( attachment ? [ attachment ] : [] ); }); }); image_frame.open(); }); }); // Ajax request to refresh the image preview function Refresh_Image(the_id){ var data = { action: 'myprefix_get_image', id: the_id }; jQuery.get(ajaxurl, data, function(response) { if(response.success === true) { jQuery('#myprefix-preview-image').replaceWith( response.data.image ); } }); } ``` And the Ajax action to refresh the image preview: ``` // Ajax action to refresh the user image add_action( 'wp_ajax_myprefix_get_image', 'myprefix_get_image' ); function myprefix_get_image() { if(isset($_GET['id']) ){ $image = wp_get_attachment_image( filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT ), 'medium', false, array( 'id' => 'myprefix-preview-image' ) ); $data = array( 'image' => $image, ); wp_send_json_success( $data ); } else { wp_send_json_error(); } } ``` PD: it is a quick sample written here based on [other answer](https://wordpress.stackexchange.com/questions/233199/get-attachment-id-of-author-meta-image-attachment-metadata/233212#233212). Not tested because you didn't provide enough information about the exact context the code will be used or the exact problems you have.
235,411
<p>I know how to add a custom field to WP register form via register_form hook. But this adds the new field at the end of the form. How would I go about moving this field at the beginning of the form? </p> <p>Example:</p> <pre><code>function mytheme_register_form() { $first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : ''; ?&gt; &lt;p&gt; &lt;label for="first_name"&gt;&lt;?php _e( 'Your name', 'mytheme' ) ?&gt;&lt;br /&gt; &lt;input type="text" name="first_name" id="first_name" class="input" value="&lt;?php echo esc_attr( wp_unslash( $first_name ) ); ?&gt;" size="25" /&gt; &lt;/label&gt; &lt;/p&gt; &lt;?php } add_action( 'register_form', 'mytheme_register_form' ); </code></pre> <p><a href="https://codex.wordpress.org/Plugin_API/Action_Reference/register_form" rel="nofollow">https://codex.wordpress.org/Plugin_API/Action_Reference/register_form</a></p>
[ { "answer_id": 235413, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 2, "selected": true, "text": "<p>You can't, because of <code>wp-login.php</code> structure. Here is code with <code>register_form</code> hook:</p>\n\n<pre><code>&lt;form name=\"registerform\" id=\"registerform\" action=\"&lt;?php echo esc_url( site_url( 'wp-login.php?action=register', 'login_post' ) ); ?&gt;\" method=\"post\" novalidate=\"novalidate\"&gt;\n &lt;p&gt;\n &lt;label for=\"user_login\"&gt;&lt;?php _e('Username') ?&gt;&lt;br /&gt;\n &lt;input type=\"text\" name=\"user_login\" id=\"user_login\" class=\"input\" value=\"&lt;?php echo esc_attr(wp_unslash($user_login)); ?&gt;\" size=\"20\" /&gt;&lt;/label&gt;\n &lt;/p&gt;\n &lt;p&gt;\n &lt;label for=\"user_email\"&gt;&lt;?php _e('Email') ?&gt;&lt;br /&gt;\n &lt;input type=\"email\" name=\"user_email\" id=\"user_email\" class=\"input\" value=\"&lt;?php echo esc_attr( wp_unslash( $user_email ) ); ?&gt;\" size=\"25\" /&gt;&lt;/label&gt;\n &lt;/p&gt;\n &lt;?php\n /**\n * Fires following the 'Email' field in the user registration form.\n *\n * @since 2.1.0\n */\n do_action( 'register_form' );\n ?&gt;\n &lt;p id=\"reg_passmail\"&gt;&lt;?php _e( 'Registration confirmation will be emailed to you.' ); ?&gt;&lt;/p&gt;\n &lt;br class=\"clear\" /&gt;\n &lt;input type=\"hidden\" name=\"redirect_to\" value=\"&lt;?php echo esc_attr( $redirect_to ); ?&gt;\" /&gt;\n &lt;p class=\"submit\"&gt;&lt;input type=\"submit\" name=\"wp-submit\" id=\"wp-submit\" class=\"button button-primary button-large\" value=\"&lt;?php esc_attr_e('Register'); ?&gt;\" /&gt;&lt;/p&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 329557, "author": "Betty", "author_id": 10287, "author_profile": "https://wordpress.stackexchange.com/users/10287", "pm_score": 0, "selected": false, "text": "<p>I just figured out a way to accomplish this.</p>\n\n<p>On the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/register_form\" rel=\"nofollow noreferrer\">register_form</a> page, there is a second example (after the example you've given) which is about changing the register form using output buffering. The example actually has some typos and won't work, but we can use the idea. </p>\n\n<p>The following code should work:</p>\n\n<pre><code>function my_register_form() {\n\n $content = ob_get_contents();\n $my_content = '&lt;label for=\"first_name\"&gt;First name&lt;br /&gt;\n &lt;input type=\"text\" name=\"first_name\" id=\"first_name\" class=\"input\" value=\"\" size=\"25\" /&gt;\n &lt;/label&gt;\n &lt;/p&gt;&lt;p&gt;\n &lt;label for=\"user_login\"&gt;';\n $content = str_replace ( '&lt;label for=\"user_login\"&gt;', $my_content, $content );\n\n ob_get_clean();\n echo $content;\n}\nadd_action( 'register_form', 'my_register_form' );\n</code></pre>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65585/" ]
I know how to add a custom field to WP register form via register\_form hook. But this adds the new field at the end of the form. How would I go about moving this field at the beginning of the form? Example: ``` function mytheme_register_form() { $first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : ''; ?> <p> <label for="first_name"><?php _e( 'Your name', 'mytheme' ) ?><br /> <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" size="25" /> </label> </p> <?php } add_action( 'register_form', 'mytheme_register_form' ); ``` <https://codex.wordpress.org/Plugin_API/Action_Reference/register_form>
You can't, because of `wp-login.php` structure. Here is code with `register_form` hook: ``` <form name="registerform" id="registerform" action="<?php echo esc_url( site_url( 'wp-login.php?action=register', 'login_post' ) ); ?>" method="post" novalidate="novalidate"> <p> <label for="user_login"><?php _e('Username') ?><br /> <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="20" /></label> </p> <p> <label for="user_email"><?php _e('Email') ?><br /> <input type="email" name="user_email" id="user_email" class="input" value="<?php echo esc_attr( wp_unslash( $user_email ) ); ?>" size="25" /></label> </p> <?php /** * Fires following the 'Email' field in the user registration form. * * @since 2.1.0 */ do_action( 'register_form' ); ?> <p id="reg_passmail"><?php _e( 'Registration confirmation will be emailed to you.' ); ?></p> <br class="clear" /> <input type="hidden" name="redirect_to" value="<?php echo esc_attr( $redirect_to ); ?>" /> <p class="submit"><input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Register'); ?>" /></p> </form> ```
235,419
<p>I am a new WordPress developer and I want to build a custom interval for a function. </p> <p>I have seen how to execute a script every one or five minutes, but I do not understand how an interval is calculated.</p>
[ { "answer_id": 235420, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 2, "selected": false, "text": "<p>Unfortunately, you cannot run script on every 12 December. WP Cron can be only defined as interval from first execution of script, so you have to execute script on 12 December with one year interval to do exactly what you want.</p>\n\n<p>I will suggest you to create WP Cron job with daily interval and check in script if today is 12 December.</p>\n\n<pre><code>if (!wp_next_scheduled('my_task_hook')) {\n wp_schedule_event(time(), 'daily', 'my_task_hook');\n}\n\nadd_action('my_task_hook', 'my_task_function');\n\nfunction my_task_function() {\n $today = strtotime(date());\n if (date('d', $today) == '12' &amp;&amp; date('m', $today) == '12') {\n // today is 12 December!\n }\n}\n</code></pre>\n" }, { "answer_id": 235444, "author": "xrissz", "author_id": 68063, "author_profile": "https://wordpress.stackexchange.com/users/68063", "pm_score": 0, "selected": false, "text": "<p>To improve @Krzysztof Grabania's answer, you can modify your WP that way it works like a Unix cron job.\nFor that you have to put this line into your wp-config.php file:</p>\n\n<p><code>//Disable internal Wp-Cron function\ndefine('DISABLE_WP_CRON', true);</code></p>\n\n<p>This will turn off the while WP Cron. So your site will be faster, because it won't check every page load the actual tasks.</p>\n\n<p>After that you have to set up a unix cron job for calling that URL:</p>\n\n<p><code>http://www.server.com/wp-cron.php?doing_wp_cron</code></p>\n\n<p>You should select the right interval wisely, because this will be the smallest interval all kind of scheduling. (I usually use 1-5 minutely cron)</p>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100701/" ]
I am a new WordPress developer and I want to build a custom interval for a function. I have seen how to execute a script every one or five minutes, but I do not understand how an interval is calculated.
Unfortunately, you cannot run script on every 12 December. WP Cron can be only defined as interval from first execution of script, so you have to execute script on 12 December with one year interval to do exactly what you want. I will suggest you to create WP Cron job with daily interval and check in script if today is 12 December. ``` if (!wp_next_scheduled('my_task_hook')) { wp_schedule_event(time(), 'daily', 'my_task_hook'); } add_action('my_task_hook', 'my_task_function'); function my_task_function() { $today = strtotime(date()); if (date('d', $today) == '12' && date('m', $today) == '12') { // today is 12 December! } } ```
235,426
<p>I have this error coming up on my wp_debug log file: [09-Aug-2016 11:05:05 UTC] PHP Warning: Invalid argument supplied for foreach() in ...wp-content/themes/mytheme/custom-post-types/cpts.php on line 23</p> <p>I cannot seem to see why this would give that that error...</p> <p>The code in question is as follows </p> <pre><code>$cpts = array( array('shows','Show','Shows','dashicons-tickets-alt',array('title','editor','thumbnail','comments')), array('people','Person','Team','dashicons-groups',array('title','editor','thumbnail')), array('cast','Cast &amp; Crew','Cast &amp; Crew','dashicons-universal-access',array('title','editor','thumbnail')), array('brochures','Brochure','Brochures','dashicons-book',array('title','editor','thumbnail')), array('jobs','Job','Jobs','dashicons-businessman',array('title','editor','thumbnail')), array('businesses','Business','Businesses','dashicons-building',array('title','editor','thumbnail')), array('prices','Price List','Price Lists','dashicons-money', array('title')), ); function cpts_register() { global $cpts; foreach($cpts as $cpt){ $cpt_wp_name = $cpt[0]; $cpt_singular = $cpt[1]; $cpt_plural = $cpt[2]; $cpt_image = $cpt[3]; $cpt_suports = $cpt[4]; $labels = array( 'name' =&gt; _x($cpt_plural, 'post type general name'), 'singular_name' =&gt; _x($cpt_singular, 'post type singular name'), 'add_new' =&gt; _x('Add New', $cpt_wp_name), 'add_new_item' =&gt; __('Add New '.$cpt_singular), 'edit_item' =&gt; __('Edit '.$cpt_singular), 'new_item' =&gt; __('New '.$cpt_singular), 'view_item' =&gt; __('View '.$cpt_singular), 'search_items' =&gt; __('Search '.$cpt_plural), 'not_found' =&gt; __('No '.$cpt_plural.' Found'), 'not_found_in_trash' =&gt; __('No '.$cpt_plural.' Found in Trash'), 'parent_item_colon' =&gt; '', ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'show_ui' =&gt; true, 'publicly_queryable' =&gt; true, 'query_var' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'rewrite' =&gt; true, 'show_in_rest' =&gt; true, 'supports' =&gt; $cpt_suports, 'menu_icon' =&gt; $cpt_image, ); register_post_type($cpt_wp_name, $args ); } } </code></pre> <p>Thanks in advance for your help...</p> <p>M</p>
[ { "answer_id": 235428, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": true, "text": "<p>Theme files are included by functions so you also need to declare <code>global $cpts</code> where you assign it. It won't be global automatically. </p>\n" }, { "answer_id": 235429, "author": "Jbbhatti", "author_id": 63179, "author_profile": "https://wordpress.stackexchange.com/users/63179", "pm_score": 0, "selected": false, "text": "<p>One fix is to check the variable’s type first</p>\n\n<pre><code>$items = $product-&gt;getFormats();\n\nif (is_array($items)) {\n foreach ($items as $item) {\n // ...\n }\n}\n</code></pre>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235426", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100706/" ]
I have this error coming up on my wp\_debug log file: [09-Aug-2016 11:05:05 UTC] PHP Warning: Invalid argument supplied for foreach() in ...wp-content/themes/mytheme/custom-post-types/cpts.php on line 23 I cannot seem to see why this would give that that error... The code in question is as follows ``` $cpts = array( array('shows','Show','Shows','dashicons-tickets-alt',array('title','editor','thumbnail','comments')), array('people','Person','Team','dashicons-groups',array('title','editor','thumbnail')), array('cast','Cast & Crew','Cast & Crew','dashicons-universal-access',array('title','editor','thumbnail')), array('brochures','Brochure','Brochures','dashicons-book',array('title','editor','thumbnail')), array('jobs','Job','Jobs','dashicons-businessman',array('title','editor','thumbnail')), array('businesses','Business','Businesses','dashicons-building',array('title','editor','thumbnail')), array('prices','Price List','Price Lists','dashicons-money', array('title')), ); function cpts_register() { global $cpts; foreach($cpts as $cpt){ $cpt_wp_name = $cpt[0]; $cpt_singular = $cpt[1]; $cpt_plural = $cpt[2]; $cpt_image = $cpt[3]; $cpt_suports = $cpt[4]; $labels = array( 'name' => _x($cpt_plural, 'post type general name'), 'singular_name' => _x($cpt_singular, 'post type singular name'), 'add_new' => _x('Add New', $cpt_wp_name), 'add_new_item' => __('Add New '.$cpt_singular), 'edit_item' => __('Edit '.$cpt_singular), 'new_item' => __('New '.$cpt_singular), 'view_item' => __('View '.$cpt_singular), 'search_items' => __('Search '.$cpt_plural), 'not_found' => __('No '.$cpt_plural.' Found'), 'not_found_in_trash' => __('No '.$cpt_plural.' Found in Trash'), 'parent_item_colon' => '', ); $args = array( 'labels' => $labels, 'public' => true, 'show_ui' => true, 'publicly_queryable' => true, 'query_var' => true, 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => true, 'show_in_rest' => true, 'supports' => $cpt_suports, 'menu_icon' => $cpt_image, ); register_post_type($cpt_wp_name, $args ); } } ``` Thanks in advance for your help... M
Theme files are included by functions so you also need to declare `global $cpts` where you assign it. It won't be global automatically.
235,438
<p>This is probably a typical Dutch issue where you have a last name which can contain multiple words. For example Robin van Persie or Mark de Jong.</p> <p>Currently I have a list of users ordered by last name, which is the default for <code>get_users</code>. This works fine most of the time but fails when a user has a last name containing more than one word. </p> <p>For example Mark de Jong is listed between the 'C' and 'E' because of 'de' Jong. However is should be listed between the 'I' and 'K' as Jong should be seen as the word to sort. </p> <p>Same with Robin van Persie which get listed between the 'U' and 'W' becasue of 'van' Persie. However it should be listed between the 'O' and 'Q' as Persie should be seen as the word to sort.</p> <p>Is there a way to create a function for this to solve this issue?</p> <p>Edit: updated with current code:</p> <pre><code>$allUsers = get_users('orderby=display_name&amp;order=ASC&amp;exclude=1,4'); $users = array(); // Remove subscribers from the list as they won't write any articles foreach($allUsers as $currentUser) { if(!in_array( 'subscriber', $currentUser-&gt;roles )) { $users[] = $currentUser; } } usort($users, create_function('$a, $b', 'return strnatcasecmp($a-&gt;last_name, $b-&gt;last_name);')); foreach($users as $user) { // Output </code></pre> <p>Thanks in advance!</p>
[ { "answer_id": 235439, "author": "Florian", "author_id": 10595, "author_profile": "https://wordpress.stackexchange.com/users/10595", "pm_score": 0, "selected": false, "text": "<p>I am guessing that your real question is \"How can I achieve this result?\".</p>\n\n<p>I would get all users, stick the values into an array and then sort that array. </p>\n\n<pre><code>$names = array();\n\nforeach($users as $user)\n{\n$names[] = $user-&gt;first_name.' '.$user-&gt;last_name;\n}\n\nusort($names, function($a, $b) {\n $a = substr(strrchr($a, ' '), 1);\n $b = substr(strrchr($b, ' '), 1);\n return strcmp($a, $b);\n});\n\nvar_dump($names);\n</code></pre>\n" }, { "answer_id": 235441, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 3, "selected": true, "text": "<p>This should do it:</p>\n\n<pre><code>usort($users, 'wpse_235438_sort_users' );\n\nfunction wpse_235438_sort_users( $a, $b ) {\n $a_last_name = array_pop( explode( ' ', $a-&gt;last_name ) );\n $b_last_name = array_pop( explode( ' ', $b-&gt;last_name ) );\n return strnatcasecmp( $a_last_name, $b_last_name );\n}\n</code></pre>\n\n<p><a href=\"http://php.net/explode\" rel=\"nofollow\"><code>explode()</code></a> will convert your names into arrays; <a href=\"http://php.net/array_pop\" rel=\"nofollow\"><code>array_pop()</code></a> will give you the last item in those arrays, which is what you're looking for. Then you just do the comparison you were already doing to sort them.</p>\n\n<h2>Using an anonymous function</h2>\n\n<p>Per the PHP page on <a href=\"http://php.net/create_function\" rel=\"nofollow\"><code>create_function()</code></a>, if you're using PHP 5.3 or newer, you should use an <a href=\"https://secure.php.net/manual/en/functions.anonymous.php\" rel=\"nofollow\">anonymous function</a> (or \"closure\") instead of <code>create_function()</code>.</p>\n\n<pre><code>usort($users, function( $a, $b ) {\n $a_last_name = array_pop( explode( ' ', $a-&gt;last_name ) );\n $b_last_name = array_pop( explode( ' ', $b-&gt;last_name ) );\n return strnatcasecmp( $a_last_name, $b_last_name );\n} );\n</code></pre>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28103/" ]
This is probably a typical Dutch issue where you have a last name which can contain multiple words. For example Robin van Persie or Mark de Jong. Currently I have a list of users ordered by last name, which is the default for `get_users`. This works fine most of the time but fails when a user has a last name containing more than one word. For example Mark de Jong is listed between the 'C' and 'E' because of 'de' Jong. However is should be listed between the 'I' and 'K' as Jong should be seen as the word to sort. Same with Robin van Persie which get listed between the 'U' and 'W' becasue of 'van' Persie. However it should be listed between the 'O' and 'Q' as Persie should be seen as the word to sort. Is there a way to create a function for this to solve this issue? Edit: updated with current code: ``` $allUsers = get_users('orderby=display_name&order=ASC&exclude=1,4'); $users = array(); // Remove subscribers from the list as they won't write any articles foreach($allUsers as $currentUser) { if(!in_array( 'subscriber', $currentUser->roles )) { $users[] = $currentUser; } } usort($users, create_function('$a, $b', 'return strnatcasecmp($a->last_name, $b->last_name);')); foreach($users as $user) { // Output ``` Thanks in advance!
This should do it: ``` usort($users, 'wpse_235438_sort_users' ); function wpse_235438_sort_users( $a, $b ) { $a_last_name = array_pop( explode( ' ', $a->last_name ) ); $b_last_name = array_pop( explode( ' ', $b->last_name ) ); return strnatcasecmp( $a_last_name, $b_last_name ); } ``` [`explode()`](http://php.net/explode) will convert your names into arrays; [`array_pop()`](http://php.net/array_pop) will give you the last item in those arrays, which is what you're looking for. Then you just do the comparison you were already doing to sort them. Using an anonymous function --------------------------- Per the PHP page on [`create_function()`](http://php.net/create_function), if you're using PHP 5.3 or newer, you should use an [anonymous function](https://secure.php.net/manual/en/functions.anonymous.php) (or "closure") instead of `create_function()`. ``` usort($users, function( $a, $b ) { $a_last_name = array_pop( explode( ' ', $a->last_name ) ); $b_last_name = array_pop( explode( ' ', $b->last_name ) ); return strnatcasecmp( $a_last_name, $b_last_name ); } ); ```
235,442
<p>I have written a simple author subscription plugin. Basically, it shows a subscribe button similar to YouTube. When a (logged in) user clicks on it, they subscribe to that author, and will get notified by their posts.</p> <p>I'm using AJAX to make the button not refresh the page, and a data-attribute to send the author ID to my function, but I'm not sure if this approach causes any risks.</p> <pre><code>&lt;button class="subscribe_button" data-author-id="352" data-action="subscribe"&gt; </code></pre> <p>Could someone theoretically change this data-attribute's value to cause an SQL injection or something? It seems that posting data through AJAX is very vulnerable to attacks, more so than if it were just a PHP file. Am I justified into thinking this? Are there any risks involved with my code below?</p> <pre><code>&lt;script&gt; ( function( $ ) { var ajaxurl = "&lt;?php echo admin_url('admin-ajax.php'); ?&gt;", subscriptions_container = $('.subscriptions_container'); $(subscriptions_container).on('click', '.subscribe_button', function() { // Disable button temporarily $(this).unbind("click"); var thisButton = $(this); // Define author_id and button action var author_id = $(this).data( "author-id"), action = $(this).data( "action") + '_callback'; // Data to be sent to function var data = { 'action': action, 'security': '&lt;?php echo $ajax_nonce; ?&gt;', 'author_id': author_id }; // Send data with AJAX jQuery.post(ajaxurl, data, function(response) { thisButton.closest('.subscriptions').replaceWith(response); }); }); } )( jQuery ); &lt;/script&gt; </code></pre> <p>And my PHP callback function:</p> <pre><code>function subscribe_callback() { check_ajax_referer( '*****', 'security' ); if ( is_user_logged_in() ) { global $wpdb; $table_name = $wpdb-&gt;prefix . "subscriptions"; // Check if author_id is posted and if it's a number if ( isset($_POST['author_id']) &amp;&amp; is_numeric($_POST['author_id']) ) { $author_id = $_POST['author_id']; $subscriber_id = get_current_user_id(); // check if author is not subscribing to himself, if not then add database query if ( $author_id != $subscriber_id ) { if ( $wpdb-&gt;insert( $table_name, array( 'subscriber_user_id' =&gt; $subscriber_id, 'author_user_id' =&gt; $author_id, 'email_notification' =&gt; 'yes', 'subscription_date' =&gt; current_time( 'mysql' ) ), array( '%d', '%d', '%s', '%s' ) ) !== FALSE ) { // add subscriber to usermeta $author_subscriber_count = get_user_meta($author_id, 'subscribers', true); $author_subscriber_count++; update_user_meta($author_id, 'subscribers', $author_subscriber_count); echo subscribe_button($author_id); } } } } wp_die(); } add_action( 'wp_ajax_subscribe_callback', 'subscribe_callback' ); </code></pre>
[ { "answer_id": 235445, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p>Data attributes can be easly overriden, for example by jQuery function <code>data</code>. I would do this with attributes using generated md5 from user id and login, for example <code>$user_id . '-' . md5($user_id . $user_login)</code>. You php script should check user by:</p>\n\n<ul>\n<li><p>exploding attribute by <code>-</code> sign</p></li>\n<li><p>get user by id (before - sign)</p></li>\n<li><p>generate md5 and compare it with value after <code>-</code> sign</p></li>\n</ul>\n" }, { "answer_id": 235451, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 1, "selected": false, "text": "<p>When dealing with submit forms, even if they are sent with AJAX, you must play by the <strong><em><a href=\"https://www.owasp.org/index.php/Don&#39;t_trust_user_input\" rel=\"nofollow\">Never trust user's input</a></em></strong> rule.</p>\n\n<p>Every <code>data-attribute</code> can be changed, edited via Inspector. Your only trusted validation should be on the server side, as you did with:</p>\n\n<pre><code>if ( isset($_POST['author_id']) || is_numeric($_POST['author_id']) )\n</code></pre>\n\n<p>Personally, I would inverse the logic and first check all the attributes before starting any action.</p>\n\n<pre><code>check_ajax_referer( '*****', 'security' );\n\nif ( ! isset($_POST['author_id']) &amp;&amp; ! is_numeric($_POST['author_id']) ) {\n // tell the villain that this tower is watched\n wp_send_json_error( 'Wrong author ID!' );\n}\n\n// now is safe to cache\n$author_id = $_POST['author_id'];\n</code></pre>\n\n<p>Stolen from <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json_error\" rel=\"nofollow\">Codex</a>.</p>\n\n<p>The parameters are passed through a URI encoding so I wouldn't worry too much about data type or casting.</p>\n" }, { "answer_id": 235459, "author": "David", "author_id": 31323, "author_profile": "https://wordpress.stackexchange.com/users/31323", "pm_score": 1, "selected": false, "text": "<p>No, it is not more or less risky than excepting data from the user via URL parameter or a POST request sent by an HTML form. For all of these methods applies the rule Andrei Lupu already mentioned: <strong>Consider each input as possibly harmful</strong>.</p>\n\n<p>To protect your system you should start by <em>validating</em> the input against your expectation, if possible. E.g. you know that the user ID will always be numeric. After validation you have to <em>escape</em> special characters on <em>context change</em>. If you want to use a string as part of a SQL query, it's a context change and thus you must escape characters with a special meaning in an SQL context. In your case, <code>wpdb::insert()</code> doest that for you.</p>\n\n<p>Another possible context change would be, if you want to use user input directly in a HTML context (print it to your template). </p>\n\n<p>Another important step in a client-server-application is to verify the command was actually intended by the user. Otherwise you open your application to <a href=\"https://en.wikipedia.org/wiki/Cross-site_request_forgery\" rel=\"nofollow\">cross-side request forgery (CSRF)</a> attacks. As you (obviously) use WordPress' nonce functions and the feature is only available for logged in users, you're command is fairly authenticated.</p>\n\n<p>So from a today perspective, your code example is considered to be secure.</p>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235442", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22588/" ]
I have written a simple author subscription plugin. Basically, it shows a subscribe button similar to YouTube. When a (logged in) user clicks on it, they subscribe to that author, and will get notified by their posts. I'm using AJAX to make the button not refresh the page, and a data-attribute to send the author ID to my function, but I'm not sure if this approach causes any risks. ``` <button class="subscribe_button" data-author-id="352" data-action="subscribe"> ``` Could someone theoretically change this data-attribute's value to cause an SQL injection or something? It seems that posting data through AJAX is very vulnerable to attacks, more so than if it were just a PHP file. Am I justified into thinking this? Are there any risks involved with my code below? ``` <script> ( function( $ ) { var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>", subscriptions_container = $('.subscriptions_container'); $(subscriptions_container).on('click', '.subscribe_button', function() { // Disable button temporarily $(this).unbind("click"); var thisButton = $(this); // Define author_id and button action var author_id = $(this).data( "author-id"), action = $(this).data( "action") + '_callback'; // Data to be sent to function var data = { 'action': action, 'security': '<?php echo $ajax_nonce; ?>', 'author_id': author_id }; // Send data with AJAX jQuery.post(ajaxurl, data, function(response) { thisButton.closest('.subscriptions').replaceWith(response); }); }); } )( jQuery ); </script> ``` And my PHP callback function: ``` function subscribe_callback() { check_ajax_referer( '*****', 'security' ); if ( is_user_logged_in() ) { global $wpdb; $table_name = $wpdb->prefix . "subscriptions"; // Check if author_id is posted and if it's a number if ( isset($_POST['author_id']) && is_numeric($_POST['author_id']) ) { $author_id = $_POST['author_id']; $subscriber_id = get_current_user_id(); // check if author is not subscribing to himself, if not then add database query if ( $author_id != $subscriber_id ) { if ( $wpdb->insert( $table_name, array( 'subscriber_user_id' => $subscriber_id, 'author_user_id' => $author_id, 'email_notification' => 'yes', 'subscription_date' => current_time( 'mysql' ) ), array( '%d', '%d', '%s', '%s' ) ) !== FALSE ) { // add subscriber to usermeta $author_subscriber_count = get_user_meta($author_id, 'subscribers', true); $author_subscriber_count++; update_user_meta($author_id, 'subscribers', $author_subscriber_count); echo subscribe_button($author_id); } } } } wp_die(); } add_action( 'wp_ajax_subscribe_callback', 'subscribe_callback' ); ```
When dealing with submit forms, even if they are sent with AJAX, you must play by the ***[Never trust user's input](https://www.owasp.org/index.php/Don't_trust_user_input)*** rule. Every `data-attribute` can be changed, edited via Inspector. Your only trusted validation should be on the server side, as you did with: ``` if ( isset($_POST['author_id']) || is_numeric($_POST['author_id']) ) ``` Personally, I would inverse the logic and first check all the attributes before starting any action. ``` check_ajax_referer( '*****', 'security' ); if ( ! isset($_POST['author_id']) && ! is_numeric($_POST['author_id']) ) { // tell the villain that this tower is watched wp_send_json_error( 'Wrong author ID!' ); } // now is safe to cache $author_id = $_POST['author_id']; ``` Stolen from [Codex](https://codex.wordpress.org/Function_Reference/wp_send_json_error). The parameters are passed through a URI encoding so I wouldn't worry too much about data type or casting.
235,463
<h3>Here's the TLDR: Is is possible to get all meta keys from a specific CPT without a database hit for each post?</h3> <h1>If so, how can I do this the Wordpress way?</h1> <p>This seems like a simple thing to do ( at least from a database perspective ) but I'm looking for the Wordpress way to get multiple post_meta values from a bunch of CPTs. Example:</p> <p>Every <code>Product</code> Custom Post Type has the following fields ( plus many more ) which holds discrete pieces of information:</p> <ul> <li><code>_ns_research_document</code></li> <li><code>_ns_monograph_document</code></li> <li><code>_ns_profile_document</code></li> </ul> <p>Essentially, I want a list of ALL <em><strong>Research</strong> Docs</em>, <em><strong>Monographs</strong></em> and <em><strong>Profile</strong> Docs</em>. Currently this site has 72 <code>product</code> posts, but other sites this will be used on have over a thousand.</p> <p>I assume there's a way to do this with wordpress methods that doesn't involve [at least] 73 calls ( one for all posts, and then <code>get_post_meta</code> inside the loop ).</p> <p>The general solution I've found suggest a get_post_meta inside a foreach loop: <a href="https://stackoverflow.com/questions/14699686/custom-post-type-loop-only-displays-first-post-meta-data">https://stackoverflow.com/questions/14699686/custom-post-type-loop-only-displays-first-post-meta-data</a></p> <p>But in this case, I really only want the <code>meta_values</code> in an array for a specific <strong>CPT</strong>.</p> <p>Database Logic tells me that this should be only 2 queries... one on the post_meta table, one on the the posts table. It might include some joins, but still a rather inexpensive couple of queries.</p>
[ { "answer_id": 235445, "author": "Krzysztof Grabania", "author_id": 81795, "author_profile": "https://wordpress.stackexchange.com/users/81795", "pm_score": 0, "selected": false, "text": "<p>Data attributes can be easly overriden, for example by jQuery function <code>data</code>. I would do this with attributes using generated md5 from user id and login, for example <code>$user_id . '-' . md5($user_id . $user_login)</code>. You php script should check user by:</p>\n\n<ul>\n<li><p>exploding attribute by <code>-</code> sign</p></li>\n<li><p>get user by id (before - sign)</p></li>\n<li><p>generate md5 and compare it with value after <code>-</code> sign</p></li>\n</ul>\n" }, { "answer_id": 235451, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 1, "selected": false, "text": "<p>When dealing with submit forms, even if they are sent with AJAX, you must play by the <strong><em><a href=\"https://www.owasp.org/index.php/Don&#39;t_trust_user_input\" rel=\"nofollow\">Never trust user's input</a></em></strong> rule.</p>\n\n<p>Every <code>data-attribute</code> can be changed, edited via Inspector. Your only trusted validation should be on the server side, as you did with:</p>\n\n<pre><code>if ( isset($_POST['author_id']) || is_numeric($_POST['author_id']) )\n</code></pre>\n\n<p>Personally, I would inverse the logic and first check all the attributes before starting any action.</p>\n\n<pre><code>check_ajax_referer( '*****', 'security' );\n\nif ( ! isset($_POST['author_id']) &amp;&amp; ! is_numeric($_POST['author_id']) ) {\n // tell the villain that this tower is watched\n wp_send_json_error( 'Wrong author ID!' );\n}\n\n// now is safe to cache\n$author_id = $_POST['author_id'];\n</code></pre>\n\n<p>Stolen from <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json_error\" rel=\"nofollow\">Codex</a>.</p>\n\n<p>The parameters are passed through a URI encoding so I wouldn't worry too much about data type or casting.</p>\n" }, { "answer_id": 235459, "author": "David", "author_id": 31323, "author_profile": "https://wordpress.stackexchange.com/users/31323", "pm_score": 1, "selected": false, "text": "<p>No, it is not more or less risky than excepting data from the user via URL parameter or a POST request sent by an HTML form. For all of these methods applies the rule Andrei Lupu already mentioned: <strong>Consider each input as possibly harmful</strong>.</p>\n\n<p>To protect your system you should start by <em>validating</em> the input against your expectation, if possible. E.g. you know that the user ID will always be numeric. After validation you have to <em>escape</em> special characters on <em>context change</em>. If you want to use a string as part of a SQL query, it's a context change and thus you must escape characters with a special meaning in an SQL context. In your case, <code>wpdb::insert()</code> doest that for you.</p>\n\n<p>Another possible context change would be, if you want to use user input directly in a HTML context (print it to your template). </p>\n\n<p>Another important step in a client-server-application is to verify the command was actually intended by the user. Otherwise you open your application to <a href=\"https://en.wikipedia.org/wiki/Cross-site_request_forgery\" rel=\"nofollow\">cross-side request forgery (CSRF)</a> attacks. As you (obviously) use WordPress' nonce functions and the feature is only available for logged in users, you're command is fairly authenticated.</p>\n\n<p>So from a today perspective, your code example is considered to be secure.</p>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235463", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37479/" ]
### Here's the TLDR: Is is possible to get all meta keys from a specific CPT without a database hit for each post? If so, how can I do this the Wordpress way? =========================================== This seems like a simple thing to do ( at least from a database perspective ) but I'm looking for the Wordpress way to get multiple post\_meta values from a bunch of CPTs. Example: Every `Product` Custom Post Type has the following fields ( plus many more ) which holds discrete pieces of information: * `_ns_research_document` * `_ns_monograph_document` * `_ns_profile_document` Essentially, I want a list of ALL ***Research** Docs*, ***Monographs*** and ***Profile** Docs*. Currently this site has 72 `product` posts, but other sites this will be used on have over a thousand. I assume there's a way to do this with wordpress methods that doesn't involve [at least] 73 calls ( one for all posts, and then `get_post_meta` inside the loop ). The general solution I've found suggest a get\_post\_meta inside a foreach loop: <https://stackoverflow.com/questions/14699686/custom-post-type-loop-only-displays-first-post-meta-data> But in this case, I really only want the `meta_values` in an array for a specific **CPT**. Database Logic tells me that this should be only 2 queries... one on the post\_meta table, one on the the posts table. It might include some joins, but still a rather inexpensive couple of queries.
When dealing with submit forms, even if they are sent with AJAX, you must play by the ***[Never trust user's input](https://www.owasp.org/index.php/Don't_trust_user_input)*** rule. Every `data-attribute` can be changed, edited via Inspector. Your only trusted validation should be on the server side, as you did with: ``` if ( isset($_POST['author_id']) || is_numeric($_POST['author_id']) ) ``` Personally, I would inverse the logic and first check all the attributes before starting any action. ``` check_ajax_referer( '*****', 'security' ); if ( ! isset($_POST['author_id']) && ! is_numeric($_POST['author_id']) ) { // tell the villain that this tower is watched wp_send_json_error( 'Wrong author ID!' ); } // now is safe to cache $author_id = $_POST['author_id']; ``` Stolen from [Codex](https://codex.wordpress.org/Function_Reference/wp_send_json_error). The parameters are passed through a URI encoding so I wouldn't worry too much about data type or casting.
235,466
<p>I want to hide Add to Cart button on woocommerce Product description page of a particular product with product id, say, 1234. </p> <p>Following code hides Add to Cart button on woocommerce Product description pages of ALL the products:</p> <pre><code>function remove_product_description_add_cart_button(){ remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); } add_action('init','remove_product_description_add_cart_button'); </code></pre> <p>But when I try to apply above remove_action for the particular product having product id 1234 using following code, it does not work?</p> <pre><code>function remove_product_description_add_cart_button(){ global $product; //Remove Add to Cart button from product description of product with id 1234 if ($product-&gt;id == 1234){ remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); } } add_action('init','remove_product_description_add_cart_button'); </code></pre> <p>Can anyone help with this please?</p>
[ { "answer_id": 235474, "author": "Max", "author_id": 78380, "author_profile": "https://wordpress.stackexchange.com/users/78380", "pm_score": 2, "selected": true, "text": "<p>You are applying your hook to early. Wordpress is perfectly fine with removing that action, however it doesn't know what product/post ID is yet. You can rewrite the last line of your code like that:</p>\n\n<pre><code>add_action('wp','remove_product_description_add_cart_button');\n</code></pre>\n\n<p>Wordpress actions chronologically - <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n" }, { "answer_id": 284688, "author": "suthanalley", "author_id": 124808, "author_profile": "https://wordpress.stackexchange.com/users/124808", "pm_score": 0, "selected": false, "text": "<p>You can easily remove the add to cart button from product pages by adding this in woocommerce.php (located wp-content/plugins/woocommerce)</p>\n\n<pre><code> function WpBlog() {\n remove_action( 'woocommerce_after_shop_loop_item', \n 'woocommerce_template_loop_add_to_cart');\n remove_action( 'woocommerce_single_product_summary', \n 'woocommerce_template_single_add_to_cart');\n return WooCommerce::instance();\n }\n</code></pre>\n\n<p>After adding this code, reload the page and you will see that the button has been hidden. </p>\n\n<p>You can also remove the add to cart button from specific Product pages using this code in functions.php (located in the theme folder):</p>\n\n<pre><code> add_filter('woocommerce_is_purchasable', 'wpblog_specific_product');\n function wpblog_specific_product($purchaseable_product_wpblog, $product) \n {\n return ($product-&gt;id == specific_product_id (512) ? false : \n $purchaseable_product_wpblog);\n }\n</code></pre>\n\n<p>For reference you can see the details to easily hide and show add to cart buttons <a href=\"https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/\" rel=\"nofollow noreferrer\">https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/</a></p>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235466", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95187/" ]
I want to hide Add to Cart button on woocommerce Product description page of a particular product with product id, say, 1234. Following code hides Add to Cart button on woocommerce Product description pages of ALL the products: ``` function remove_product_description_add_cart_button(){ remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); } add_action('init','remove_product_description_add_cart_button'); ``` But when I try to apply above remove\_action for the particular product having product id 1234 using following code, it does not work? ``` function remove_product_description_add_cart_button(){ global $product; //Remove Add to Cart button from product description of product with id 1234 if ($product->id == 1234){ remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); } } add_action('init','remove_product_description_add_cart_button'); ``` Can anyone help with this please?
You are applying your hook to early. Wordpress is perfectly fine with removing that action, however it doesn't know what product/post ID is yet. You can rewrite the last line of your code like that: ``` add_action('wp','remove_product_description_add_cart_button'); ``` Wordpress actions chronologically - <https://codex.wordpress.org/Plugin_API/Action_Reference>
235,483
<p>I followed the install instructions at wp-cli.org and am unable to connect to database. I am using a newly installed (this morning) version of MAMP PRO.</p> <pre><code>which php /usr/bin/php echo $WP_CLI_PHP /Applications/MAMP/bin/php/php5.5.14/bin/php wp --info PHP binary: /usr/bin/php PHP version: 5.5.14 php.ini used: WP-CLI root dir: phar://wp-cli.phar WP-CLI packages dir: WP-CLI global config: WP-CLI project config: WP-CLI version: 0.24.1 </code></pre> <p>When I run <code>wp &lt;anything&gt;</code> in the command line, I get <code>Error: Error establishing a database connection</code></p>
[ { "answer_id": 235496, "author": "Graham Lutz", "author_id": 100738, "author_profile": "https://wordpress.stackexchange.com/users/100738", "pm_score": 2, "selected": false, "text": "<p>Alright - so here's what I figured out.</p>\n\n<p><code>~/.bash_profile</code> should look like this:</p>\n\n<pre><code>#MAMP Madness\nexport PATH=/Applications/MAMP/Library/bin:$PATH\nPHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`\nexport PATH=/Applications/MAMP/bin/php/${PHP_VERSION}bin:$PATH\n</code></pre>\n" }, { "answer_id": 294678, "author": "Stacy", "author_id": 137247, "author_profile": "https://wordpress.stackexchange.com/users/137247", "pm_score": 3, "selected": false, "text": "<p>I noticed a typo in the original answer, but it did work for me in my .zshrc file. The typo was the end of the last line, it was missing the final <code>/</code> between the php version and bin directory </p>\n\n<pre><code>#MAMP Madness\nexport PATH=/Applications/MAMP/Library/bin:$PATH\nPHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`\nexport PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH\n</code></pre>\n" }, { "answer_id": 305313, "author": "mtedwards", "author_id": 144820, "author_profile": "https://wordpress.stackexchange.com/users/144820", "pm_score": 2, "selected": false, "text": "<p>I've found it seems to work a lot better if, in wp-config.php you use: </p>\n\n<p><code>define('DB_HOST', '127.0.0.1');</code></p>\n\n<p>instead of:</p>\n\n<p><code>define('DB_HOST', 'localhost');</code></p>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235483", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100738/" ]
I followed the install instructions at wp-cli.org and am unable to connect to database. I am using a newly installed (this morning) version of MAMP PRO. ``` which php /usr/bin/php echo $WP_CLI_PHP /Applications/MAMP/bin/php/php5.5.14/bin/php wp --info PHP binary: /usr/bin/php PHP version: 5.5.14 php.ini used: WP-CLI root dir: phar://wp-cli.phar WP-CLI packages dir: WP-CLI global config: WP-CLI project config: WP-CLI version: 0.24.1 ``` When I run `wp <anything>` in the command line, I get `Error: Error establishing a database connection`
I noticed a typo in the original answer, but it did work for me in my .zshrc file. The typo was the end of the last line, it was missing the final `/` between the php version and bin directory ``` #MAMP Madness export PATH=/Applications/MAMP/Library/bin:$PATH PHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1` export PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH ```
235,488
<p>My website receives this error when going to the home page: Parse error: syntax error, unexpected 'endif' (T_ENDIF) in /home/wha2wearco/wha2wear.com/wp-content/themes/pro-blogg/index.php on line 63</p> <p>But I don't see that error on line 63. Actually, I don't see any error. Can anyone check the code for me, please:</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php if (dess_setting('dess_show_slider') == 1) : $args = array( 'post_type' =&gt; 'post', 'meta_key' =&gt; 'show_in_slider', 'meta_value' =&gt; 'yes', 'posts_per_page' =&gt; -1, 'ignore_sticky_posts' =&gt; true ); $the_query = new WP_Query( $args ); if ( $the_query-&gt;have_posts() ) : echo '&lt;div class="home_slider"&gt;&lt;ul class="slides"&gt;'; while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); $type = get_post_meta($post-&gt;ID,'page_featured_type',true); switch ($type) { case 'youtube': echo '&lt;li&gt;&lt;iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;/li&gt;'; break; case 'vimeo': echo '&lt;li&gt;&lt;iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&amp;amp;byline=0&amp;amp;portrait=0&amp;amp;color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen&gt;&lt;/iframe&gt;&lt;/li&gt;'; break; default: $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id($post-&gt;ID), 'full' ); echo '&lt;li&gt;&lt;a style="background-image: url('.$thumbnail[0].')" class="home_slide_bg" href="'.get_permalink().'"&gt;&lt;/a&gt;&lt;a href="'.get_permalink().'"&gt;'.get_the_title().'&lt;/a&gt;&lt;/li&gt;'; break; } endwhile; echo '&lt;/ul&gt;&lt;/div&gt;'; wp_reset_postdata(); endif; endif; ?&gt; &lt;div class="container"&gt; &lt;div class="post_content"&gt; &lt;div class="home_posts"&gt; &lt;?php $args2 = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 10, 'paged' =&gt; ( get_query_var('paged') ? get_query_var('paged') : 2), ); $query = new WP_Query( $args2 ); if ( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); echo '&lt;div class="grid_post"&gt; &lt;h3&gt;&lt;a href="'.get_permalink().'"&gt;'.get_the_title().'&lt;/a&gt;&lt;/h3&gt;'; $type = get_post_meta($post-&gt;ID,'page_featured_type',true); switch ($type) { case 'youtube': echo '&lt;iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;'; break; case 'vimeo': echo '&lt;iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&amp;amp;byline=0&amp;amp;portrait=0&amp;amp;color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen&gt;&lt;/iframe&gt;'; break; default: echo '&lt;div class="grid_post_img"&gt; &lt;a href="'.get_permalink().'"&gt;'.get_the_post_thumbnail().'&lt;/a&gt; &lt;/div&gt;'; break; } echo '&lt;div class="grid_home_posts"&gt; &lt;p&gt;'.dess_get_excerpt(120).'&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; '; endwhile; endif; ?&gt; &lt;/div&gt; &lt;?php echo '&lt;div class="load_more_content"&gt;&lt;div class="load_more_text"&gt;'; ob_start(); next_posts_link('LOAD MORE',$query-&gt;max_num_pages); $buffer = ob_get_contents(); ob_end_clean(); if (!empty($buffer)) echo $buffer; echo'&lt;/div&gt;&lt;/div&gt;'; $max_pages = $query-&gt;max_num_pages; wp_reset_postdata(); endif; ?&gt; &lt;span id="max-pages" style="display:none"&gt;&lt;?php echo $max_pages ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;?php get_sidebar(); ?&gt; &lt;div class="clear"&gt;&lt;/div&gt; </code></pre> <p> </p>
[ { "answer_id": 235496, "author": "Graham Lutz", "author_id": 100738, "author_profile": "https://wordpress.stackexchange.com/users/100738", "pm_score": 2, "selected": false, "text": "<p>Alright - so here's what I figured out.</p>\n\n<p><code>~/.bash_profile</code> should look like this:</p>\n\n<pre><code>#MAMP Madness\nexport PATH=/Applications/MAMP/Library/bin:$PATH\nPHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`\nexport PATH=/Applications/MAMP/bin/php/${PHP_VERSION}bin:$PATH\n</code></pre>\n" }, { "answer_id": 294678, "author": "Stacy", "author_id": 137247, "author_profile": "https://wordpress.stackexchange.com/users/137247", "pm_score": 3, "selected": false, "text": "<p>I noticed a typo in the original answer, but it did work for me in my .zshrc file. The typo was the end of the last line, it was missing the final <code>/</code> between the php version and bin directory </p>\n\n<pre><code>#MAMP Madness\nexport PATH=/Applications/MAMP/Library/bin:$PATH\nPHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`\nexport PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH\n</code></pre>\n" }, { "answer_id": 305313, "author": "mtedwards", "author_id": 144820, "author_profile": "https://wordpress.stackexchange.com/users/144820", "pm_score": 2, "selected": false, "text": "<p>I've found it seems to work a lot better if, in wp-config.php you use: </p>\n\n<p><code>define('DB_HOST', '127.0.0.1');</code></p>\n\n<p>instead of:</p>\n\n<p><code>define('DB_HOST', 'localhost');</code></p>\n" } ]
2016/08/09
[ "https://wordpress.stackexchange.com/questions/235488", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91761/" ]
My website receives this error when going to the home page: Parse error: syntax error, unexpected 'endif' (T\_ENDIF) in /home/wha2wearco/wha2wear.com/wp-content/themes/pro-blogg/index.php on line 63 But I don't see that error on line 63. Actually, I don't see any error. Can anyone check the code for me, please: ``` <?php get_header(); ?> <?php if (dess_setting('dess_show_slider') == 1) : $args = array( 'post_type' => 'post', 'meta_key' => 'show_in_slider', 'meta_value' => 'yes', 'posts_per_page' => -1, 'ignore_sticky_posts' => true ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : echo '<div class="home_slider"><ul class="slides">'; while ( $the_query->have_posts() ) : $the_query->the_post(); $type = get_post_meta($post->ID,'page_featured_type',true); switch ($type) { case 'youtube': echo '<li><iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen></iframe></li>'; break; case 'vimeo': echo '<li><iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&amp;byline=0&amp;portrait=0&amp;color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></li>'; break; default: $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); echo '<li><a style="background-image: url('.$thumbnail[0].')" class="home_slide_bg" href="'.get_permalink().'"></a><a href="'.get_permalink().'">'.get_the_title().'</a></li>'; break; } endwhile; echo '</ul></div>'; wp_reset_postdata(); endif; endif; ?> <div class="container"> <div class="post_content"> <div class="home_posts"> <?php $args2 = array( 'post_type' => 'post', 'posts_per_page' => 10, 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 2), ); $query = new WP_Query( $args2 ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); echo '<div class="grid_post"> <h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>'; $type = get_post_meta($post->ID,'page_featured_type',true); switch ($type) { case 'youtube': echo '<iframe width="560" height="315" src="http://www.youtube.com/embed/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?wmode=transparent" frameborder="0" allowfullscreen></iframe>'; break; case 'vimeo': echo '<iframe src="http://player.vimeo.com/video/'.get_post_meta( get_the_ID(), 'page_video_id', true ).'?title=0&amp;byline=0&amp;portrait=0&amp;color=03b3fc" width="500" height="338" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'; break; default: echo '<div class="grid_post_img"> <a href="'.get_permalink().'">'.get_the_post_thumbnail().'</a> </div>'; break; } echo '<div class="grid_home_posts"> <p>'.dess_get_excerpt(120).'</p> </div> </div> '; endwhile; endif; ?> </div> <?php echo '<div class="load_more_content"><div class="load_more_text">'; ob_start(); next_posts_link('LOAD MORE',$query->max_num_pages); $buffer = ob_get_contents(); ob_end_clean(); if (!empty($buffer)) echo $buffer; echo'</div></div>'; $max_pages = $query->max_num_pages; wp_reset_postdata(); endif; ?> <span id="max-pages" style="display:none"><?php echo $max_pages ?></span> </div> <?php get_sidebar(); ?> <div class="clear"></div> ```
I noticed a typo in the original answer, but it did work for me in my .zshrc file. The typo was the end of the last line, it was missing the final `/` between the php version and bin directory ``` #MAMP Madness export PATH=/Applications/MAMP/Library/bin:$PATH PHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1` export PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH ```
235,501
<p>How can I fetch a <code>div</code> content from a post?</p> <p>Using <code>the_content()</code> can fetch all the data but instead of that, I need specific content from the <code>div</code> only. So far, all I could do was get the link of the post as the <code>div</code> content. </p> <p>Here is was I am trying to do:</p> <pre><code>&lt;?php while (have_posts()) : the_post(); ?&gt; &lt;li style = "text-align: center; float : left;"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php echo get_the_post_thumbnail($id); ?&gt;&lt;/a&gt; &lt;div class="title"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="&lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id = "result"&gt;` &lt;?php echo "&lt;script&gt; $('#result').load( '".the_permalink()." .ps_post_description' ); &lt;/script&gt;"; ?&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; </code></pre> <p><code>ps_post_description</code> is the class of the div for which I need the content.</p>
[ { "answer_id": 235503, "author": "lucian", "author_id": 70333, "author_profile": "https://wordpress.stackexchange.com/users/70333", "pm_score": 1, "selected": false, "text": "<p>You'd have to get all the content out and then trim it down to that specific div. But why would you want to do that? It's inneficient and cumbersome - extra work to put it into the database, extra work to get it out.\nHave you considered adding a custom field to use just for that piece of content?\n(The excerpt sounds like what you're looking for, it's already built in and all you'd have to do to use it is <code>&lt;?php the_excerpt(); ?&gt;</code>)</p>\n" }, { "answer_id": 235507, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>Using <a href=\"http://php.net/manual/en/class.domdocument.php\" rel=\"nofollow\">DOMDocument</a> and <a href=\"http://php.net/manual/en/class.domxpath.php\" rel=\"nofollow\">DOMXPath</a> you could try this.</p>\n\n<pre><code>&lt;?php while (have_posts()) : the_post();\n\nob_start(); // run the_content() through the Output Buffer\nthe_content();\n$html = ob_get_clean(); // Store the formatted HTML\n$content = new DomDocument(); // Create a new DOMDocument Object to work with our HTML\n$content-&gt;loadHTML( $html ); // Load the $html into the new object\n$finder = new DomXPath( $content ); // Create a new DOMXPath object with our $content object that we will evaluate\n$classname = 'ps_post_description'; // The class we are looking for\n\n$item_list = $finder-&gt;query(\"//*[contains(@class, '$classname')]\"); // Evaluates our content and will return an object containing the number of items matching our query\n?&gt;\n\n&lt;li style = \"text-align: center; float : left;\"&gt;\n\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php echo get_the_post_thumbnail($id); ?&gt;&lt;/a&gt;\n\n &lt;div class=\"title\"&gt;\n &lt;a href=\"&lt;?php the_permalink() ?&gt;\" rel=\"bookmark\" title=\"&lt;?php the_title_attribute(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;\n &lt;/div&gt;\n\n &lt;div id = \"result\"&gt;`\n &lt;?php \n // echo the value of each item found\n // You might want to format or wrap your $value according to your specification if necessary\n for( $i = 0; $i &lt; $item_list-&gt;length; $i++ ){\n $value = $item_list-&gt;item( $i )-&gt;nodeValue;\n\n echo $value;\n\n // if you want the text to be a link to the post, you could use this instead \n // echo '&lt;a href=\"' . get_the_permalink() . '\"&gt;' . $value . '&lt;/a&gt;';\n\n } ?&gt;\n &lt;/div&gt;\n\n&lt;/li&gt;\n\n&lt;?php endwhile; ?&gt;\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Made use of <a href=\"http://php.net/manual/en/book.outcontrol.php\" rel=\"nofollow\">Output Buffering</a> to expand shortcodes before we try to load the HTML in DOMDocument</p>\n\n<p>Note that both solutions (before and after the edit) are working, so errors/warnings should come from elsewhere in your setup.</p>\n" } ]
2016/08/10
[ "https://wordpress.stackexchange.com/questions/235501", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99340/" ]
How can I fetch a `div` content from a post? Using `the_content()` can fetch all the data but instead of that, I need specific content from the `div` only. So far, all I could do was get the link of the post as the `div` content. Here is was I am trying to do: ``` <?php while (have_posts()) : the_post(); ?> <li style = "text-align: center; float : left;"> <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php echo get_the_post_thumbnail($id); ?></a> <div class="title"> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </div> <div id = "result">` <?php echo "<script> $('#result').load( '".the_permalink()." .ps_post_description' ); </script>"; ?> </div> </li> <?php endwhile; ?> ``` `ps_post_description` is the class of the div for which I need the content.
Using [DOMDocument](http://php.net/manual/en/class.domdocument.php) and [DOMXPath](http://php.net/manual/en/class.domxpath.php) you could try this. ``` <?php while (have_posts()) : the_post(); ob_start(); // run the_content() through the Output Buffer the_content(); $html = ob_get_clean(); // Store the formatted HTML $content = new DomDocument(); // Create a new DOMDocument Object to work with our HTML $content->loadHTML( $html ); // Load the $html into the new object $finder = new DomXPath( $content ); // Create a new DOMXPath object with our $content object that we will evaluate $classname = 'ps_post_description'; // The class we are looking for $item_list = $finder->query("//*[contains(@class, '$classname')]"); // Evaluates our content and will return an object containing the number of items matching our query ?> <li style = "text-align: center; float : left;"> <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php echo get_the_post_thumbnail($id); ?></a> <div class="title"> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </div> <div id = "result">` <?php // echo the value of each item found // You might want to format or wrap your $value according to your specification if necessary for( $i = 0; $i < $item_list->length; $i++ ){ $value = $item_list->item( $i )->nodeValue; echo $value; // if you want the text to be a link to the post, you could use this instead // echo '<a href="' . get_the_permalink() . '">' . $value . '</a>'; } ?> </div> </li> <?php endwhile; ?> ``` **UPDATE** Made use of [Output Buffering](http://php.net/manual/en/book.outcontrol.php) to expand shortcodes before we try to load the HTML in DOMDocument Note that both solutions (before and after the edit) are working, so errors/warnings should come from elsewhere in your setup.
235,538
<p>I have a archive page which is running under <code>https</code>. It doesn't loading any images within the post as all the image urls with <code>http</code>.</p> <p>It is giving an error like bellow,</p> <pre><code>Blocked loading mixed active content "http://www.example.com/wp-content/uploads/image.jpg" </code></pre> <p>How should I avoid that errors and load the images on that page.</p> <p>I saw in a article simplest way to fix it by converting urls into relative urls.</p> <p>eg: </p> <pre><code>http://www.example.com/wp-content/uploads/image.jpg -&gt; //wp-content/uploads/image.jpg </code></pre> <p>Any idea how should I do that ?</p>
[ { "answer_id": 235542, "author": "Amarendra Kumar", "author_id": 98677, "author_profile": "https://wordpress.stackexchange.com/users/98677", "pm_score": 0, "selected": false, "text": "<p>For Load images with http urls follow below steps:</p>\n\n<ol>\n<li>Go to phpmyadmin export database SQL file.</li>\n<li>Open SQL file in text editor.</li>\n<li>Find URL like \"<a href=\"https://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">https://www.example.com/wp-content/uploads/image.jpg</a>\".</li>\n<li>Replace URL like \"<a href=\"http://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">http://www.example.com/wp-content/uploads/image.jpg</a>\"</li>\n<li>Save the file and import updated SQL file.</li>\n</ol>\n\n<p>Hope its helpful.</p>\n" }, { "answer_id": 235555, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": true, "text": "<p>simply used the <code>str_replace</code> function to convert the urls to <code>https</code></p>\n\n<pre><code>$content = get_the_content();\n$content = apply_filters( 'the_content', $content );\n$content = str_replace( ']]&gt;', ']]&amp;gt;', $content );\n$content = str_replace(\"http://example.com/\", \"https://example.com/\", $content);\necho $content;\n</code></pre>\n\n<p>event you can make the relative urls with this way.</p>\n" }, { "answer_id": 235559, "author": "Jean-philippe Emond", "author_id": 99064, "author_profile": "https://wordpress.stackexchange.com/users/99064", "pm_score": 2, "selected": false, "text": "<p><strong>Do a backup before</strong></p>\n\n<p>I propose 2 thing for you:</p>\n\n<p><strong><em>First:</em></strong></p>\n\n<p>we have 3 possibility to change your content,</p>\n\n<ul>\n<li><p>permanent tool : <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">this Search &amp; replace for wordpress</a>\n.<br>\nIts not elegant and it may break your website but I use many time and it works as well. </p>\n\n<p>I think it can be help you to change database for your whole site in 1 shot. </p>\n\n<p><em>It not fix your image into plugin but it can be help at all.</em></p></li>\n<li><p>Temporary tool : If you aren’t comfortable doing this you can also use the free <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow\">really-simple-ssl</a> it change you content using add_action, http <strong>=></strong> https</p></li>\n<li><p>Temporary tool: adding this in your function.php:</p>\n\n<p><code>function change_http_into_content( $content ) {\n $custom_content = str_replace('http://', 'https://', $content );\n return $custom_content;\n}\nadd_filter( 'the_content', 'change_http_into_content' );</code></p></li>\n</ul>\n\n<p><strong><em>Second:</em></strong></p>\n\n<p>Also, don't forget to change your URL into the custom JS, AJAX request and other plugin.</p>\n" }, { "answer_id": 235561, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 2, "selected": false, "text": "<p>There is a pre-built tool called <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">Search and Replace</a> (recommended in the WordPress.org codex) that you can use to safely edit your database for just this type of change. Whether you choose to use a protocol relative link <code>//wp-content/...</code> or change everything to <code>https</code> to prevent mixed content is still your choice.</p>\n\n<p><strong>The reason for this tool, rather than the easier SQL replace is that data is <code>serialized</code> in the WordPress database and if not taken care of properly can/will be destroyed.</strong></p>\n\n<p>Always make a backup of your database before using this. The toole also gives the option of running a dry run so you can see what tables will be affected before actually performing the task. I personally recommend a dry run (for obvious reasons) and then write down the tables affected. From here, if your server is not exceptionally fast it will be wise to select only a small amount of tables to make changes to at one time so that the process does not hang up and fail. Writing down the affected tables means you can skip the unaffected ones entirely in the live run.</p>\n\n<p>It is not without risk, but if done properly you <strong>can</strong> run this on a live site. Since you will be changing valid, but not 100% accepted links into valid, and 100% accepted links it should not negatively affect your site so long as you do not give it so high of a workload that the process hangs. <em>Also, mistakes on a live site are bad so don't make those</em>.</p>\n\n<p>If you have a construction area to use, then absolutely use that. But if not, I am saying that it <strong>is</strong> possible to run this tool on a live site without any trouble. It is by no means fool proof though. I use this tool a lot for moving sites from construction (etc), if this is your first time... expect trouble, always expect and plan for the worst. Make a backup and have it ready.</p>\n\n<p><strong>Note on version 2.? vs 3.?:</strong></p>\n\n<p>If your server is older, then version 2 is likely the one for you. If your server is newer then give version 3 a try. They are both fairly easy to use, but if your server accepts v3 then use that one, it's newer and does everything all one one page which makes things very much more convenient. Try a dry run with version 3 and you should find out if your server can run that version or if you need to use the older version 2.</p>\n\n<p><strong>BIG NOTE:</strong></p>\n\n<p>As the tool should let you know, <strong>DO NOT</strong> forget to remove this once you are done using it. You don't want this left up for any nefarious character(s) to exploit.</p>\n" }, { "answer_id": 235564, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": false, "text": "<p>It's a fairly common issue when you update your WordPress site's URL form HTTP to HTTPS or if you are migrating to a new domain. While a partial solution is to update your WordPress' home and site URL in your settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/d5QVQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d5QVQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>That doesn't mean that the new URL structure in your posts will be fixed. This results in some of your pages pointing to your HTTP link instead.</p>\n\n<p>As a quick solution that ensures that all of the URLs for your website are up-to-date, use the following SQL query:</p>\n\n<h3>SQL Query</h3>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'OLD_URL', 'NEW_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'OLD_URL','NEW_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'OLD_URL', 'NEW_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'OLD_URL','NEW_URL');\n</code></pre>\n\n<ul>\n<li><code>OLD_URL</code> will be replaced with <code>http://example.com</code> (non-HTTP)</li>\n<li><code>NEW_URL</code> will be replaced with <code>https://example.com</code> (HTTPS)</li>\n</ul>\n\n<p>Be sure to back up your database before you perform this SQL query in case you run into an issue.</p>\n" } ]
2016/08/10
[ "https://wordpress.stackexchange.com/questions/235538", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68403/" ]
I have a archive page which is running under `https`. It doesn't loading any images within the post as all the image urls with `http`. It is giving an error like bellow, ``` Blocked loading mixed active content "http://www.example.com/wp-content/uploads/image.jpg" ``` How should I avoid that errors and load the images on that page. I saw in a article simplest way to fix it by converting urls into relative urls. eg: ``` http://www.example.com/wp-content/uploads/image.jpg -> //wp-content/uploads/image.jpg ``` Any idea how should I do that ?
simply used the `str_replace` function to convert the urls to `https` ``` $content = get_the_content(); $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); $content = str_replace("http://example.com/", "https://example.com/", $content); echo $content; ``` event you can make the relative urls with this way.
235,563
<p>I have to make a site where i have to assign posts to users.</p> <p>Want i already did:</p> <p>1: made new user roles with only 'read' enabled</p> <p>But i can't seem to figure out how to assign a certain post to a specific user/user role. So that when there logged in they will only see the post that is assigned to them, instead of seeing all the post and when they click it they get a message like: "Sorry, you have to be user*** to see this post."</p> <p>Does anyone know how to do this?</p>
[ { "answer_id": 235542, "author": "Amarendra Kumar", "author_id": 98677, "author_profile": "https://wordpress.stackexchange.com/users/98677", "pm_score": 0, "selected": false, "text": "<p>For Load images with http urls follow below steps:</p>\n\n<ol>\n<li>Go to phpmyadmin export database SQL file.</li>\n<li>Open SQL file in text editor.</li>\n<li>Find URL like \"<a href=\"https://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">https://www.example.com/wp-content/uploads/image.jpg</a>\".</li>\n<li>Replace URL like \"<a href=\"http://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">http://www.example.com/wp-content/uploads/image.jpg</a>\"</li>\n<li>Save the file and import updated SQL file.</li>\n</ol>\n\n<p>Hope its helpful.</p>\n" }, { "answer_id": 235555, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": true, "text": "<p>simply used the <code>str_replace</code> function to convert the urls to <code>https</code></p>\n\n<pre><code>$content = get_the_content();\n$content = apply_filters( 'the_content', $content );\n$content = str_replace( ']]&gt;', ']]&amp;gt;', $content );\n$content = str_replace(\"http://example.com/\", \"https://example.com/\", $content);\necho $content;\n</code></pre>\n\n<p>event you can make the relative urls with this way.</p>\n" }, { "answer_id": 235559, "author": "Jean-philippe Emond", "author_id": 99064, "author_profile": "https://wordpress.stackexchange.com/users/99064", "pm_score": 2, "selected": false, "text": "<p><strong>Do a backup before</strong></p>\n\n<p>I propose 2 thing for you:</p>\n\n<p><strong><em>First:</em></strong></p>\n\n<p>we have 3 possibility to change your content,</p>\n\n<ul>\n<li><p>permanent tool : <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">this Search &amp; replace for wordpress</a>\n.<br>\nIts not elegant and it may break your website but I use many time and it works as well. </p>\n\n<p>I think it can be help you to change database for your whole site in 1 shot. </p>\n\n<p><em>It not fix your image into plugin but it can be help at all.</em></p></li>\n<li><p>Temporary tool : If you aren’t comfortable doing this you can also use the free <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow\">really-simple-ssl</a> it change you content using add_action, http <strong>=></strong> https</p></li>\n<li><p>Temporary tool: adding this in your function.php:</p>\n\n<p><code>function change_http_into_content( $content ) {\n $custom_content = str_replace('http://', 'https://', $content );\n return $custom_content;\n}\nadd_filter( 'the_content', 'change_http_into_content' );</code></p></li>\n</ul>\n\n<p><strong><em>Second:</em></strong></p>\n\n<p>Also, don't forget to change your URL into the custom JS, AJAX request and other plugin.</p>\n" }, { "answer_id": 235561, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 2, "selected": false, "text": "<p>There is a pre-built tool called <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">Search and Replace</a> (recommended in the WordPress.org codex) that you can use to safely edit your database for just this type of change. Whether you choose to use a protocol relative link <code>//wp-content/...</code> or change everything to <code>https</code> to prevent mixed content is still your choice.</p>\n\n<p><strong>The reason for this tool, rather than the easier SQL replace is that data is <code>serialized</code> in the WordPress database and if not taken care of properly can/will be destroyed.</strong></p>\n\n<p>Always make a backup of your database before using this. The toole also gives the option of running a dry run so you can see what tables will be affected before actually performing the task. I personally recommend a dry run (for obvious reasons) and then write down the tables affected. From here, if your server is not exceptionally fast it will be wise to select only a small amount of tables to make changes to at one time so that the process does not hang up and fail. Writing down the affected tables means you can skip the unaffected ones entirely in the live run.</p>\n\n<p>It is not without risk, but if done properly you <strong>can</strong> run this on a live site. Since you will be changing valid, but not 100% accepted links into valid, and 100% accepted links it should not negatively affect your site so long as you do not give it so high of a workload that the process hangs. <em>Also, mistakes on a live site are bad so don't make those</em>.</p>\n\n<p>If you have a construction area to use, then absolutely use that. But if not, I am saying that it <strong>is</strong> possible to run this tool on a live site without any trouble. It is by no means fool proof though. I use this tool a lot for moving sites from construction (etc), if this is your first time... expect trouble, always expect and plan for the worst. Make a backup and have it ready.</p>\n\n<p><strong>Note on version 2.? vs 3.?:</strong></p>\n\n<p>If your server is older, then version 2 is likely the one for you. If your server is newer then give version 3 a try. They are both fairly easy to use, but if your server accepts v3 then use that one, it's newer and does everything all one one page which makes things very much more convenient. Try a dry run with version 3 and you should find out if your server can run that version or if you need to use the older version 2.</p>\n\n<p><strong>BIG NOTE:</strong></p>\n\n<p>As the tool should let you know, <strong>DO NOT</strong> forget to remove this once you are done using it. You don't want this left up for any nefarious character(s) to exploit.</p>\n" }, { "answer_id": 235564, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": false, "text": "<p>It's a fairly common issue when you update your WordPress site's URL form HTTP to HTTPS or if you are migrating to a new domain. While a partial solution is to update your WordPress' home and site URL in your settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/d5QVQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d5QVQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>That doesn't mean that the new URL structure in your posts will be fixed. This results in some of your pages pointing to your HTTP link instead.</p>\n\n<p>As a quick solution that ensures that all of the URLs for your website are up-to-date, use the following SQL query:</p>\n\n<h3>SQL Query</h3>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'OLD_URL', 'NEW_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'OLD_URL','NEW_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'OLD_URL', 'NEW_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'OLD_URL','NEW_URL');\n</code></pre>\n\n<ul>\n<li><code>OLD_URL</code> will be replaced with <code>http://example.com</code> (non-HTTP)</li>\n<li><code>NEW_URL</code> will be replaced with <code>https://example.com</code> (HTTPS)</li>\n</ul>\n\n<p>Be sure to back up your database before you perform this SQL query in case you run into an issue.</p>\n" } ]
2016/08/10
[ "https://wordpress.stackexchange.com/questions/235563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44597/" ]
I have to make a site where i have to assign posts to users. Want i already did: 1: made new user roles with only 'read' enabled But i can't seem to figure out how to assign a certain post to a specific user/user role. So that when there logged in they will only see the post that is assigned to them, instead of seeing all the post and when they click it they get a message like: "Sorry, you have to be user\*\*\* to see this post." Does anyone know how to do this?
simply used the `str_replace` function to convert the urls to `https` ``` $content = get_the_content(); $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); $content = str_replace("http://example.com/", "https://example.com/", $content); echo $content; ``` event you can make the relative urls with this way.
235,570
<p>I have a category template which displays some posts and some content generated by a plugin template, which uses <code>the_permalink()</code> to refer to the current url. The category template looks like this (<code>category.php</code>):</p> <pre><code>&lt;?php $categoryQuery = get_the_category(); ?&gt; &lt;?php $parentCategory = get_term_by('id', $categoryQuery[0]-&gt;parent, 'category') ?&gt; &lt;?php if ($parentCategory-&gt;slug !== 'teams' &amp;&amp; $categoryQuery[0]-&gt;slug !== 'teams') { get_template_part( 'archive', get_post_format() ); } else { get_header(); ?&gt; &lt;div class="container main-outer"&gt; &lt;?php set_query_var( 'categorySlug', $categoryQuery[0]-&gt;slug ); ?&gt; &lt;?php set_query_var( 'categoryName', $categoryQuery[0]-&gt;name ); ?&gt; &lt;?php get_template_part( 'teams-header', get_post_format() ); ?&gt; &lt;?php } ?&gt; ... // Here goes the plugin template ... </code></pre> <p>And the <code>teams-header.php</code> file looks like this:</p> <pre><code>... &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $featpost = new WP_Query(array( 'category_name' =&gt; $categorySlug, 'showposts' =&gt; 5, 'paged' =&gt; $paged, )); $newnum = 1; $maxNumPages = $featpost-&gt;max_num_pages; while($featpost-&gt;have_posts()) : $featpost-&gt;the_post(); ... $newnum++; endwhile; ?&gt; &lt;?php wp_reset_postdata() ?&gt; &lt;div class="pagination-links"&gt; &lt;br /&gt; &lt;?php next_posts_link('&amp;laquo; Older entries', $maxNumPages) ?&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;?php previous_posts_link('Recent entries &amp;raquo;') ?&gt; &lt;/div&gt; </code></pre> <p>The problem is that the plugin template is showing the first displayed post url as the current url (with <code>the_permalink()</code>), and not the category one. <code>wp_reset_postdata()</code> should reset the current post data, but maybe I'm missing something. Any idea?</p>
[ { "answer_id": 235542, "author": "Amarendra Kumar", "author_id": 98677, "author_profile": "https://wordpress.stackexchange.com/users/98677", "pm_score": 0, "selected": false, "text": "<p>For Load images with http urls follow below steps:</p>\n\n<ol>\n<li>Go to phpmyadmin export database SQL file.</li>\n<li>Open SQL file in text editor.</li>\n<li>Find URL like \"<a href=\"https://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">https://www.example.com/wp-content/uploads/image.jpg</a>\".</li>\n<li>Replace URL like \"<a href=\"http://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">http://www.example.com/wp-content/uploads/image.jpg</a>\"</li>\n<li>Save the file and import updated SQL file.</li>\n</ol>\n\n<p>Hope its helpful.</p>\n" }, { "answer_id": 235555, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": true, "text": "<p>simply used the <code>str_replace</code> function to convert the urls to <code>https</code></p>\n\n<pre><code>$content = get_the_content();\n$content = apply_filters( 'the_content', $content );\n$content = str_replace( ']]&gt;', ']]&amp;gt;', $content );\n$content = str_replace(\"http://example.com/\", \"https://example.com/\", $content);\necho $content;\n</code></pre>\n\n<p>event you can make the relative urls with this way.</p>\n" }, { "answer_id": 235559, "author": "Jean-philippe Emond", "author_id": 99064, "author_profile": "https://wordpress.stackexchange.com/users/99064", "pm_score": 2, "selected": false, "text": "<p><strong>Do a backup before</strong></p>\n\n<p>I propose 2 thing for you:</p>\n\n<p><strong><em>First:</em></strong></p>\n\n<p>we have 3 possibility to change your content,</p>\n\n<ul>\n<li><p>permanent tool : <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">this Search &amp; replace for wordpress</a>\n.<br>\nIts not elegant and it may break your website but I use many time and it works as well. </p>\n\n<p>I think it can be help you to change database for your whole site in 1 shot. </p>\n\n<p><em>It not fix your image into plugin but it can be help at all.</em></p></li>\n<li><p>Temporary tool : If you aren’t comfortable doing this you can also use the free <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow\">really-simple-ssl</a> it change you content using add_action, http <strong>=></strong> https</p></li>\n<li><p>Temporary tool: adding this in your function.php:</p>\n\n<p><code>function change_http_into_content( $content ) {\n $custom_content = str_replace('http://', 'https://', $content );\n return $custom_content;\n}\nadd_filter( 'the_content', 'change_http_into_content' );</code></p></li>\n</ul>\n\n<p><strong><em>Second:</em></strong></p>\n\n<p>Also, don't forget to change your URL into the custom JS, AJAX request and other plugin.</p>\n" }, { "answer_id": 235561, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 2, "selected": false, "text": "<p>There is a pre-built tool called <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">Search and Replace</a> (recommended in the WordPress.org codex) that you can use to safely edit your database for just this type of change. Whether you choose to use a protocol relative link <code>//wp-content/...</code> or change everything to <code>https</code> to prevent mixed content is still your choice.</p>\n\n<p><strong>The reason for this tool, rather than the easier SQL replace is that data is <code>serialized</code> in the WordPress database and if not taken care of properly can/will be destroyed.</strong></p>\n\n<p>Always make a backup of your database before using this. The toole also gives the option of running a dry run so you can see what tables will be affected before actually performing the task. I personally recommend a dry run (for obvious reasons) and then write down the tables affected. From here, if your server is not exceptionally fast it will be wise to select only a small amount of tables to make changes to at one time so that the process does not hang up and fail. Writing down the affected tables means you can skip the unaffected ones entirely in the live run.</p>\n\n<p>It is not without risk, but if done properly you <strong>can</strong> run this on a live site. Since you will be changing valid, but not 100% accepted links into valid, and 100% accepted links it should not negatively affect your site so long as you do not give it so high of a workload that the process hangs. <em>Also, mistakes on a live site are bad so don't make those</em>.</p>\n\n<p>If you have a construction area to use, then absolutely use that. But if not, I am saying that it <strong>is</strong> possible to run this tool on a live site without any trouble. It is by no means fool proof though. I use this tool a lot for moving sites from construction (etc), if this is your first time... expect trouble, always expect and plan for the worst. Make a backup and have it ready.</p>\n\n<p><strong>Note on version 2.? vs 3.?:</strong></p>\n\n<p>If your server is older, then version 2 is likely the one for you. If your server is newer then give version 3 a try. They are both fairly easy to use, but if your server accepts v3 then use that one, it's newer and does everything all one one page which makes things very much more convenient. Try a dry run with version 3 and you should find out if your server can run that version or if you need to use the older version 2.</p>\n\n<p><strong>BIG NOTE:</strong></p>\n\n<p>As the tool should let you know, <strong>DO NOT</strong> forget to remove this once you are done using it. You don't want this left up for any nefarious character(s) to exploit.</p>\n" }, { "answer_id": 235564, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": false, "text": "<p>It's a fairly common issue when you update your WordPress site's URL form HTTP to HTTPS or if you are migrating to a new domain. While a partial solution is to update your WordPress' home and site URL in your settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/d5QVQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d5QVQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>That doesn't mean that the new URL structure in your posts will be fixed. This results in some of your pages pointing to your HTTP link instead.</p>\n\n<p>As a quick solution that ensures that all of the URLs for your website are up-to-date, use the following SQL query:</p>\n\n<h3>SQL Query</h3>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'OLD_URL', 'NEW_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'OLD_URL','NEW_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'OLD_URL', 'NEW_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'OLD_URL','NEW_URL');\n</code></pre>\n\n<ul>\n<li><code>OLD_URL</code> will be replaced with <code>http://example.com</code> (non-HTTP)</li>\n<li><code>NEW_URL</code> will be replaced with <code>https://example.com</code> (HTTPS)</li>\n</ul>\n\n<p>Be sure to back up your database before you perform this SQL query in case you run into an issue.</p>\n" } ]
2016/08/10
[ "https://wordpress.stackexchange.com/questions/235570", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36778/" ]
I have a category template which displays some posts and some content generated by a plugin template, which uses `the_permalink()` to refer to the current url. The category template looks like this (`category.php`): ``` <?php $categoryQuery = get_the_category(); ?> <?php $parentCategory = get_term_by('id', $categoryQuery[0]->parent, 'category') ?> <?php if ($parentCategory->slug !== 'teams' && $categoryQuery[0]->slug !== 'teams') { get_template_part( 'archive', get_post_format() ); } else { get_header(); ?> <div class="container main-outer"> <?php set_query_var( 'categorySlug', $categoryQuery[0]->slug ); ?> <?php set_query_var( 'categoryName', $categoryQuery[0]->name ); ?> <?php get_template_part( 'teams-header', get_post_format() ); ?> <?php } ?> ... // Here goes the plugin template ... ``` And the `teams-header.php` file looks like this: ``` ... <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $featpost = new WP_Query(array( 'category_name' => $categorySlug, 'showposts' => 5, 'paged' => $paged, )); $newnum = 1; $maxNumPages = $featpost->max_num_pages; while($featpost->have_posts()) : $featpost->the_post(); ... $newnum++; endwhile; ?> <?php wp_reset_postdata() ?> <div class="pagination-links"> <br /> <?php next_posts_link('&laquo; Older entries', $maxNumPages) ?> &nbsp;&nbsp;&nbsp; <?php previous_posts_link('Recent entries &raquo;') ?> </div> ``` The problem is that the plugin template is showing the first displayed post url as the current url (with `the_permalink()`), and not the category one. `wp_reset_postdata()` should reset the current post data, but maybe I'm missing something. Any idea?
simply used the `str_replace` function to convert the urls to `https` ``` $content = get_the_content(); $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); $content = str_replace("http://example.com/", "https://example.com/", $content); echo $content; ``` event you can make the relative urls with this way.
235,571
<p>In the action <code>user_new_form</code>, the parameter <code>$user</code> returns a string <code>add-new-user</code>.</p> <p>I've used <code>esc_attr( get_the_author_meta( '_typeuser', $user-&gt;ID ) );</code> but I get an error.</p> <p>Another <a href="https://wordpress.stackexchange.com/questions/174386/having-an-add-action-user-new-form">question</a> on the topic is non-response at the moment but I've patched the problem with:</p> <pre><code>/* PROFIL FIELD */ add_action( 'show_user_profile', 'my_show_extra_profile_fields' ); add_action( 'edit_user_profile', 'my_show_extra_profile_fields' ); add_action( 'user_new_form', 'my_show_extra_profile_fields'); function my_show_extra_profile_fields( $user ) { if(is_string($user) === true){ $user = new stdClass();//create a new $user-&gt;ID = -9999; } $newsletter = esc_attr( get_the_author_meta( '_newsletter', $user-&gt;ID ) ); unset($user); } </code></pre> <p>How we can fix this problem without creating an object and setup <code>$user-&gt;ID</code> to <code>-9999</code> for new user?</p>
[ { "answer_id": 235542, "author": "Amarendra Kumar", "author_id": 98677, "author_profile": "https://wordpress.stackexchange.com/users/98677", "pm_score": 0, "selected": false, "text": "<p>For Load images with http urls follow below steps:</p>\n\n<ol>\n<li>Go to phpmyadmin export database SQL file.</li>\n<li>Open SQL file in text editor.</li>\n<li>Find URL like \"<a href=\"https://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">https://www.example.com/wp-content/uploads/image.jpg</a>\".</li>\n<li>Replace URL like \"<a href=\"http://www.example.com/wp-content/uploads/image.jpg\" rel=\"nofollow\">http://www.example.com/wp-content/uploads/image.jpg</a>\"</li>\n<li>Save the file and import updated SQL file.</li>\n</ol>\n\n<p>Hope its helpful.</p>\n" }, { "answer_id": 235555, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 2, "selected": true, "text": "<p>simply used the <code>str_replace</code> function to convert the urls to <code>https</code></p>\n\n<pre><code>$content = get_the_content();\n$content = apply_filters( 'the_content', $content );\n$content = str_replace( ']]&gt;', ']]&amp;gt;', $content );\n$content = str_replace(\"http://example.com/\", \"https://example.com/\", $content);\necho $content;\n</code></pre>\n\n<p>event you can make the relative urls with this way.</p>\n" }, { "answer_id": 235559, "author": "Jean-philippe Emond", "author_id": 99064, "author_profile": "https://wordpress.stackexchange.com/users/99064", "pm_score": 2, "selected": false, "text": "<p><strong>Do a backup before</strong></p>\n\n<p>I propose 2 thing for you:</p>\n\n<p><strong><em>First:</em></strong></p>\n\n<p>we have 3 possibility to change your content,</p>\n\n<ul>\n<li><p>permanent tool : <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">this Search &amp; replace for wordpress</a>\n.<br>\nIts not elegant and it may break your website but I use many time and it works as well. </p>\n\n<p>I think it can be help you to change database for your whole site in 1 shot. </p>\n\n<p><em>It not fix your image into plugin but it can be help at all.</em></p></li>\n<li><p>Temporary tool : If you aren’t comfortable doing this you can also use the free <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow\">really-simple-ssl</a> it change you content using add_action, http <strong>=></strong> https</p></li>\n<li><p>Temporary tool: adding this in your function.php:</p>\n\n<p><code>function change_http_into_content( $content ) {\n $custom_content = str_replace('http://', 'https://', $content );\n return $custom_content;\n}\nadd_filter( 'the_content', 'change_http_into_content' );</code></p></li>\n</ul>\n\n<p><strong><em>Second:</em></strong></p>\n\n<p>Also, don't forget to change your URL into the custom JS, AJAX request and other plugin.</p>\n" }, { "answer_id": 235561, "author": "KnightHawk", "author_id": 50492, "author_profile": "https://wordpress.stackexchange.com/users/50492", "pm_score": 2, "selected": false, "text": "<p>There is a pre-built tool called <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">Search and Replace</a> (recommended in the WordPress.org codex) that you can use to safely edit your database for just this type of change. Whether you choose to use a protocol relative link <code>//wp-content/...</code> or change everything to <code>https</code> to prevent mixed content is still your choice.</p>\n\n<p><strong>The reason for this tool, rather than the easier SQL replace is that data is <code>serialized</code> in the WordPress database and if not taken care of properly can/will be destroyed.</strong></p>\n\n<p>Always make a backup of your database before using this. The toole also gives the option of running a dry run so you can see what tables will be affected before actually performing the task. I personally recommend a dry run (for obvious reasons) and then write down the tables affected. From here, if your server is not exceptionally fast it will be wise to select only a small amount of tables to make changes to at one time so that the process does not hang up and fail. Writing down the affected tables means you can skip the unaffected ones entirely in the live run.</p>\n\n<p>It is not without risk, but if done properly you <strong>can</strong> run this on a live site. Since you will be changing valid, but not 100% accepted links into valid, and 100% accepted links it should not negatively affect your site so long as you do not give it so high of a workload that the process hangs. <em>Also, mistakes on a live site are bad so don't make those</em>.</p>\n\n<p>If you have a construction area to use, then absolutely use that. But if not, I am saying that it <strong>is</strong> possible to run this tool on a live site without any trouble. It is by no means fool proof though. I use this tool a lot for moving sites from construction (etc), if this is your first time... expect trouble, always expect and plan for the worst. Make a backup and have it ready.</p>\n\n<p><strong>Note on version 2.? vs 3.?:</strong></p>\n\n<p>If your server is older, then version 2 is likely the one for you. If your server is newer then give version 3 a try. They are both fairly easy to use, but if your server accepts v3 then use that one, it's newer and does everything all one one page which makes things very much more convenient. Try a dry run with version 3 and you should find out if your server can run that version or if you need to use the older version 2.</p>\n\n<p><strong>BIG NOTE:</strong></p>\n\n<p>As the tool should let you know, <strong>DO NOT</strong> forget to remove this once you are done using it. You don't want this left up for any nefarious character(s) to exploit.</p>\n" }, { "answer_id": 235564, "author": "Ethan O'Sullivan", "author_id": 98212, "author_profile": "https://wordpress.stackexchange.com/users/98212", "pm_score": 2, "selected": false, "text": "<p>It's a fairly common issue when you update your WordPress site's URL form HTTP to HTTPS or if you are migrating to a new domain. While a partial solution is to update your WordPress' home and site URL in your settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/d5QVQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d5QVQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>That doesn't mean that the new URL structure in your posts will be fixed. This results in some of your pages pointing to your HTTP link instead.</p>\n\n<p>As a quick solution that ensures that all of the URLs for your website are up-to-date, use the following SQL query:</p>\n\n<h3>SQL Query</h3>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'OLD_URL', 'NEW_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'OLD_URL','NEW_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'OLD_URL', 'NEW_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'OLD_URL','NEW_URL');\n</code></pre>\n\n<ul>\n<li><code>OLD_URL</code> will be replaced with <code>http://example.com</code> (non-HTTP)</li>\n<li><code>NEW_URL</code> will be replaced with <code>https://example.com</code> (HTTPS)</li>\n</ul>\n\n<p>Be sure to back up your database before you perform this SQL query in case you run into an issue.</p>\n" } ]
2016/08/10
[ "https://wordpress.stackexchange.com/questions/235571", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99064/" ]
In the action `user_new_form`, the parameter `$user` returns a string `add-new-user`. I've used `esc_attr( get_the_author_meta( '_typeuser', $user->ID ) );` but I get an error. Another [question](https://wordpress.stackexchange.com/questions/174386/having-an-add-action-user-new-form) on the topic is non-response at the moment but I've patched the problem with: ``` /* PROFIL FIELD */ add_action( 'show_user_profile', 'my_show_extra_profile_fields' ); add_action( 'edit_user_profile', 'my_show_extra_profile_fields' ); add_action( 'user_new_form', 'my_show_extra_profile_fields'); function my_show_extra_profile_fields( $user ) { if(is_string($user) === true){ $user = new stdClass();//create a new $user->ID = -9999; } $newsletter = esc_attr( get_the_author_meta( '_newsletter', $user->ID ) ); unset($user); } ``` How we can fix this problem without creating an object and setup `$user->ID` to `-9999` for new user?
simply used the `str_replace` function to convert the urls to `https` ``` $content = get_the_content(); $content = apply_filters( 'the_content', $content ); $content = str_replace( ']]>', ']]&gt;', $content ); $content = str_replace("http://example.com/", "https://example.com/", $content); echo $content; ``` event you can make the relative urls with this way.