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...
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</c...
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...
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_...
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_...
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:</...
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:</...
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 ma...
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 ...
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 th...
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_acti...
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 ...
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...
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...
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_pri...
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_pri...
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 e...
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 /s...
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/...
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...
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 ...
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 ...
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 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 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_interventi...
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 s...
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 s...
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...
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> endpoin...
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...
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 im...
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 you...
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 you...
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 you...
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 you...
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 i...
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...
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\nfuncti...
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\nfuncti...
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>...
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...
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...
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><cod...
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><cod...
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 (untes...
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;admin@bainternet.info&gt; */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz &lt;admin@bainternet.info&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;admin@bainternet.info&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://co...
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 <admin@bainternet.info> */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz <admin@bainternet.info> * @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 <admin@bainternet.info> * @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 <admin@bainternet.info> */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz <admin@bainternet.info> * @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 <admin@bainternet.info> * @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://co...
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 <admin@bainternet.info> */ class auto_child_page_menu { /** * class constructor * @author Ohad Raz <admin@bainternet.info> * @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 <admin@bainternet.info> * @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_l...
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_l...
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<...
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 thi...
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...
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_...
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_...
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 i...
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 var...
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 plug...
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=\"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 cl...
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 me...
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 wordpr...
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\"&...
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>ad...
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 b...
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 ...
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-swit...
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-swit...
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" }, { ...
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...
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...
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 th...
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 to...
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><c...
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 P...
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 retr...
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...
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 <co...
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 <co...
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 <co...
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\nRewrite...
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\nRewrite...
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<...
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 pr...
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 pr...
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 shou...
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. Th...
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</c...
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...
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 ...
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,...
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 ...
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 ...
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 kno...
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:</...
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:</...
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...
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 ...
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 ...
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 ...
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 ...
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.