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
268,495
<p><a href="https://developer.wordpress.org/reference/classes/wp_posts_list_table/extra_tablenav/" rel="noreferrer">WP_Posts_List_Table::extra_tablenav()</a> applies <a href="https://developer.wordpress.org/reference/hooks/restrict_manage_posts/" rel="noreferrer">restrict_manage_posts</a>, which can be used by a plugin to output extra dropdowns (or other markup) that allow filtering the posts in the table by arbitrary criteria.</p> <p>Similarly, <code>WP_(Users|Comments)_List_Table</code> have a <code>resttric_manage_(users|comment)</code> action for similar purposes.</p> <p>However, as far as I can tell, <a href="https://developer.wordpress.org/reference/classes/wp_terms_list_table/" rel="noreferrer">WP_Terms_List_Table</a> does <strong>not</strong>. Is this correct?</p> <p>I'm writing a plugin that relies heavily on <code>termmeta</code> on various custom taxonomies. My plugin adds custom columns to <code>edit-tags.php?taxonomy=my_custom_tax</code> that display the value(s) of the various <code>termmeta</code> for each term. It would greatly enhance the UX of my plugin if users were able to filter the term list by the distinct <code>meta_value</code>'s for my <code>meta_key</code>'s.</p> <p>Before I open a Trac ticket that proposes adding a <code>WP_Terms_List_Table::extra_tablenav()</code> method and <code>restrict_manage_terms</code> filter so that it would be possible to do what I want to do, I wanted to see if anyone here on WPSE knows:</p> <ol> <li>is there a viable work around (that doesn't involve something like hijacking <code>edit-tags.php?taxonomy=my_custom_tax</code> to redirect to a custom page that uses a custom subclass of <code>WP_Terms_List_Table</code>)?</li> <li>is there a (good) reason <code>WP_Terms_List_Table</code> doesn't currently support this functionality? <ol> <li>I realize for core there is no (good) reason to filter by any of the standard <code>WP_Term_List_Table</code> columns, but adding custom columns to it is fairly common and I can't believe I'm the only one who's ever wanted to filter by the values in custom columns.</li> </ol></li> </ol> <p><strong>Edit</strong></p> <p>I should note that I when displaying the <code>meta_value</code> in the custom column, I am outputting it as a link which effectively filters the term list by that value. The the reason the UX would be enchanced if users could choose from a dropdown (like in <code>WP_Posts_List_Table</code>) is that not all values of the <code>meta_value</code> are always visible on any given page of terms displayed in the list table. What <strong>I</strong> do to use the links to filter by a value that is not currently displayed on the current page is click on a random link, then edit the resulting URL in the browser's address field to have the <code>meta_value</code> <strong>I</strong> want to filter by. Not only is that a pain, but not all user's are savy enough to realize they can do this.</p>
[ { "answer_id": 268720, "author": "constancecchen", "author_id": 110820, "author_profile": "https://wordpress.stackexchange.com/users/110820", "pm_score": 2, "selected": false, "text": "<p>I've been searching around for the same answer to your question and running into the exact same issu...
2017/05/29
[ "https://wordpress.stackexchange.com/questions/268495", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113496/" ]
[WP\_Posts\_List\_Table::extra\_tablenav()](https://developer.wordpress.org/reference/classes/wp_posts_list_table/extra_tablenav/) applies [restrict\_manage\_posts](https://developer.wordpress.org/reference/hooks/restrict_manage_posts/), which can be used by a plugin to output extra dropdowns (or other markup) that allow filtering the posts in the table by arbitrary criteria. Similarly, `WP_(Users|Comments)_List_Table` have a `resttric_manage_(users|comment)` action for similar purposes. However, as far as I can tell, [WP\_Terms\_List\_Table](https://developer.wordpress.org/reference/classes/wp_terms_list_table/) does **not**. Is this correct? I'm writing a plugin that relies heavily on `termmeta` on various custom taxonomies. My plugin adds custom columns to `edit-tags.php?taxonomy=my_custom_tax` that display the value(s) of the various `termmeta` for each term. It would greatly enhance the UX of my plugin if users were able to filter the term list by the distinct `meta_value`'s for my `meta_key`'s. Before I open a Trac ticket that proposes adding a `WP_Terms_List_Table::extra_tablenav()` method and `restrict_manage_terms` filter so that it would be possible to do what I want to do, I wanted to see if anyone here on WPSE knows: 1. is there a viable work around (that doesn't involve something like hijacking `edit-tags.php?taxonomy=my_custom_tax` to redirect to a custom page that uses a custom subclass of `WP_Terms_List_Table`)? 2. is there a (good) reason `WP_Terms_List_Table` doesn't currently support this functionality? 1. I realize for core there is no (good) reason to filter by any of the standard `WP_Term_List_Table` columns, but adding custom columns to it is fairly common and I can't believe I'm the only one who's ever wanted to filter by the values in custom columns. **Edit** I should note that I when displaying the `meta_value` in the custom column, I am outputting it as a link which effectively filters the term list by that value. The the reason the UX would be enchanced if users could choose from a dropdown (like in `WP_Posts_List_Table`) is that not all values of the `meta_value` are always visible on any given page of terms displayed in the list table. What **I** do to use the links to filter by a value that is not currently displayed on the current page is click on a random link, then edit the resulting URL in the browser's address field to have the `meta_value` **I** want to filter by. Not only is that a pain, but not all user's are savy enough to realize they can do this.
I've been searching around for the same answer to your question and running into the exact same issues, and really appreciate your thorough research. I'm definitely +1 here for proposing this addition! To attempt to answer 2) - I don't think there's a good reason to exclude it. I think WordPress's taxonomy terms are woefully lacking in features compared to the post and user entities (seeing as how term meta came much later, after post and user meta), and would like to see that change. To answer 1) - I don't know how much *better* this is than your solution, but the workaround I've come up with involves filtering the taxonomy list via the `get_terms_args` filter, and then manually inserting a select dropdown + filter button in client-side JS. Here's a sample of my setup (modified to not use my specific classes or constants), which is filtering by a certain term meta field: **PHP Logic** ``` // @see https://developer.wordpress.org/reference/hooks/get_terms_args/ add_filter( 'get_terms_args', 'taxonomy_filter', 10, 2 ); function taxonomy_filter( $args, $taxonomies ) { global $pagenow; if ( 'edit-tags.php' !== $pagenow || ! in_array( 'taxonomy-name', $taxonomies, true ) ) { return $args; } // Sort by most recently added terms, instead of alphabetically $args['orderby'] = 'term_id'; $args['order'] = 'desc'; // Filter by term meta $meta_key = ( isset( $_GET['meta_key'] ) ) ? sanitize_text_field( $_GET['meta_key'] ) : null; $meta_value = ( isset( $_GET['meta_value'] ) ) ? sanitize_text_field( $_GET['meta_value'] ) : null; if ( 'meta-filter' === $meta_key && $meta_value ) { $args['meta_key'] = $meta_key; $args['meta_value'] = $meta_value; } // Note: for more complex filtering, use the $args['meta_query'] array. return $args; } ``` At this point, you should be able to see this working simply by going to (e.g.) `yoursite.com/wp-admin/edit-tags.php?taxonomy=taxonomy-name&meta_key=meta-filter&meta_value=foobar`. **Client-side jQuery logic** (Make sure you include this file in `wp_enqueue_script()`, but only when `$pagenow === 'edit-tags.php'`). ``` /** * Param helpers */ // Get params in a JS object var params = {}; window.location.search.substr(1).split( '&' ).forEach(function(item) { params[ item.split( '=' )[0] ] = item.split( '=' )[1]; }); // Return param string based on the params object function setParams() { var string = '?'; for ( key in params ) { var value = params[ key ]; string += key + '=' + value + '&'; } return string.slice(0, -1); // Remove trailing & } /** * Add dropdown filters + functionality to term tables */ if ( 'taxonomy-name' === params.taxonomy ) { // Create the dropdown menu & HTML $( document.querySelector( '.tablenav .bulkactions' ) ).after( '\ <div class="alignleft actions"> \ <select id="js-filter-dropdown"> \ <option value="">Term Meta Filter</option> \ <option value="foo">Foo</option> \ <option value="bar">Bar</option> \ <option value="baz">Baz</option> \ </select> \ <button id="js-filter" class="button" type="button">Filter</button> \ </div> \ ' ); // If we're already filtering the view, have the dropdown reflect that var value = decodeURIComponent( params.meta_value ).replace(/\+/g, ' '); $( '#js-filter-dropdown' ).find( 'option[value="' + value + '"]' ).prop( 'selected', true ); // Set up the button action - see taxonomy_filter() for server-side filtering $( '#js-filter' ).click(function() { var value = $( '#js-filter-dropdown' ).val(); if ( value ) { params.meta_key = 'meta-filter'; params.meta_value = encodeURIComponent( value ); } else { delete params.meta_key; delete params.meta_value; } window.location.search = setParams(); }); } ``` **Screenshot of the Filtering UI** [![Before](https://i.stack.imgur.com/34v2k.png)](https://i.stack.imgur.com/34v2k.png) **Screenshot of the filtered table** [![After image](https://i.stack.imgur.com/p2FW5.png)](https://i.stack.imgur.com/p2FW5.png)
268,513
<p>I'm using the theme customizer where I'm trying to find a way to check two settings. Here's my code and an explanation what it does:</p> <pre><code>// start a setting called 'twsa_show_active_days' $wp_customize-&gt;add_setting( 'twsa_show_active_days' ); // add options to the setting, in this case a radio to select three options $wp_customize-&gt;add_control( 'twsa_show_active_days', array( 'description' =&gt; 'Weekdays and/or weekends?', 'type' =&gt; 'radio', 'section' =&gt; 'twsa_show', 'choices' =&gt; array( 'weekdays' =&gt; 'Weekdays', 'plus_sat' =&gt; 'Weekdays plus Saturday', 'full_week' =&gt; 'Weekdays plus Saturday &amp; Sunday'), // active callback to check if 'active' is selected in another setting 'active_callback' =&gt; function() use ( $wp_customize ) { return 'active' === $wp_customize-&gt;get_setting( 'twsa_show_schedule' )-&gt;value(); }, // another active_callback to check if 'twsa_show_active' is selected in another setting 'active_callback' =&gt; function() use ( $wp_customize ) { return 'daily' === $wp_customize-&gt;get_setting( 'twsa_show_active' )-&gt;value(); }) ); </code></pre> <p>My question is, how do you use <code>active_callback</code> to check two settings? It works on one setting but I need it to check two settings. Do I need to create a function?</p>
[ { "answer_id": 268516, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>In general, there should not be any limitation on what is being checked in <code>active_callback</code> o...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I'm using the theme customizer where I'm trying to find a way to check two settings. Here's my code and an explanation what it does: ``` // start a setting called 'twsa_show_active_days' $wp_customize->add_setting( 'twsa_show_active_days' ); // add options to the setting, in this case a radio to select three options $wp_customize->add_control( 'twsa_show_active_days', array( 'description' => 'Weekdays and/or weekends?', 'type' => 'radio', 'section' => 'twsa_show', 'choices' => array( 'weekdays' => 'Weekdays', 'plus_sat' => 'Weekdays plus Saturday', 'full_week' => 'Weekdays plus Saturday & Sunday'), // active callback to check if 'active' is selected in another setting 'active_callback' => function() use ( $wp_customize ) { return 'active' === $wp_customize->get_setting( 'twsa_show_schedule' )->value(); }, // another active_callback to check if 'twsa_show_active' is selected in another setting 'active_callback' => function() use ( $wp_customize ) { return 'daily' === $wp_customize->get_setting( 'twsa_show_active' )->value(); }) ); ``` My question is, how do you use `active_callback` to check two settings? It works on one setting but I need it to check two settings. Do I need to create a function?
Maybe I'm misreading your question, but combining these two conditions in one anonymous function doesn't look that difficult: ``` 'active_callback' => function() use ( $wp_customize ) { $condition1 == $wp_customize->get_setting( 'twsa_show_schedule' )->value(); $condition2 == $wp_customize->get_setting( 'twsa_show_active' )->value(); return ($condition1 && $condition2); } ``` For really smart thinking on active callbacks, [read Otto's take on them](http://ottopress.com/2015/whats-new-with-the-customizer/).
268,531
<p>I realise this may be a generic php question, but as it's related to WP I'm including it here.</p> <p>If adding a simple conditional to my page.php template, do I need to include an 'else' (for other pages) and 'endif'?</p> <pre><code>&lt;?php if (is_tree(39)) : get_template_part('templates/partial/menu-buy'); elseif (is_tree(117)) : get_template_part('templates/partial/menu-programs'); ?&gt; </code></pre> <p>Other than an 'empty condition' (don't know if that's the right word) I can't see a way to include an 'else' for other pages.</p> <p>My limited knowledge suggests it's probably good practice to finish with 'endif', but I've seen conditionals written with/without an 'endif' and hence wonder whether it's necessary.</p> <p>UPDATE: Thanks to those who've answered, I now realise there's two different forms of syntax: <a href="http://php.net/manual/en/control-structures.alternative-syntax.php" rel="nofollow noreferrer">http://php.net/manual/en/control-structures.alternative-syntax.php</a> PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.</p>
[ { "answer_id": 268533, "author": "Steve", "author_id": 120700, "author_profile": "https://wordpress.stackexchange.com/users/120700", "pm_score": 4, "selected": true, "text": "<p>You just need an else block:</p>\n\n<pre><code>//templating syntax\nif($condOne):\n //do stuff if $condOne ...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103213/" ]
I realise this may be a generic php question, but as it's related to WP I'm including it here. If adding a simple conditional to my page.php template, do I need to include an 'else' (for other pages) and 'endif'? ``` <?php if (is_tree(39)) : get_template_part('templates/partial/menu-buy'); elseif (is_tree(117)) : get_template_part('templates/partial/menu-programs'); ?> ``` Other than an 'empty condition' (don't know if that's the right word) I can't see a way to include an 'else' for other pages. My limited knowledge suggests it's probably good practice to finish with 'endif', but I've seen conditionals written with/without an 'endif' and hence wonder whether it's necessary. UPDATE: Thanks to those who've answered, I now realise there's two different forms of syntax: <http://php.net/manual/en/control-structures.alternative-syntax.php> PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
You just need an else block: ``` //templating syntax if($condOne): //do stuff if $condOne is true elseif($condTwo): //do stuff if $condOne is false and $condTwo is true else: //do stuff if both $condOne and $condTwo are false endif; //braces syntax if($condOne){ //do stuff if $condOne is true }elseif($condTwo){ //do stuff if $condOne is false and $condTwo is true else{ //do stuff if both $condOne and $condTwo are false } ``` Regarding "it's probably good practice to finish with 'endif'", `endif` is only used when you are using the templating syntax: ``` if(): //do stuff endif; ``` the alternative is regular braces syntax: ``` if(){ //do stuff } ``` The former is preferable when you are outputting html by dropping out of php with a closing php tag, because an `endif` is easier to match up than a closing brace: ``` <?php if($someCondition):?> <h1>Hello <?=$userName?>, how are you today?</h1> <ul> <?php foreach($someArray as $key => $value):?> <li><?=$key?> : <?=$value?></li> <?php endforeach;?> </ul> <?php endif;?> ``` VS: ``` <?php if($someCondition){?> <h1>Hello <?=$userName?>, how are you today?</h1> <ul> <?php foreach($someArray as $key => $value){?> <li><?=$key?> : <?=$value?></li> <?php }?> </ul> <?php }?> ``` However when writting code that does not drop out of php mode, the latter is far more common and arguable easier to read: ``` $out=[]; if($someCondition){ $out[$username]=[]; foreach($someArray as $key => $value){ $out[$username][] = $key . ' : ' . $value; } } ```
268,535
<p>How i can create custom post method url in wordpress? For Example i will send data by ajax to urls: </p> <p><a href="http://example.com/?call_option=option1" rel="nofollow noreferrer">http://example.com/?call_option=option1</a> or <a href="http://example.com/?call_option=option2" rel="nofollow noreferrer">http://example.com/?call_option=option2</a></p> <p>And this will execute my code in function.php (in theme folder) </p> <pre><code>$option = trim($_GET['call_option']); if(empty($option)) { header("Location: ./404"); die(); } else { if ( $option == 'option1' ) { // do something } else if ( $option == 'option2' ) { // do something } } </code></pre> <p>Ho do this?</p>
[ { "answer_id": 268540, "author": "Jiten Gaikwad", "author_id": 120716, "author_profile": "https://wordpress.stackexchange.com/users/120716", "pm_score": 3, "selected": true, "text": "<p>WordPress comes with built in support for using AJAX calls from within your plugins or themes function...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120726/" ]
How i can create custom post method url in wordpress? For Example i will send data by ajax to urls: <http://example.com/?call_option=option1> or <http://example.com/?call_option=option2> And this will execute my code in function.php (in theme folder) ``` $option = trim($_GET['call_option']); if(empty($option)) { header("Location: ./404"); die(); } else { if ( $option == 'option1' ) { // do something } else if ( $option == 'option2' ) { // do something } } ``` Ho do this?
WordPress comes with built in support for using AJAX calls from within your plugins or themes functions.php. Following is the sample example: Javascript code: ``` jQuery( document ).on( 'click', '.event-trigger', function() { var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>"; //You can define this parameter globally as well. jQuery.ajax({ url : ajax_url, type : 'post', data : { action : 'youraction', param1: param1, param2: param2 }, success : function( response ) { alert(response) } }); }) ``` Write the following code in plugin file or functions.php file in your theme: ``` add_action( 'wp_ajax_nopriv_youraction', 'your_functionname' ); //This action calls for non-authenticated users as well add_action( 'wp_ajax_post_youraction', 'your_functionname' ); //This action calls only for authenticated user function your_functionname() { //your code goes here } ``` Refer [Ajax Example](https://premium.wpmudev.org/blog/using-ajax-with-wordpress/) for more details.
268,560
<p>I'm desperately trying to make an advanced searchform in order to get posts by their meta fields. I got this: </p> <p>[UPDATE]: This is the correct code:</p> <pre><code>/** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'cabins'; $vars[] = 'base'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); &lt;?php /** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'people'; $vars[] = 'base'; $vars[] = 'duration'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); /** * Build a custom query based on several conditions * The pre_get_posts action gives developers access to the $query object by reference * any changes you make to $query are made directly to the original object - no return value is requested * */ function sy_pre_get_posts( $query ){ if( is_admin() || ! $query-&gt;is_main_query() ){ return; } $query-&gt;set( 'type', get_query_var( 'type' ) ); $query-&gt;set( 'people', get_query_var( 'people' ) ); $query-&gt;set( 'base', get_query_var( 'base' ) ); $query-&gt;set( 'duration', get_query_var( 'duration' ) ); if( !is_post_type_archive( 'fleet' ) ){ return; } $meta_query = array(); if( !empty( get_query_var( 'type' ) ) ) { $meta_query[] = array( 'key' =&gt; 'type', 'value' =&gt; get_query_var( 'type' ), 'compare' =&gt; 'LIKE' ); } elseif ( !empty( get_query_var( 'people' ) ) ){ $meta_query[] = array( 'key' =&gt; 'people', 'value' =&gt; get_query_var( 'people' ), 'compare' =&gt; 'LIKE' ); } elseif ( !empty( get_query_var( 'base' ) ) ){ $meta_query[] = array( 'key' =&gt; 'base', 'value' =&gt; get_query_var( 'base' ), 'compare' =&gt; 'LIKE' ); } elseif ( !empty( get_query_var( 'duration' ) ) ){ $meta_query[] = array( 'key' =&gt; 'duration', 'value' =&gt; get_query_var( 'duration' ), 'compare' =&gt; 'LIKE' ); } if( count( $meta_query ) &gt; 1 ){ $meta_query['relation'] = 'AND'; } if( count( $meta_query ) &gt; 0 ){ $query-&gt;set( 'meta_query', array($meta_query) ); } } add_action( 'pre_get_posts', 'sy_pre_get_posts', 1 ); function sy_search_form(){ $select_type = '&lt;select name="type" style="width: 100%"&gt;'; $select_type .= '&lt;option value="" selected="selected"&gt;' . __( 'Type', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Motor"&gt;' . __( 'Motor', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Sailing"&gt;' . __( 'Sailing', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Ribs"&gt;' . __( 'Ribs', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Caiques"&gt;' . __( 'Caiques', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;option value="Speed Boats"&gt;' . __( 'Spead Boats', 'syacht' ) . '&lt;/option&gt;'; $select_type .= '&lt;/select&gt;' . "\n"; $select_people = '&lt;select name="people" style="width: 100%"&gt;'; $select_people .= '&lt;option value="" selected="selected"&gt;' . __( 'People', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;option value="3 or less"&gt;' . __( '3 or less', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;option value="4-6"&gt;' . __( '4-6', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;option value="6 or more"&gt;' . __( '6 or more', 'syacht' ) . '&lt;/option&gt;'; $select_people .= '&lt;/select&gt;' . "\n"; $select_base = '&lt;select name="base" style="width: 100%"&gt;'; $select_base .= '&lt;option value="" selected="selected"&gt;' . __( 'Base', 'syacht' ) . '&lt;/option&gt;'; $select_base .= '&lt;option value="Mykonos"&gt;' . __( 'Mykonos', 'syacht' ) . '&lt;/option&gt;'; $select_base .= '&lt;option value="Old Port"&gt;' . __( 'Old Port', 'syacht' ) . '&lt;/option&gt;'; $select_base .= '&lt;/select&gt;' . "\n"; $select_duration = '&lt;select name="duration" style="width: 100%"&gt;'; $select_duration .= '&lt;option value="" selected="selected"&gt;' . __( 'Duration', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;option value="1 to 3 days"&gt;' . __( '1 to 3 days', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;option value="1 week"&gt;' . __( '1 week', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;option value="2 weeks"&gt;' . __( '2 weeks', 'syacht' ) . '&lt;/option&gt;'; $select_duration .= '&lt;/select&gt;' . "\n"; $output = '&lt;form class="advanced-search" action="' . esc_url( home_url() ) . '" method="get" role="search"&gt;'; $output .= '&lt;div class="wrap"&gt;'; $output .= '&lt;div&gt;'. $select_type . '&lt;/div&gt;'; $output .= '&lt;div&gt;'. $select_people . '&lt;/div&gt;'; $output .= '&lt;div&gt;'. $select_base . '&lt;/div&gt;'; $output .= '&lt;div&gt;'. $select_duration . '&lt;/div&gt;'; $output .= '&lt;input type="hidden" name="post_type" value="fleet" /&gt;'; $output .= '&lt;div&gt;&lt;input type="submit" id="as-submit" class="button gold full" value="Search yachts" /&gt;&lt;/div&gt;'; $output .= '&lt;a href="javascript:void(0)" class="search-hide" title="Hide this box"&gt;Hide this box&lt;/a&gt;'; $output .= '&lt;/div&gt;&lt;/form&gt;'; return $output; } </code></pre> <p>Actually this form works, but not at all. In fact, the search page shows all posts belonging to "fleet" custom post type and they are not filtered by the search terms I set. Why this? Where is the error? Please it's been days since I've started trying to solve this. Thanks all.</p> <p>P.s.: Please, do not suggest any plugin. I've tried already many, and none of them worked. </p>
[ { "answer_id": 268540, "author": "Jiten Gaikwad", "author_id": 120716, "author_profile": "https://wordpress.stackexchange.com/users/120716", "pm_score": 3, "selected": true, "text": "<p>WordPress comes with built in support for using AJAX calls from within your plugins or themes function...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268560", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120682/" ]
I'm desperately trying to make an advanced searchform in order to get posts by their meta fields. I got this: [UPDATE]: This is the correct code: ``` /** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'cabins'; $vars[] = 'base'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); <?php /** *Registering custom query vars * */ function sy_register_query_var( $vars ){ $vars[] = 'type'; $vars[] = 'people'; $vars[] = 'base'; $vars[] = 'duration'; return $vars; } add_filter( 'query_vars', 'sy_register_query_var' ); /** * Build a custom query based on several conditions * The pre_get_posts action gives developers access to the $query object by reference * any changes you make to $query are made directly to the original object - no return value is requested * */ function sy_pre_get_posts( $query ){ if( is_admin() || ! $query->is_main_query() ){ return; } $query->set( 'type', get_query_var( 'type' ) ); $query->set( 'people', get_query_var( 'people' ) ); $query->set( 'base', get_query_var( 'base' ) ); $query->set( 'duration', get_query_var( 'duration' ) ); if( !is_post_type_archive( 'fleet' ) ){ return; } $meta_query = array(); if( !empty( get_query_var( 'type' ) ) ) { $meta_query[] = array( 'key' => 'type', 'value' => get_query_var( 'type' ), 'compare' => 'LIKE' ); } elseif ( !empty( get_query_var( 'people' ) ) ){ $meta_query[] = array( 'key' => 'people', 'value' => get_query_var( 'people' ), 'compare' => 'LIKE' ); } elseif ( !empty( get_query_var( 'base' ) ) ){ $meta_query[] = array( 'key' => 'base', 'value' => get_query_var( 'base' ), 'compare' => 'LIKE' ); } elseif ( !empty( get_query_var( 'duration' ) ) ){ $meta_query[] = array( 'key' => 'duration', 'value' => get_query_var( 'duration' ), 'compare' => 'LIKE' ); } if( count( $meta_query ) > 1 ){ $meta_query['relation'] = 'AND'; } if( count( $meta_query ) > 0 ){ $query->set( 'meta_query', array($meta_query) ); } } add_action( 'pre_get_posts', 'sy_pre_get_posts', 1 ); function sy_search_form(){ $select_type = '<select name="type" style="width: 100%">'; $select_type .= '<option value="" selected="selected">' . __( 'Type', 'syacht' ) . '</option>'; $select_type .= '<option value="Motor">' . __( 'Motor', 'syacht' ) . '</option>'; $select_type .= '<option value="Sailing">' . __( 'Sailing', 'syacht' ) . '</option>'; $select_type .= '<option value="Ribs">' . __( 'Ribs', 'syacht' ) . '</option>'; $select_type .= '<option value="Caiques">' . __( 'Caiques', 'syacht' ) . '</option>'; $select_type .= '<option value="Speed Boats">' . __( 'Spead Boats', 'syacht' ) . '</option>'; $select_type .= '</select>' . "\n"; $select_people = '<select name="people" style="width: 100%">'; $select_people .= '<option value="" selected="selected">' . __( 'People', 'syacht' ) . '</option>'; $select_people .= '<option value="3 or less">' . __( '3 or less', 'syacht' ) . '</option>'; $select_people .= '<option value="4-6">' . __( '4-6', 'syacht' ) . '</option>'; $select_people .= '<option value="6 or more">' . __( '6 or more', 'syacht' ) . '</option>'; $select_people .= '</select>' . "\n"; $select_base = '<select name="base" style="width: 100%">'; $select_base .= '<option value="" selected="selected">' . __( 'Base', 'syacht' ) . '</option>'; $select_base .= '<option value="Mykonos">' . __( 'Mykonos', 'syacht' ) . '</option>'; $select_base .= '<option value="Old Port">' . __( 'Old Port', 'syacht' ) . '</option>'; $select_base .= '</select>' . "\n"; $select_duration = '<select name="duration" style="width: 100%">'; $select_duration .= '<option value="" selected="selected">' . __( 'Duration', 'syacht' ) . '</option>'; $select_duration .= '<option value="1 to 3 days">' . __( '1 to 3 days', 'syacht' ) . '</option>'; $select_duration .= '<option value="1 week">' . __( '1 week', 'syacht' ) . '</option>'; $select_duration .= '<option value="2 weeks">' . __( '2 weeks', 'syacht' ) . '</option>'; $select_duration .= '</select>' . "\n"; $output = '<form class="advanced-search" action="' . esc_url( home_url() ) . '" method="get" role="search">'; $output .= '<div class="wrap">'; $output .= '<div>'. $select_type . '</div>'; $output .= '<div>'. $select_people . '</div>'; $output .= '<div>'. $select_base . '</div>'; $output .= '<div>'. $select_duration . '</div>'; $output .= '<input type="hidden" name="post_type" value="fleet" />'; $output .= '<div><input type="submit" id="as-submit" class="button gold full" value="Search yachts" /></div>'; $output .= '<a href="javascript:void(0)" class="search-hide" title="Hide this box">Hide this box</a>'; $output .= '</div></form>'; return $output; } ``` Actually this form works, but not at all. In fact, the search page shows all posts belonging to "fleet" custom post type and they are not filtered by the search terms I set. Why this? Where is the error? Please it's been days since I've started trying to solve this. Thanks all. P.s.: Please, do not suggest any plugin. I've tried already many, and none of them worked.
WordPress comes with built in support for using AJAX calls from within your plugins or themes functions.php. Following is the sample example: Javascript code: ``` jQuery( document ).on( 'click', '.event-trigger', function() { var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>"; //You can define this parameter globally as well. jQuery.ajax({ url : ajax_url, type : 'post', data : { action : 'youraction', param1: param1, param2: param2 }, success : function( response ) { alert(response) } }); }) ``` Write the following code in plugin file or functions.php file in your theme: ``` add_action( 'wp_ajax_nopriv_youraction', 'your_functionname' ); //This action calls for non-authenticated users as well add_action( 'wp_ajax_post_youraction', 'your_functionname' ); //This action calls only for authenticated user function your_functionname() { //your code goes here } ``` Refer [Ajax Example](https://premium.wpmudev.org/blog/using-ajax-with-wordpress/) for more details.
268,563
<p>I was able to echo out all terms belonging to a custom taxonomy using the code below:</p> <pre><code>$args = array('post_type' =&gt; 'my_post_type','number' =&gt; '999'); $terms = get_terms( 'my_taxo', [ 'hide_empty' =&gt; true, 'orderby' =&gt; 'wpse_last_word', ] , $args ); foreach ( $terms as $term ) { echo '' . $term-&gt;name . ''; } </code></pre> <p>This code provides the results I want on my localhost (xampp). Basically, it outputs all of the terms assigned to a particular post. But when I upload the code to a live server, the code no longer works as expected. Instead, it shows all the terms without filtering them. I even updates the PHP version on my live server match to the local server; still no luck.</p> <p>Can anyone point out the issue on my code.</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are call...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97402/" ]
I was able to echo out all terms belonging to a custom taxonomy using the code below: ``` $args = array('post_type' => 'my_post_type','number' => '999'); $terms = get_terms( 'my_taxo', [ 'hide_empty' => true, 'orderby' => 'wpse_last_word', ] , $args ); foreach ( $terms as $term ) { echo '' . $term->name . ''; } ``` This code provides the results I want on my localhost (xampp). Basically, it outputs all of the terms assigned to a particular post. But when I upload the code to a live server, the code no longer works as expected. Instead, it shows all the terms without filtering them. I even updates the PHP version on my live server match to the local server; still no luck. Can anyone point out the issue on my code.
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,591
<h1>Background</h1> <p>I am trying to add page templates from inside of a plugin. For this question, I have trimmed my code down into a test plugin which has two files, the PHP main plugin file, and a PHP template file.</p> <p>wp-plugins/test-plugin/test-plugin.php</p> <p>wp-plugins/test-plugin/templates/test-template.php</p> <p>The plugin has two pieces. First off, I tap into the <code>template_include</code> filter, and I return the path to the template file (test-template.php).</p> <p>Next, I have a new extension of <code>Walker_Page</code>, called <code>Walker_Page_New</code> in this example. In the file, it is a word for word copy of <code>Walker_Page</code>.</p> <h1>Current Code</h1> <p><strong>test-plugin.php</strong></p> <pre><code>&lt;?php /** * Plugin Name: Test Plugin * Version: 1.0 * Author: Andy Mercer * Author URI: http://www.andymercer.net * License: GPL2 */ add_filter( 'template_include', 'test_get_template' ); function test_get_template( $template ) { $template_path = plugin_dir_path( __FILE__ ) . 'templates/test-template.php'; if ( file_exists( $template_path ) ) { $template = $template_path; } return $template; } class Walker_Page_New extends Walker_Page { // THE CODE IN HERE IS AN EXACT COPY OF WALKER_PAGE // I AM NOT ENTERING IT ALL IN THIS QUESTION BECAUSE IT'S A COUPLE HUNDRED LINES OF CODE } </code></pre> <p><strong>test-template.php</strong></p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en"&gt; &lt;head&gt; ...head stuff... &lt;/head&gt; &lt;body&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div&gt; &lt;?php $ancestors = get_ancestors( get_the_ID(), 'page' ); wp_list_pages([ 'title_li' =&gt; '', 'sort_column' =&gt; 'menu_order', 'child_of' =&gt; $ancestors[0], 'depth' =&gt; 2, 'walker' =&gt; 'Walker_Page_New', ]); ?&gt; &lt;/div&gt; &lt;div&gt; &lt;?php the_title(); ?&gt; &lt;?php the_content() ?&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h1>Problem</h1> <p>When I then load the page, I only get this error:</p> <blockquote> <p>Fatal error: Uncaught Error: Using $this when not in object context in C:...\wp-includes\class-wp-walker.php:199</p> </blockquote> <p>What is triggering this error is the call to <code>wp_list_pages()</code> with a custom Walker. When I remove the Walker, I am fine and everything works as expected.</p> <h1>Research</h1> <p>From looking around, the only specific mention of this I have found is semi-related here: <a href="https://github.com/Automattic/amp-wp/issues/412#issuecomment-240871878" rel="nofollow noreferrer">https://github.com/Automattic/amp-wp/issues/412#issuecomment-240871878</a>, where it's stated that using <code>template_include</code> will cause this:</p> <blockquote> <p>e.g. we would no longer have the $this context in the templates</p> </blockquote> <h1>Question</h1> <p>Is it expected that using <code>template_include</code> will break stuff? Should I use <code>template_redirect</code> instead?</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are call...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268591", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47789/" ]
Background ========== I am trying to add page templates from inside of a plugin. For this question, I have trimmed my code down into a test plugin which has two files, the PHP main plugin file, and a PHP template file. wp-plugins/test-plugin/test-plugin.php wp-plugins/test-plugin/templates/test-template.php The plugin has two pieces. First off, I tap into the `template_include` filter, and I return the path to the template file (test-template.php). Next, I have a new extension of `Walker_Page`, called `Walker_Page_New` in this example. In the file, it is a word for word copy of `Walker_Page`. Current Code ============ **test-plugin.php** ``` <?php /** * Plugin Name: Test Plugin * Version: 1.0 * Author: Andy Mercer * Author URI: http://www.andymercer.net * License: GPL2 */ add_filter( 'template_include', 'test_get_template' ); function test_get_template( $template ) { $template_path = plugin_dir_path( __FILE__ ) . 'templates/test-template.php'; if ( file_exists( $template_path ) ) { $template = $template_path; } return $template; } class Walker_Page_New extends Walker_Page { // THE CODE IN HERE IS AN EXACT COPY OF WALKER_PAGE // I AM NOT ENTERING IT ALL IN THIS QUESTION BECAUSE IT'S A COUPLE HUNDRED LINES OF CODE } ``` **test-template.php** ``` <!DOCTYPE HTML> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> ...head stuff... </head> <body> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div> <?php $ancestors = get_ancestors( get_the_ID(), 'page' ); wp_list_pages([ 'title_li' => '', 'sort_column' => 'menu_order', 'child_of' => $ancestors[0], 'depth' => 2, 'walker' => 'Walker_Page_New', ]); ?> </div> <div> <?php the_title(); ?> <?php the_content() ?> </div> <?php endwhile; endif; ?> <?php wp_footer(); ?> </body> </html> ``` Problem ======= When I then load the page, I only get this error: > > Fatal error: Uncaught Error: Using $this when not in object context in C:...\wp-includes\class-wp-walker.php:199 > > > What is triggering this error is the call to `wp_list_pages()` with a custom Walker. When I remove the Walker, I am fine and everything works as expected. Research ======== From looking around, the only specific mention of this I have found is semi-related here: <https://github.com/Automattic/amp-wp/issues/412#issuecomment-240871878>, where it's stated that using `template_include` will cause this: > > e.g. we would no longer have the $this context in the templates > > > Question ======== Is it expected that using `template_include` will break stuff? Should I use `template_redirect` instead?
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,607
<p>I've got a page where I only want to display one post per page with pagination at the bottom to go to the next/ previous post. This is my code:</p> <pre><code> &lt;?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1'; $args = array ( 'nopaging' =&gt; false, 'paged' =&gt; $paged, 'posts_per_page' =&gt; '1', 'post_type' =&gt; 'post', 'category_name' =&gt; 'enforcement', ); ?&gt; &lt;?php $wp_query = new WP_Query($args); ?&gt; &lt;?php if ( $wp_query-&gt;have_posts() ) : ?&gt; &lt;?php while ( $wp_query-&gt;have_posts() ) : the_post(); ?&gt; &lt;!--&lt;div class="case-studies-text-banner"&gt; &lt;img src="http://www.mariadev.co.uk/wp-content/uploads/2017/05/case-study-layer.png"/&gt; &lt;div class="case-study-title"&gt;&lt;?php the_title(); ?&gt;&lt;/div&gt; &lt;div class="case-study-pdf"&gt;&lt;?php if (function_exists("wpptopdfenh_display_icon")) echo wpptopdfenh_display_icon();?&gt;&lt;/div&gt; &lt;/div&gt;--&gt; &lt;?php the_content(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php next_posts_link( 'Older Entries »', $query-&gt;max_num_pages ); ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php __('No News'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre> <p>It does only show 1 post on the first page but when clicking on older posts and moving to this url <code>www.testing./?cat=8&amp;paged=2</code> no posts show even though there are 3 posts in this category. Any ideas what I'm doing wrong?</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are call...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268607", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120767/" ]
I've got a page where I only want to display one post per page with pagination at the bottom to go to the next/ previous post. This is my code: ``` <?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1'; $args = array ( 'nopaging' => false, 'paged' => $paged, 'posts_per_page' => '1', 'post_type' => 'post', 'category_name' => 'enforcement', ); ?> <?php $wp_query = new WP_Query($args); ?> <?php if ( $wp_query->have_posts() ) : ?> <?php while ( $wp_query->have_posts() ) : the_post(); ?> <!--<div class="case-studies-text-banner"> <img src="http://www.mariadev.co.uk/wp-content/uploads/2017/05/case-study-layer.png"/> <div class="case-study-title"><?php the_title(); ?></div> <div class="case-study-pdf"><?php if (function_exists("wpptopdfenh_display_icon")) echo wpptopdfenh_display_icon();?></div> </div>--> <?php the_content(); ?> <?php endwhile; ?> <?php next_posts_link( 'Older Entries »', $query->max_num_pages ); ?> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php __('No News'); ?></p> <?php endif; ?> ``` It does only show 1 post on the first page but when clicking on older posts and moving to this url `www.testing./?cat=8&paged=2` no posts show even though there are 3 posts in this category. Any ideas what I'm doing wrong?
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,609
<p>We use Open Live Writer to upload to our Wordpress Blog on GoDaddy. It takes us numerous times to upload the draft with pictures to the Blog as we get the error message of lost connection. I have noticed in the Media file that the pictures are uploading in stages. That is, after I get the connection error message I check the Media file and more pictures have uploaded. Finally the Draft shows up in the Post file and all pictures are there. Sometimes I need to change the hotpot I am using as it also seems to get stuck. </p> <p>Other than a smaller Blog posting what can we due to limit these disconnections?</p>
[ { "answer_id": 268569, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 3, "selected": true, "text": "<p>Your code is wrong. I don't know how it is working in your localhost. Cause- </p>\n\n<ol>\n<li>You are call...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268609", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120768/" ]
We use Open Live Writer to upload to our Wordpress Blog on GoDaddy. It takes us numerous times to upload the draft with pictures to the Blog as we get the error message of lost connection. I have noticed in the Media file that the pictures are uploading in stages. That is, after I get the connection error message I check the Media file and more pictures have uploaded. Finally the Draft shows up in the Post file and all pictures are there. Sometimes I need to change the hotpot I am using as it also seems to get stuck. Other than a smaller Blog posting what can we due to limit these disconnections?
Your code is wrong. I don't know how it is working in your localhost. Cause- 1. You are calling `get_terms()` with 3 parameters which actually accepts 2 parameters. The last one is extra. 2. And secondly `get_terms()` returns all the terms of a taxonomy, not the terms associated with a post. For getting the terms associated for a post you can use [`wp_get_post_terms`](https://codex.wordpress.org/Function_Reference/wp_get_post_terms). **Usage of `wp_get_post_terms` inside *WordPress* loop-** For each post you'll get the post's terms by calling `wp_get_post_terms` like below- ``` //Do something if a specific array value exists within a post $term_list = wp_get_post_terms($post->ID, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` And for outside of the loop- ``` // Do something if a specific array value exists within a post // And somehow you need to get the post ID to pas it to below. $term_list = wp_get_post_terms($post_id, 'your_taxonomy', array("fields" => "all")); // Then you can run a foreach loop to show the taxonomy terms infront. foreach($term_list as $term_single) { echo $term_single->slug; //do something here } ``` Hope that helps.
268,615
<p>How can I prevent Headers from being sent?</p> <p>I am trying to list (WordPress) blog posts on a non-WordPress site (both sites share a public web folder). </p> <p>I want to run the following PHP code to get the blog posts:</p> <pre><code> &lt;ul class='list-unstyled'&gt; &lt;?php define('WP_USE_THEMES', false); require($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php'); query_posts('showposts=5'); while (have_posts()): the_post(); ?&gt; &lt;li&gt;&lt;i class='glyphicon glyphicon-menu-right'&gt;&lt;/i&gt; &lt;h4&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" class="myred text-main"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt; &lt;p&gt;&lt;?php the_date(); ?&gt; | Category: &lt;?php the_category(','); ?&gt; | &lt;?php the_tags(); ?&gt;&lt;/p&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; </code></pre> <p>However, it seems running this code sends payload headers to client. Is there any way to retrieve the blog posts without sending headers?</p>
[ { "answer_id": 268617, "author": "DaveLak", "author_id": 119673, "author_profile": "https://wordpress.stackexchange.com/users/119673", "pm_score": 0, "selected": false, "text": "<p>Output of the page started as your php is executing. Look into into <a href=\"http://php.net/manual/en/book...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268615", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120771/" ]
How can I prevent Headers from being sent? I am trying to list (WordPress) blog posts on a non-WordPress site (both sites share a public web folder). I want to run the following PHP code to get the blog posts: ``` <ul class='list-unstyled'> <?php define('WP_USE_THEMES', false); require($_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php'); query_posts('showposts=5'); while (have_posts()): the_post(); ?> <li><i class='glyphicon glyphicon-menu-right'></i> <h4><a href="<?php the_permalink(); ?>" class="myred text-main"><?php the_title(); ?></a></h4> <p><?php the_date(); ?> | Category: <?php the_category(','); ?> | <?php the_tags(); ?></p> </li> <?php endwhile; ?> </ul> ``` However, it seems running this code sends payload headers to client. Is there any way to retrieve the blog posts without sending headers?
"Headers already sent" is not a WordPress error, it is PHP processing error message. Good explanation here; <https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php> . I suspect it might be caused by some characters (probably space characters) sent before your `<?php` code segment. Even space (or tab [code formatting] ) characters will cause an error. And perhaps move your `<ul>` code to just above the `while` loop.
268,630
<p>I'm working on a function where I just want to output a button that links to a specific term. I have used <code>get_the_terms</code> and have gotten it to work successfully, but I've been trying <code>get_term</code> and I've have no luck. I want the shortcode to look like this <code>[see_all_products category="bakery"]</code> and output a button that links to it.</p> <p>This is my function so far:</p> <pre><code>function product_category_button($atts) { extract(shortcode_atts(array( 'category' =&gt; '', ), $atts)); // if( $category ) : // Vars $taxonomy = 'product_categories'; $term = get_term( $category, $taxonomy ); //$post-&gt;ID $cat = $term-&gt;name; $parent = $term-&gt;parent; var_dump($cat); if ($parent == NULL) : // Vars $link = get_term_link( $term-&gt;slug, $taxonomy); $html_out = ''; $html_out .= '&lt;a class="x-btn x-btn-primary x-btn-global hvr-bounce-to-bottom" href="' . $link . '"&gt;' . 'See All Products' . $cat . '&lt;/a&gt;'; endif; return $html_out; // endif; } add_shortcode( 'see_all_products', 'product_category_button' ); </code></pre> <p>Right now, <code>$link</code> gives me this error "Catchable fatal error: Object of class WP_Error could not be converted to string" and <code>$cat</code> returns <code>NULL</code> in the <code>var_dump</code>.</p> <p>Not sure if this could be affecting it, but the <code>$parent</code> stuff here was meant to get only the parent term.</p>
[ { "answer_id": 268617, "author": "DaveLak", "author_id": 119673, "author_profile": "https://wordpress.stackexchange.com/users/119673", "pm_score": 0, "selected": false, "text": "<p>Output of the page started as your php is executing. Look into into <a href=\"http://php.net/manual/en/book...
2017/05/30
[ "https://wordpress.stackexchange.com/questions/268630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96257/" ]
I'm working on a function where I just want to output a button that links to a specific term. I have used `get_the_terms` and have gotten it to work successfully, but I've been trying `get_term` and I've have no luck. I want the shortcode to look like this `[see_all_products category="bakery"]` and output a button that links to it. This is my function so far: ``` function product_category_button($atts) { extract(shortcode_atts(array( 'category' => '', ), $atts)); // if( $category ) : // Vars $taxonomy = 'product_categories'; $term = get_term( $category, $taxonomy ); //$post->ID $cat = $term->name; $parent = $term->parent; var_dump($cat); if ($parent == NULL) : // Vars $link = get_term_link( $term->slug, $taxonomy); $html_out = ''; $html_out .= '<a class="x-btn x-btn-primary x-btn-global hvr-bounce-to-bottom" href="' . $link . '">' . 'See All Products' . $cat . '</a>'; endif; return $html_out; // endif; } add_shortcode( 'see_all_products', 'product_category_button' ); ``` Right now, `$link` gives me this error "Catchable fatal error: Object of class WP\_Error could not be converted to string" and `$cat` returns `NULL` in the `var_dump`. Not sure if this could be affecting it, but the `$parent` stuff here was meant to get only the parent term.
"Headers already sent" is not a WordPress error, it is PHP processing error message. Good explanation here; <https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php> . I suspect it might be caused by some characters (probably space characters) sent before your `<?php` code segment. Even space (or tab [code formatting] ) characters will cause an error. And perhaps move your `<ul>` code to just above the `while` loop.
268,653
<p>Media Library is not loading on grid view and also featured image not select any image from post and page . The progress circle keeps spinning. Due to this issue, I am not able to add any image in the post as insert image option also opens in “grid view” by default.</p> <p>The things I tried but not resolved my issue:</p> <ol> <li>Removed all plugins. Switch to twenty sixteen theme.</li> <li>Deleted whole wordpress installation. Installed fresh. </li> <li>Enabled script debug.Doesn’t show any error in console. Tried reloading the page too.</li> </ol> <p>I am not able to do anything on my website for many days now, please help me.</p>
[ { "answer_id": 268778, "author": "Pavnish Yadav", "author_id": 68882, "author_profile": "https://wordpress.stackexchange.com/users/68882", "pm_score": -1, "selected": false, "text": "<p>I faced same issue on my wordpress site. After the lot of debugging i fixed my problem step by step.</...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68882/" ]
Media Library is not loading on grid view and also featured image not select any image from post and page . The progress circle keeps spinning. Due to this issue, I am not able to add any image in the post as insert image option also opens in “grid view” by default. The things I tried but not resolved my issue: 1. Removed all plugins. Switch to twenty sixteen theme. 2. Deleted whole wordpress installation. Installed fresh. 3. Enabled script debug.Doesn’t show any error in console. Tried reloading the page too. I am not able to do anything on my website for many days now, please help me.
I ran into a similar issue with the same symptoms. What I determined was in my theme's function.php there was a DEBUG statement that output some html. While this was fine for browsing, when the POST request came into admin-ajax.php to refresh the thumbnails, it was causing the infinite spinning wheel and not showing images. I removed the output from functions.php and problem was resolved. Not sure if this will work for you, but I found the issue by using the following command: ``` curl -X POST http://YOUR_DOMAIN_NAME_HERE/wp-admin/admin-ajax.php -d 'action=query-attachments&post_id=0&query[orderby]=date&query[order]=DESC&query[post_per_page]=40&query[paged]=1' ```
268,669
<p>I have a custom post type containing job listings, that is highly volatile. Jobs are frequently added and removed. Our analytics show that a lot of crawling errors are for detail pages of jobs that have been unlisted.</p> <p>The solution I came up with is to redirect all visits for non-existant URLs within the CPT's slug to the job listing overview, and I would like to automate this.</p> <p>How would I go about this? I'm looking for a solution that does this very early and skips as much unnecessary calls as possible. (i.e. something earlier than doing this in header.php, ideally as an action)</p> <p>Example:</p> <ul> <li><code>mydomain.com/jobs/existingjob/</code> delivers the detail page for the job</li> <li><code>mydomain.com/jobs/nojobhere/</code> does not exist and would throw a 404 but instead gets redirected to <code>mydomain.com/jobs/</code></li> </ul>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really ...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268669", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120812/" ]
I have a custom post type containing job listings, that is highly volatile. Jobs are frequently added and removed. Our analytics show that a lot of crawling errors are for detail pages of jobs that have been unlisted. The solution I came up with is to redirect all visits for non-existant URLs within the CPT's slug to the job listing overview, and I would like to automate this. How would I go about this? I'm looking for a solution that does this very early and skips as much unnecessary calls as possible. (i.e. something earlier than doing this in header.php, ideally as an action) Example: * `mydomain.com/jobs/existingjob/` delivers the detail page for the job * `mydomain.com/jobs/nojobhere/` does not exist and would throw a 404 but instead gets redirected to `mydomain.com/jobs/`
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,696
<p>Using theme (and child theme) of Sailent, I'm trying to work out a way to completely remove a menu item from my navigation bar while on desktop. See site here: <a href="http://www.boinginflatables.com/2017update/" rel="nofollow noreferrer">http://www.boinginflatables.com/2017update/</a></p> <p><a href="https://i.stack.imgur.com/7eec2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7eec2.png" alt="It&#39;s there, although not visible"></a> As you can see, the text for the menu item isn't there, yet it messes up the alignment of the menu. </p> <p>At the moment, I have that menu item set to a css class of mobile-only with css settings as: </p> <pre><code>.mobile-only { visibility:hidden; } @media (min-width:992px) { .desktop-only { visibility:visible !important; } } @media (max-width: 991px) { .mobile-only { visibility:visible !important; } .desktop-only { visibility:hidden !important; } } </code></pre>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really ...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120829/" ]
Using theme (and child theme) of Sailent, I'm trying to work out a way to completely remove a menu item from my navigation bar while on desktop. See site here: <http://www.boinginflatables.com/2017update/> [![It's there, although not visible](https://i.stack.imgur.com/7eec2.png)](https://i.stack.imgur.com/7eec2.png) As you can see, the text for the menu item isn't there, yet it messes up the alignment of the menu. At the moment, I have that menu item set to a css class of mobile-only with css settings as: ``` .mobile-only { visibility:hidden; } @media (min-width:992px) { .desktop-only { visibility:visible !important; } } @media (max-width: 991px) { .mobile-only { visibility:visible !important; } .desktop-only { visibility:hidden !important; } } ```
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,700
<p>I need to get all post ids, post_titles and the according meta_value which is "featured" for a custom post_type. I think I need to do a join, but I don't know how they work.. Could anyone help me out on this? </p>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really ...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80443/" ]
I need to get all post ids, post\_titles and the according meta\_value which is "featured" for a custom post\_type. I think I need to do a join, but I don't know how they work.. Could anyone help me out on this?
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,732
<p>Is it possible to password protect a PDF for visitors to our website (not users)? We have uploaded a PDF to our media and created a link to it on a page, but we would like to password protect just that PDF and not the whole page that contains the link to it.</p>
[ { "answer_id": 268673, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>If there is no page on your site with that post type, you need to ask yourself the question:\nshould I really ...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120857/" ]
Is it possible to password protect a PDF for visitors to our website (not users)? We have uploaded a PDF to our media and created a link to it on a page, but we would like to password protect just that PDF and not the whole page that contains the link to it.
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: ``` add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } } ```
268,742
<p>I am using WordPress MU Domain Mapping which works fine, but when I try to these any theme's customizer, I get this error when trying to save:</p> <p><strong>Cheatin’ uh? Sorry, you are not allowed to customize this site.</strong></p> <p>When I deactivate the plugin, the customizer works. I have 'Remote Login' and ' Redirect administration pages...' unchecked in the options as well.</p>
[ { "answer_id": 268947, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 0, "selected": false, "text": "<p>Try mapping without a plugin then. Since WP 4.5 this is possible. Just point the domain to the server with ...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268742", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101588/" ]
I am using WordPress MU Domain Mapping which works fine, but when I try to these any theme's customizer, I get this error when trying to save: **Cheatin’ uh? Sorry, you are not allowed to customize this site.** When I deactivate the plugin, the customizer works. I have 'Remote Login' and ' Redirect administration pages...' unchecked in the options as well.
After much trial and error, I found the cause to be a conflict with the WP Super Cache plugin, I had to disable the following from my wp-config.php file: ``` define( 'WPCACHEHOME', '/var/www/html/wp-content/plugins/wp-super-cache/' ); //Added by WP-Cache Manager ```
268,750
<p>I want to link a external url as follows:</p> <pre><code>$url='www.example.com'; $output ='&lt;div class="button"&gt;&lt;a href="'.$url.'"&gt; View Profile&lt;/a&gt;&lt;/div&gt;'; </code></pre> <p>I run this wordpress web app at my localhost and base url is localhost/wordpress. When I echo <code>$output</code> it produce a link for view profile: <code>localhost/wordpress/www.example.com</code>. But it should be <code>www.facebook.com</code> </p> <p>What change shall i make?</p>
[ { "answer_id": 268752, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": 0, "selected": false, "text": "<p>You have a / thats not needed in the href this will add the link to the end of your current url hence localhost...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268750", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120824/" ]
I want to link a external url as follows: ``` $url='www.example.com'; $output ='<div class="button"><a href="'.$url.'"> View Profile</a></div>'; ``` I run this wordpress web app at my localhost and base url is localhost/wordpress. When I echo `$output` it produce a link for view profile: `localhost/wordpress/www.example.com`. But it should be `www.facebook.com` What change shall i make?
@Sam is close, but I think you need to do this: ``` $url = 'http://www.example.com'; ``` Without the protocol in front, you get the wrong result. Change to ``` $url = 'https://www.example.com'; ``` if you need an SSL link.
268,755
<p>I'm trying to allow Subscriber roles to be allowed to delete their own posts using the following code:</p> <pre><code>&lt;?php if ($post-&gt;post_author == $current_user-&gt;ID) { ?&gt; &lt;div class="col-sm-12 box-delete" style="margin-top: 20px;"&gt; &lt;a class="option" onclick="return confirm('Are you sure you want to delete &lt;?php the_title();?&gt;')" href="&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;"&gt; &lt;i class="fa fa-trash"&gt;&lt;/i&gt; &lt;span class="option-text"&gt;Delete&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I'm using the User Role Editor, but it only works when I grant access to all the core roles, which gives subscriber access to backend, which I certainly don't want. Any other ideas or solutions to accomplish this?</p>
[ { "answer_id": 268756, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": -1, "selected": false, "text": "<p>You should be able to adapt the below to suit your needs, Just make sure to select the option for delete_posts...
2017/05/31
[ "https://wordpress.stackexchange.com/questions/268755", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54953/" ]
I'm trying to allow Subscriber roles to be allowed to delete their own posts using the following code: ``` <?php if ($post->post_author == $current_user->ID) { ?> <div class="col-sm-12 box-delete" style="margin-top: 20px;"> <a class="option" onclick="return confirm('Are you sure you want to delete <?php the_title();?>')" href="<?php echo get_delete_post_link( $post->ID ) ?>"> <i class="fa fa-trash"></i> <span class="option-text">Delete</span> </a> </div> <?php } ?> ``` I'm using the User Role Editor, but it only works when I grant access to all the core roles, which gives subscriber access to backend, which I certainly don't want. Any other ideas or solutions to accomplish this?
The capability required to delete posts is `delete_posts`. If you want them to be able to delete their own published posts, the capability is `delete_published_posts`. The capability required to view the administration panel is `read`. Subscribers have this capability natively, so unless you have removed it, subscribers can access the backend. I would write a simple plugin that upon activation adds the required capabilities to the subscriber role and upon deactivation removes those caps. Then in your theme, you can check for: ``` if( current_user_can( 'delete_posts' ) ) { //* Show delete link } ``` Because the subscriber role doesn't have the capability to `delete_others_posts`, the link will not show on posts that they didn't author, and they will not be able to delete posts that they did not publish. ``` /** * Plugin Name: WordPress StackExchange Question 268755 * Description: Allow subscribers to delete their own posts **/ //* On activation, add the capabilities to the subscriber role register_activation_hook( __FILE__, 'wpse_268755_activation' ); function wpse_268755_activation() { $subscriber = get_role( 'subscriber' ); $subscriber->add_cap( 'delete_posts' ); $subscriber->add_cap( 'delete_published_posts' ); } //* On deactivation, remove the capabilities from the subscriber role register_deactivation_hook( __FILE__, 'wpse_268755_deactivation' ); function wpse_268755_deactivation() { $subscriber = get_role( 'subscriber' ); $subscriber->remove_cap( 'delete_posts' ); $subscriber->remove_cap( 'delete_published_posts' ); } ``` Without giving the user and/or role the capability to delete a post, then they won't be able to do so, even if you show them a delete link. Likewise, a user or role can delete a post if they have the capability even if you don't show a delete link, it will just be more difficult for them.
268,763
<p>I'm designing a theme for a customer. We have only <strong>one post</strong> for each <strong>TvShow</strong>, And inside that post, We have all the <strong>Seasons</strong> and <strong>Episodes</strong>. (Using <code>meta_post</code>).</p> <p>Now, I have a <code>ul</code> for <strong>filtering seasons</strong> and one for <strong>filtering episodes</strong>, Like <em>Show 1st Season, Episode 3</em>. But that needs adding rules to posts (I don't want to use <strong>js</strong> for this). </p> <p>Something like: <code>www.example.com/tvshow-name/season-3/episode4/</code> </p> <p>Apparently we cannot add rule to posts using <code>add_rewrite_rule</code> (Believe me, I tried a lot!), And I don't know how can I add something to address of the post like pages. </p> <p>Something like: <code>add_rewrite_rules('/([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$', 'index.php?name=$matches[1]&amp;season=$matches[2]&amp;episode=$matches[3])</code> </p> <p><strong>The problem is</strong>: After going to <code>www.example.com/tvshow-name/season-3/episode4/</code>, It redirects back to <code>www.example.com/tvshow-name/</code>, And I get no season or episode!</p> <p>Is this possible, Or I have to create a page and create my single post template on that? (It's very ugly, But last hope)</p>
[ { "answer_id": 268770, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You're almost there. You need to add the <code>season</code> and <code>episode</code> query vars to the array of r...
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268763", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120875/" ]
I'm designing a theme for a customer. We have only **one post** for each **TvShow**, And inside that post, We have all the **Seasons** and **Episodes**. (Using `meta_post`). Now, I have a `ul` for **filtering seasons** and one for **filtering episodes**, Like *Show 1st Season, Episode 3*. But that needs adding rules to posts (I don't want to use **js** for this). Something like: `www.example.com/tvshow-name/season-3/episode4/` Apparently we cannot add rule to posts using `add_rewrite_rule` (Believe me, I tried a lot!), And I don't know how can I add something to address of the post like pages. Something like: `add_rewrite_rules('/([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$', 'index.php?name=$matches[1]&season=$matches[2]&episode=$matches[3])` **The problem is**: After going to `www.example.com/tvshow-name/season-3/episode4/`, It redirects back to `www.example.com/tvshow-name/`, And I get no season or episode! Is this possible, Or I have to create a page and create my single post template on that? (It's very ugly, But last hope)
You're almost there. You need to add the `season` and `episode` query vars to the array of recognized vars. Note the small change to your regex as well- ``` function wpd_add_my_rule(){ add_rewrite_rule( '^([^/]+)/season-([0-9]+)/episode-([0-9]+)/?$', 'index.php?name=$matches[1]&season=$matches[2]&episode=$matches[3]', 'top' ); } add_action( 'init', 'wpd_add_my_rule' ); function wpd_add_query_vars( $query_vars ) { $query_vars[] = 'season'; $query_vars[] = 'episode'; return $query_vars; } add_filter( 'query_vars', 'wpd_add_query_vars' ); ``` You can use [`get_query_var()`](https://codex.wordpress.org/Function_Reference/get_query_var) in the template to fetch the values.
268,774
<p>So in WordPress 4.6 they added the localization to the jQuery datepicker to be automatic. I am posting here first because I am not sure if this is actually a bug with WP or if I am doing something wrong.</p> <p>If I set my language in the settings to French then the datepicker correctly gets localized and shows the months etc in French. However, for a demo page I want to show this off and don't want to have the entire site set to French but instead just a single page. Here is what I am using:</p> <pre><code>function change_language( $locale ) { if ( is_page( 156 ) ) { return 'fr_FR'; } return $locale; } add_filter( 'locale', 'change_language' ); </code></pre> <p>It is correctly changing the locale of the page but is not actually loading the datepicker localization based on that locale. Here is a screenshot:</p> <p><a href="https://i.stack.imgur.com/DFjwI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DFjwI.png" alt="enter image description here"></a></p> <p>Is there some kind of timing issue here perhaps? Maybe I am using the wrong filter? Or is this possibly a WP bug?</p> <p>Thanks for any help!</p>
[ { "answer_id": 269354, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>Create <code>page-156.php</code> template with its content matching the page you use right now...
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48502/" ]
So in WordPress 4.6 they added the localization to the jQuery datepicker to be automatic. I am posting here first because I am not sure if this is actually a bug with WP or if I am doing something wrong. If I set my language in the settings to French then the datepicker correctly gets localized and shows the months etc in French. However, for a demo page I want to show this off and don't want to have the entire site set to French but instead just a single page. Here is what I am using: ``` function change_language( $locale ) { if ( is_page( 156 ) ) { return 'fr_FR'; } return $locale; } add_filter( 'locale', 'change_language' ); ``` It is correctly changing the locale of the page but is not actually loading the datepicker localization based on that locale. Here is a screenshot: [![enter image description here](https://i.stack.imgur.com/DFjwI.png)](https://i.stack.imgur.com/DFjwI.png) Is there some kind of timing issue here perhaps? Maybe I am using the wrong filter? Or is this possibly a WP bug? Thanks for any help!
I was able to successfully change the datepicker's strings to a different locale for a single page using the [`switch_to_locale()`](https://developer.wordpress.org/reference/functions/switch_to_locale/) function introduced in [WordPress v4.7](https://make.wordpress.org/core/2016/11/07/user-admin-languages-and-locale-switching-in-4-7/). `switch_to_locale()` will modify the global `$wp_locale` variable which is used by `wp_localize_jquery_ui_datepicker()`. Changing the locale with the `locale` filter alone does not overwrite `$wp_locale`. ``` /** * Use switch_to_locale() on a special page. * This needs to be done early. */ add_action( 'pre_get_posts', 'wpse_change_language' ); function wpse_change_language( $query ) { if ( $query->is_main_query() && $query->is_page( 156 ) ) { // This will change the global $wp_locale which // is used by wp_localize_jquery_ui_datepicker() for translations. switch_to_locale( 'fr_FR' ); } } ``` Enqueue datepicker styles and scripts. ``` /** * Load jQuery datepicker scripts and styles. */ add_action( 'wp_enqueue_scripts', 'wpse_enqueue_datepicker' ); function wpse_enqueue_datepicker() { wp_enqueue_script( 'jquery-ui-datepicker' ); // Using code.jquery.com for simplicity. Normally I'd use a local file. wp_register_style( 'jquery-ui', 'https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css' ); wp_enqueue_style( 'jquery-ui' ); // A simple datepicker initialization script. wp_enqueue_script( 'wpse-datepicker', plugin_dir_url( __FILE__ ) . '/wpse-datepicker.js', [ 'jquery-ui-datepicker' ], false, true ); } ``` **wpse-datepicker.js** ``` /** * Attach a datepicker to our markup. */ jQuery( document ).ready(function( $ ) { $( "#datepicker" ).datepicker(); }); ``` **Shortcode** (for demo purposes) ``` /** * A simple shortcode used for adding the markup for * the datepicker. */ add_shortcode( 'wpse_datepicker', 'wpse_datepicker' ); function wpse_datepicker() { // Start buffering output. ob_start(); // Add some debugging info: echo '<p>The locale is: ' . get_locale() . '</p>'; ?> <div id="datepicker"></div> <?php // Return output generated up to this point. return ob_get_clean(); } ``` **Content of page with ID 156** > > > ``` > Testing the datepicker: > > [wpse_datepicker] > > Test complete! > > ``` > > Also note that it is necessary to have the language files installed for whatever locale is being used. They can be automatically installed by selecting the appropriate language in the admin area under *Settings > General > Site Language*.
268,809
<p>I have a custom user role : Photograph.</p> <p>This role should not be able to log into the back-office, but have to be able to delete their own posts from the front-end.</p> <p>I am using this code to block all non-admin user from connecting to the backoffice with this (function.php) :</p> <pre><code>add_action( 'init', 'blockusers_init' ); function blockusers_init() { if ( is_admin() &amp;&amp; ! current_user_can( 'administrator' ) &amp;&amp; ! ( defined( 'DOING_AJAX' ) &amp;&amp; DOING_AJAX ) ) { wp_redirect( home_url() ); exit; } } </code></pre> <p>And I am using this code to delete posts (portfolio.php) :</p> <pre><code>&lt;a href="&lt;?php echo get_delete_post_link( $post-&gt;ID ) ?&gt;"&gt;Delete post&lt;/a&gt; </code></pre> <p>I have tried a few other options but have never been able to only allow to photographers to delete their posts (or globally posts because they only can see theirs anyway)</p> <p>Thank you !</p>
[ { "answer_id": 269327, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>Assuming you're talking about a custom user <strong>role</strong> named \"<em>photographer</em>\", I believe som...
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268809", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97852/" ]
I have a custom user role : Photograph. This role should not be able to log into the back-office, but have to be able to delete their own posts from the front-end. I am using this code to block all non-admin user from connecting to the backoffice with this (function.php) : ``` add_action( 'init', 'blockusers_init' ); function blockusers_init() { if ( is_admin() && ! current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { wp_redirect( home_url() ); exit; } } ``` And I am using this code to delete posts (portfolio.php) : ``` <a href="<?php echo get_delete_post_link( $post->ID ) ?>">Delete post</a> ``` I have tried a few other options but have never been able to only allow to photographers to delete their posts (or globally posts because they only can see theirs anyway) Thank you !
Assuming you're talking about a custom user **role** named "*photographer*", I believe something like this should add the `delete_posts` capability to that role. ``` function add_delete_cap_to_photog_role() { $role = get_role( 'photographer' ); $role->add_cap( 'delete_posts' ); } add_action( 'admin_init', 'add_delete_cap_to_photog_role'); ``` --- After adding the caps to the role, to solve the rest you could either 1. keep `blockusers_init` and ditch `get_delete_post_link` for an ajax delete. 2. ditch the `blockusers_init` function and do a conditional redirect. I'll give some ideas on each. I prefer ditching `get_delete_post_link` in this instance. **Several steps below, so be aware the code is provided as a guide only. Rewrite and rename things as needed.** --- Ditch `get_delete_post_link` aka AJAX Delete -------------------------------------------- replace `get_delete_post_link` line with something like this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <a href="#" data-id="<?php the_ID() ?>" data-nonce="<?php echo wp_create_nonce('ajax_delete_post_nonce') ?>" class="delete-post">delete</a> <?php endif ?> ``` **Enqueue some JS** in file: *functions.php* ``` function delete_post_ajax() { wp_enqueue_script( 'delete_ajax', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'delete_ajax', 'TheAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'delete_post_ajax' ); ``` **onClick to pass data to delete method** in file: /js/my\_script.js ``` jQuery( document ).ready( function($) { $(document).on( 'click', '.delete-post', function() { var id = $(this).data('id'); var nonce = $(this).data('nonce'); var post = $(this).parents('.post:first'); $.ajax({ type: 'post', url: TheAjax.ajaxurl, data: { action: 'wpse_ajax_delete_post', nonce: nonce, id: id }, success: function( result ) { if( result == 'success' ) { post.fadeOut( function(){ post.remove(); }); } } }) return false; }) }) ``` **the delete method** in file: functions.php (the hook we need is just "`wp_ajax`" prepending the name of the `action` in js file) ``` add_action( 'wp_ajax_wpse_ajax_delete_post', 'wpse_ajax_delete_post_func' ); function wpse_ajax_delete_post_func(){ $permission = check_ajax_referer( 'ajax_delete_post_nonce', 'nonce', false ); if( $permission == false ) { echo 'error'; } else { wp_delete_post( $_REQUEST['id'] ); echo 'success'; } die(); } ``` To do the above by passing uri params: Change where we swapped out `get_delete_posts_link` for this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <?php $nonce = wp_create_nonce('ajax_delete_post_nonce') ?> <a href="<?php echo admin_url( 'admin-ajax.php?action=wpse_ajax_delete_post&id=' . get_the_ID() . '&nonce=' . $nonce ) ?>" data-id="<?php the_ID() ?>" data-nonce="<?php echo $nonce ?>" class="delete-post">delete</a> <?php endif ?> ``` See this for [a more involved walkthrough explaining each step](http://www.vandelaydesign.com/delete-a-wordpress-post-using-ajax/) --- Ditch `blockusers_init` (aka conditional redirect) -------------------------------------------------- This sets a redirect on wp-admin if user does not have `manage_options` cap, which is an administrator role. But first it pseudo-hides things and adds a message to user with some css: **The CSS bit** in file: *functions.php* ``` add_action('admin_head', 'hide_admin_via_css'); function hide_admin_via_css() { if (!current_user_can( 'manage_options' )) { echo '<style>body * {visibility:hidden !important;} body:before {content:"Give it a second...";} '; } } ``` **Enqueueing the JS file** in file: *functions.php* ``` function my_enqueue( $hook ) { if (!current_user_can( 'manage_options' )) { wp_enqueue_script( 'my_custom_script', get_template_directory_uri() '/js/block-admin.js' ); } } add_action('admin_enqueue_scripts', 'my_enqueue'); ``` **Set the JS to just immediately redirect** file: *theme\_root/js/block-admin.js* ``` window.location.href = "/"; ``` **OR a timed redirect** ``` setTimeout(function () { window.location.href = "/"; }, 2000); ``` This approach [came from clicknathan, and he offers more details here.](https://clicknathan.com/web-design/allow-subscribers-to-delete-posts-from-the-front-end-while-still-blocking-the-admin-area/)
268,827
<p>I want to merge two queries together and remove duplicate. I got it working individually. Now I got it working together but the results are not mixed and the duplicates are not removed. So I got the first queries result and then the second query result...</p> <pre><code> $fav_author_list = get_user_option( 'favorite-authors', fav_authors_get_user_id() ); $fav_categorie_list = get_user_option( 'favorite-categories', fav_categories_get_user_id() ); $rm_blog_args = array( 'posts_per_page' =&gt; -1, 'author__in'=&gt; $fav_author_list, 'post_type' =&gt; 'post' ); $rm_blog = new WP_Query($rm_blog_args); $fb_args = array( 'posts_per_page' =&gt; -1, 'category__in'=&gt; $fav_categorie_list, 'post_type' =&gt; 'post' ); $fb = new WP_Query($fb_args); // Final Query $final_query = new WP_Query(); // Merging queries $final_query-&gt;posts = array_merge( $rm_blog-&gt;posts, $fb-&gt;posts); // Recount echo $final_query-&gt;post_count = count( $final_query-&gt;posts ); // Remove duplicate post IDs $post_ids = array(); foreach( $final_query-&gt;posts as $item ) { $post_ids[] = $item-&gt;ID; } $unique_posts = array_unique($post_ids); if($final_query-&gt;have_posts()) : while ( $final_query-&gt;have_posts() ) : $final_query-&gt;the_post(); </code></pre>
[ { "answer_id": 269327, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>Assuming you're talking about a custom user <strong>role</strong> named \"<em>photographer</em>\", I believe som...
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120827/" ]
I want to merge two queries together and remove duplicate. I got it working individually. Now I got it working together but the results are not mixed and the duplicates are not removed. So I got the first queries result and then the second query result... ``` $fav_author_list = get_user_option( 'favorite-authors', fav_authors_get_user_id() ); $fav_categorie_list = get_user_option( 'favorite-categories', fav_categories_get_user_id() ); $rm_blog_args = array( 'posts_per_page' => -1, 'author__in'=> $fav_author_list, 'post_type' => 'post' ); $rm_blog = new WP_Query($rm_blog_args); $fb_args = array( 'posts_per_page' => -1, 'category__in'=> $fav_categorie_list, 'post_type' => 'post' ); $fb = new WP_Query($fb_args); // Final Query $final_query = new WP_Query(); // Merging queries $final_query->posts = array_merge( $rm_blog->posts, $fb->posts); // Recount echo $final_query->post_count = count( $final_query->posts ); // Remove duplicate post IDs $post_ids = array(); foreach( $final_query->posts as $item ) { $post_ids[] = $item->ID; } $unique_posts = array_unique($post_ids); if($final_query->have_posts()) : while ( $final_query->have_posts() ) : $final_query->the_post(); ```
Assuming you're talking about a custom user **role** named "*photographer*", I believe something like this should add the `delete_posts` capability to that role. ``` function add_delete_cap_to_photog_role() { $role = get_role( 'photographer' ); $role->add_cap( 'delete_posts' ); } add_action( 'admin_init', 'add_delete_cap_to_photog_role'); ``` --- After adding the caps to the role, to solve the rest you could either 1. keep `blockusers_init` and ditch `get_delete_post_link` for an ajax delete. 2. ditch the `blockusers_init` function and do a conditional redirect. I'll give some ideas on each. I prefer ditching `get_delete_post_link` in this instance. **Several steps below, so be aware the code is provided as a guide only. Rewrite and rename things as needed.** --- Ditch `get_delete_post_link` aka AJAX Delete -------------------------------------------- replace `get_delete_post_link` line with something like this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <a href="#" data-id="<?php the_ID() ?>" data-nonce="<?php echo wp_create_nonce('ajax_delete_post_nonce') ?>" class="delete-post">delete</a> <?php endif ?> ``` **Enqueue some JS** in file: *functions.php* ``` function delete_post_ajax() { wp_enqueue_script( 'delete_ajax', get_template_directory_uri() . '/js/my_script.js', array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'delete_ajax', 'TheAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'delete_post_ajax' ); ``` **onClick to pass data to delete method** in file: /js/my\_script.js ``` jQuery( document ).ready( function($) { $(document).on( 'click', '.delete-post', function() { var id = $(this).data('id'); var nonce = $(this).data('nonce'); var post = $(this).parents('.post:first'); $.ajax({ type: 'post', url: TheAjax.ajaxurl, data: { action: 'wpse_ajax_delete_post', nonce: nonce, id: id }, success: function( result ) { if( result == 'success' ) { post.fadeOut( function(){ post.remove(); }); } } }) return false; }) }) ``` **the delete method** in file: functions.php (the hook we need is just "`wp_ajax`" prepending the name of the `action` in js file) ``` add_action( 'wp_ajax_wpse_ajax_delete_post', 'wpse_ajax_delete_post_func' ); function wpse_ajax_delete_post_func(){ $permission = check_ajax_referer( 'ajax_delete_post_nonce', 'nonce', false ); if( $permission == false ) { echo 'error'; } else { wp_delete_post( $_REQUEST['id'] ); echo 'success'; } die(); } ``` To do the above by passing uri params: Change where we swapped out `get_delete_posts_link` for this: ``` <?php if( current_user_can( 'delete_post' ) ) : ?> <?php $nonce = wp_create_nonce('ajax_delete_post_nonce') ?> <a href="<?php echo admin_url( 'admin-ajax.php?action=wpse_ajax_delete_post&id=' . get_the_ID() . '&nonce=' . $nonce ) ?>" data-id="<?php the_ID() ?>" data-nonce="<?php echo $nonce ?>" class="delete-post">delete</a> <?php endif ?> ``` See this for [a more involved walkthrough explaining each step](http://www.vandelaydesign.com/delete-a-wordpress-post-using-ajax/) --- Ditch `blockusers_init` (aka conditional redirect) -------------------------------------------------- This sets a redirect on wp-admin if user does not have `manage_options` cap, which is an administrator role. But first it pseudo-hides things and adds a message to user with some css: **The CSS bit** in file: *functions.php* ``` add_action('admin_head', 'hide_admin_via_css'); function hide_admin_via_css() { if (!current_user_can( 'manage_options' )) { echo '<style>body * {visibility:hidden !important;} body:before {content:"Give it a second...";} '; } } ``` **Enqueueing the JS file** in file: *functions.php* ``` function my_enqueue( $hook ) { if (!current_user_can( 'manage_options' )) { wp_enqueue_script( 'my_custom_script', get_template_directory_uri() '/js/block-admin.js' ); } } add_action('admin_enqueue_scripts', 'my_enqueue'); ``` **Set the JS to just immediately redirect** file: *theme\_root/js/block-admin.js* ``` window.location.href = "/"; ``` **OR a timed redirect** ``` setTimeout(function () { window.location.href = "/"; }, 2000); ``` This approach [came from clicknathan, and he offers more details here.](https://clicknathan.com/web-design/allow-subscribers-to-delete-posts-from-the-front-end-while-still-blocking-the-admin-area/)
268,829
<p>I need to hook to the users list page.</p> <p>I Need to add a checkbox column for each user to remember if they have paid or not.</p> <p>Thanks for help because can’t find snippet to hook to this admin page.</p>
[ { "answer_id": 268835, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>The users list column is filtered by <code>manage_users_columns</code>. Take a look into this simple exampl...
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268829", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120924/" ]
I need to hook to the users list page. I Need to add a checkbox column for each user to remember if they have paid or not. Thanks for help because can’t find snippet to hook to this admin page.
One thing you should remember is that function, which will be hooked into `manage_users_custom_column` action **must have 3 parameters**, the first of which (i.e. `$val`) should be the returned value: ``` // Add custom column using 'manage_users_columns' filter if(!function_exists('bm_utm_column')){ function bm_utm_column($columns) { return array_merge( $columns, array('utm_source' => __('UTM source'), 'utm_medium' => __('UTM medium') ) ); } } // Add the content from usermeta's table by using 'manage_users_custom_column' hook if(!function_exists('bm_utm_column_value')){ function bm_utm_column_value($val, $column_name, $user_id) { if ( 'utm_source' == $column_name ) { //Custom value $val = get_user_meta($user_id, 'utm_source', true); } if ( 'utm_medium' == $column_name ) { //Custom value $val = get_user_meta($user_id, 'utm_medium', true); } return $val; } } // Hook into filter add_filter( 'manage_users_columns', 'bm_utm_column' ); add_action( 'manage_users_custom_column', 'bm_utm_column_value', 10, 3 ); ```
268,842
<p>I'm moving existing data involving paintings from an old host that didn't use WordPress to a new host that does.</p> <p>With the old site, data was stored in a database so that each painting had its own page with information (artist, name, year, style, etc) and media pertaining to it, and the pages could then be searched by the different info (similar year, artist, etc)</p> <p>With WordPress, is there any way to use my old database to automatically generate pages/posts that could be sorted in this way?</p>
[ { "answer_id": 268845, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>You <em>could</em> use custom rewrite rule so that WP interprets specific URLs to call and present data from old da...
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268842", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120930/" ]
I'm moving existing data involving paintings from an old host that didn't use WordPress to a new host that does. With the old site, data was stored in a database so that each painting had its own page with information (artist, name, year, style, etc) and media pertaining to it, and the pages could then be searched by the different info (similar year, artist, etc) With WordPress, is there any way to use my old database to automatically generate pages/posts that could be sorted in this way?
Before getting into [*Importing*](https://codex.wordpress.org/Importing_Content), I would familiarize yourself with both the [standard post type](https://codex.wordpress.org/Post_Types) and [post\_meta](https://codex.wordpress.org/Post_Meta_Data_Section) as well as [custom post types](https://codex.wordpress.org/Post_Types) and [taxonomies](https://codex.wordpress.org/Taxonomies). If your end goal would benefit from the latter, you will save yourself quite a bit of headache utilizing them during the import preparation. --- If you prefer working with the database directly, a dump/convert/import is always possible, of course. The schematic attached below would answer any questions you'd have there. Another option, in the vein of the importer, would be to send posts from the old site to the wp-json api endpoints of the wordpress site and handle the migration that way. As [@Rarst](https://wordpress.stackexchange.com/users/847/rarst) mentioned, there isn't really a shortcut, but as [@Max](https://wordpress.stackexchange.com/users/11761/max-yudin) noted in his comment the Importer can at least assist you in the process on the Wordpress side. The below just elaborates on and consolidates links for those points. Using Wordpress Importer ( *Tools > Import* ) --------------------------------------------- There are a multitude of options, (and an even greater multitude of things to consider before using any of them), for importing content into wordpress. **This would be the *safest* method to take.** You can familiarize yourself with many of them here: [Importing Content into Wordpress](https://codex.wordpress.org/Importing_Content) Including: * Blogger * Drupal * Excel Spreadsheet/CSV/XML/JSON * Google Blog Converters * Joomla * LiveJournal * Magento * Mambo * Movable Type * Nucleus CMS * Plone * Posterous * SPIP * Tumblr * Twitter * TypePad * etc, etc, you get the point That pages also lists various plugins for importing an export of a previous cms (multiple types listed). CSV, XML, RSS... any manner really. You will have to create the file it needs to process, of course. --- Database Dump > Import ---------------------- (*Without knowing any info on the current DB*), you could dump the old DBs *pages* content, and convert it into an sql import. **Don't even consider this if you don't really know what you're doing, though. You could seriously muck things up.** But a viable option if you're comfortable with it. I would not consider this a *wordpress* solution, just noting it as an approach. --- Import Bridge with WP-JSON API ------------------------------ If you still have access to the old DB/site, you could utilize the [wp-json api](https://developer.wordpress.org/rest-api/) by writing something on your end that `posts` to the appropriate endpoint on the wordpress end for each entry in your old DB. You may normally build this for keeping things in sync, but it could work as a one-time import tool as well. --- Expanding on this in lieu of OP's additional questions in comments: First, you will want to bookmark [this resource for dealing with the WP\_REST\_request class](https://developer.wordpress.org/reference/classes/wp_rest_request/) Assuming we have written a bit of code on the *old site* that grabs the relevant content and puts it into a formatted POST object, and assuming a custom endpoint: `[Old Site Data ]` POST http to route `http://new-WP-site.com/wp-json/v2/plugin_namespace/v1/posts/` On the WP end, `/plugin_namespace/v1/posts/` we would create. To make this happen, we first `extend` the `WP_REST_Controller` class. Then inside our class we register our routes using `register_rest_routes()`. Something like: ``` public function __construct() { add_action( 'rest_api_init', array($this, 'register_routes' ) ); }//end __construct public function register_routes() { $version = '1'; $namespace = 'plugin_namespace/v' . $version; $base = 'posts'; register_rest_route( $namespace, '/'. $base, array( array( 'methods' => 'GET', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ), array( 'methods' => 'POST', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ),) ); }//register_routes public function this_is_a_callback_function(WP_REST_Request $request) { //if posted in body like form data $posted_data = $request->get_body_params(); } ``` From this point `$posted_data` has what was `POST`ed, and you can walk through it, or pass it on to another function that does. That function would need to build the post\_array out of each entry, and pass that along to `wp_insert_post()` An approach could be made utilizing `WP_REST_Server::CREATABLE` in place of `methods => POST` as well. Mine is just a quick/incomplete example. Also I commented out the `permissions_callbacks`, but that callback function is where your authorization checks would normally go. *Note that `wp_insert_post()` will allow you to pass an array of meta as well, but `wp_update_post` will not. `wp_insert_post` also requires a `title` and `content` values. If you pass any ID other than 0, it will run `wp_upate_post`.* You may want to look at using something like [requestb.in](https://requestb.in) while sorting out your *old site* code to check what it is sending, and [postman](https://www.getpostman.com/) works quite well for checking the api's response. As I mentioned in the comments, [ngrok](https://ngrok.com/) could be used to do the non-wp to wp migration completely in a dev environment. Hopefully that gives you enough info to translate it to whomever you need. --- Relevant WP Tables (posts) -------------------------- Whether building an sql import or writing some other bridge, for **posts**, the tables to map to on the wordpress end of things would be: > > **Table Name** : **data in table** > > > wp\_posts : the posts > > > wp\_postmeta : post meta values > > > wp\_term\_relationships : posts to taxonomies > > > wp\_term\_taxonomy : taxonomies > > > wp\_terms : tag and category values > > > Here is the [full database schematic](https://codex.wordpress.org/Database_Description) [![enter image description here](https://i.stack.imgur.com/F2sGQ.png)](https://i.stack.imgur.com/F2sGQ.png)
268,864
<p>I will frequently add a line of text in my article sending the reader to the article page. This is separate from the actual produced permalink. The problem I'm having is that I can't get the permalink until the article is posted. I can copy the text from the displayed permalink, but if the title is too long that won't work. I can also copy that permalink but then I just get the generic ?p=123 type of link and I have to be sure to remove the 'preview' part of it. </p> <p>Is there a nifty piece of code to put in the link field that will pull the permalink for that article? Kind of how it does in the PHP? This would also solve the issue if the permalink was changed and it broke the custom link. </p>
[ { "answer_id": 268845, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>You <em>could</em> use custom rewrite rule so that WP interprets specific URLs to call and present data from old da...
2017/06/01
[ "https://wordpress.stackexchange.com/questions/268864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120941/" ]
I will frequently add a line of text in my article sending the reader to the article page. This is separate from the actual produced permalink. The problem I'm having is that I can't get the permalink until the article is posted. I can copy the text from the displayed permalink, but if the title is too long that won't work. I can also copy that permalink but then I just get the generic ?p=123 type of link and I have to be sure to remove the 'preview' part of it. Is there a nifty piece of code to put in the link field that will pull the permalink for that article? Kind of how it does in the PHP? This would also solve the issue if the permalink was changed and it broke the custom link.
Before getting into [*Importing*](https://codex.wordpress.org/Importing_Content), I would familiarize yourself with both the [standard post type](https://codex.wordpress.org/Post_Types) and [post\_meta](https://codex.wordpress.org/Post_Meta_Data_Section) as well as [custom post types](https://codex.wordpress.org/Post_Types) and [taxonomies](https://codex.wordpress.org/Taxonomies). If your end goal would benefit from the latter, you will save yourself quite a bit of headache utilizing them during the import preparation. --- If you prefer working with the database directly, a dump/convert/import is always possible, of course. The schematic attached below would answer any questions you'd have there. Another option, in the vein of the importer, would be to send posts from the old site to the wp-json api endpoints of the wordpress site and handle the migration that way. As [@Rarst](https://wordpress.stackexchange.com/users/847/rarst) mentioned, there isn't really a shortcut, but as [@Max](https://wordpress.stackexchange.com/users/11761/max-yudin) noted in his comment the Importer can at least assist you in the process on the Wordpress side. The below just elaborates on and consolidates links for those points. Using Wordpress Importer ( *Tools > Import* ) --------------------------------------------- There are a multitude of options, (and an even greater multitude of things to consider before using any of them), for importing content into wordpress. **This would be the *safest* method to take.** You can familiarize yourself with many of them here: [Importing Content into Wordpress](https://codex.wordpress.org/Importing_Content) Including: * Blogger * Drupal * Excel Spreadsheet/CSV/XML/JSON * Google Blog Converters * Joomla * LiveJournal * Magento * Mambo * Movable Type * Nucleus CMS * Plone * Posterous * SPIP * Tumblr * Twitter * TypePad * etc, etc, you get the point That pages also lists various plugins for importing an export of a previous cms (multiple types listed). CSV, XML, RSS... any manner really. You will have to create the file it needs to process, of course. --- Database Dump > Import ---------------------- (*Without knowing any info on the current DB*), you could dump the old DBs *pages* content, and convert it into an sql import. **Don't even consider this if you don't really know what you're doing, though. You could seriously muck things up.** But a viable option if you're comfortable with it. I would not consider this a *wordpress* solution, just noting it as an approach. --- Import Bridge with WP-JSON API ------------------------------ If you still have access to the old DB/site, you could utilize the [wp-json api](https://developer.wordpress.org/rest-api/) by writing something on your end that `posts` to the appropriate endpoint on the wordpress end for each entry in your old DB. You may normally build this for keeping things in sync, but it could work as a one-time import tool as well. --- Expanding on this in lieu of OP's additional questions in comments: First, you will want to bookmark [this resource for dealing with the WP\_REST\_request class](https://developer.wordpress.org/reference/classes/wp_rest_request/) Assuming we have written a bit of code on the *old site* that grabs the relevant content and puts it into a formatted POST object, and assuming a custom endpoint: `[Old Site Data ]` POST http to route `http://new-WP-site.com/wp-json/v2/plugin_namespace/v1/posts/` On the WP end, `/plugin_namespace/v1/posts/` we would create. To make this happen, we first `extend` the `WP_REST_Controller` class. Then inside our class we register our routes using `register_rest_routes()`. Something like: ``` public function __construct() { add_action( 'rest_api_init', array($this, 'register_routes' ) ); }//end __construct public function register_routes() { $version = '1'; $namespace = 'plugin_namespace/v' . $version; $base = 'posts'; register_rest_route( $namespace, '/'. $base, array( array( 'methods' => 'GET', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ), array( 'methods' => 'POST', 'callback' => array( $this, 'this_is_a_callback_function' ), //'permission_callback' => array( $this, 'key_permissions_check' ), ),) ); }//register_routes public function this_is_a_callback_function(WP_REST_Request $request) { //if posted in body like form data $posted_data = $request->get_body_params(); } ``` From this point `$posted_data` has what was `POST`ed, and you can walk through it, or pass it on to another function that does. That function would need to build the post\_array out of each entry, and pass that along to `wp_insert_post()` An approach could be made utilizing `WP_REST_Server::CREATABLE` in place of `methods => POST` as well. Mine is just a quick/incomplete example. Also I commented out the `permissions_callbacks`, but that callback function is where your authorization checks would normally go. *Note that `wp_insert_post()` will allow you to pass an array of meta as well, but `wp_update_post` will not. `wp_insert_post` also requires a `title` and `content` values. If you pass any ID other than 0, it will run `wp_upate_post`.* You may want to look at using something like [requestb.in](https://requestb.in) while sorting out your *old site* code to check what it is sending, and [postman](https://www.getpostman.com/) works quite well for checking the api's response. As I mentioned in the comments, [ngrok](https://ngrok.com/) could be used to do the non-wp to wp migration completely in a dev environment. Hopefully that gives you enough info to translate it to whomever you need. --- Relevant WP Tables (posts) -------------------------- Whether building an sql import or writing some other bridge, for **posts**, the tables to map to on the wordpress end of things would be: > > **Table Name** : **data in table** > > > wp\_posts : the posts > > > wp\_postmeta : post meta values > > > wp\_term\_relationships : posts to taxonomies > > > wp\_term\_taxonomy : taxonomies > > > wp\_terms : tag and category values > > > Here is the [full database schematic](https://codex.wordpress.org/Database_Description) [![enter image description here](https://i.stack.imgur.com/F2sGQ.png)](https://i.stack.imgur.com/F2sGQ.png)
268,900
<p>I've built a marketplace-type site that lets different users post custom listings to the site.</p> <p>I want to use the WP backend to administer these listings with my admin account. The custom post types are displayed much like normal posts there.</p> <p>The problem is that the post author isn't shown. I googled the issue and quickly found that adding <code>"supports" =&gt; array( "title", "editor", "author" )</code> to the $args for <code>register_post_type()</code> adds a column showing the author to the listings of all custom post items.</p> <p>However, I'm unsure how to add a box displaying the author in the edit screen where the editor and other detailed information about the post shows. As is I just have the box with the publishing information and one for the custom post type's taxonomies.</p> <p>How would I go about having the post's author displayed there too? I'm really a bit lost on this and couldn't find anything on google.</p>
[ { "answer_id": 274573, "author": "PoeHaH", "author_id": 102898, "author_profile": "https://wordpress.stackexchange.com/users/102898", "pm_score": 2, "selected": false, "text": "<p>You can achieve this by using the <code>add_post_type_support</code> function as described here: <a href=\"h...
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268900", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104550/" ]
I've built a marketplace-type site that lets different users post custom listings to the site. I want to use the WP backend to administer these listings with my admin account. The custom post types are displayed much like normal posts there. The problem is that the post author isn't shown. I googled the issue and quickly found that adding `"supports" => array( "title", "editor", "author" )` to the $args for `register_post_type()` adds a column showing the author to the listings of all custom post items. However, I'm unsure how to add a box displaying the author in the edit screen where the editor and other detailed information about the post shows. As is I just have the box with the publishing information and one for the custom post type's taxonomies. How would I go about having the post's author displayed there too? I'm really a bit lost on this and couldn't find anything on google.
You can achieve this by using the `add_post_type_support` function as described here: <https://codex.wordpress.org/Function_Reference/add_post_type_support>. This code should work: ``` function add_author_support_to_posts() { add_post_type_support( 'your_custom_post_type', 'author' ); } add_action( 'init', 'add_author_support_to_posts' ); ``` It can be added in your theme's `function.php` file.
268,913
<p>I want to get several post by tag. So I try to use get_posts() function:</p> <pre><code>&lt;?php $args = array( 'numberposts' =&gt; '3', 'post_status' =&gt; 'publish', 'tag' =&gt; 'travel' ); $recent_posts = get_posts($args);?&gt; </code></pre> <p>But it doesn't work. How can I get posts by tag?</p>
[ { "answer_id": 268934, "author": "Jan Čejka", "author_id": 70265, "author_profile": "https://wordpress.stackexchange.com/users/70265", "pm_score": 1, "selected": false, "text": "<p>Look at this section: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters\" rel=\...
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268913", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103556/" ]
I want to get several post by tag. So I try to use get\_posts() function: ``` <?php $args = array( 'numberposts' => '3', 'post_status' => 'publish', 'tag' => 'travel' ); $recent_posts = get_posts($args);?> ``` But it doesn't work. How can I get posts by tag?
Look at this section: [Tag parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters) in WP Codex, where is explained search by tags. Your code like right. Try change numberposts to int: ``` <?php $args = array( 'numberposts' => 3, 'post_status' => 'publish', 'tag' => 'travel' ); ```
268,928
<p>I would like to redirect users to my home page when the requested page or post cannot be found, but don't know how to go about with that.</p> <p>How do I proceed with such and action?</p>
[ { "answer_id": 268969, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You can set any page/url to handle a 404 error via the <code>htaccess</code> file. This is a good tuto...
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268928", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120985/" ]
I would like to redirect users to my home page when the requested page or post cannot be found, but don't know how to go about with that. How do I proceed with such and action?
You can use this code inside your `404.php` template file to safely redirect to users to homepage: ``` wp_safe_redirect(site_url()); exit(); ``` Use this code before every line of code in your `404.php`. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for. You don't have to delete the content of your `404.php` file, since every line of code after the `exit()` will be ignored.
268,978
<p>I need to copy over Wordpress users with roles/passwords intact to a new install. I'd prefer not to copy the entire site (though if I have to I will.)</p> <p>Currently I only have the one main admin account on the new install. Some people have mentioned importing the old user and user-meta tables from the original database, but others have said this could cause problems.</p>
[ { "answer_id": 268969, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You can set any page/url to handle a 404 error via the <code>htaccess</code> file. This is a good tuto...
2017/06/02
[ "https://wordpress.stackexchange.com/questions/268978", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106747/" ]
I need to copy over Wordpress users with roles/passwords intact to a new install. I'd prefer not to copy the entire site (though if I have to I will.) Currently I only have the one main admin account on the new install. Some people have mentioned importing the old user and user-meta tables from the original database, but others have said this could cause problems.
You can use this code inside your `404.php` template file to safely redirect to users to homepage: ``` wp_safe_redirect(site_url()); exit(); ``` Use this code before every line of code in your `404.php`. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for. You don't have to delete the content of your `404.php` file, since every line of code after the `exit()` will be ignored.
269,016
<p>Recently I've locked myself out of my WordPress site by changing the site URL. I fixed that problem by reverting the site URL to the original one in PHPmyadmin database.</p> <p>But what happens now is that my website is working properly but whenever i access the back-end, only the HTML part of WordPress is loading and not the CSS part. </p> <p>Can anyone explain to me what is happening and how to fix this?</p>
[ { "answer_id": 268969, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You can set any page/url to handle a 404 error via the <code>htaccess</code> file. This is a good tuto...
2017/06/03
[ "https://wordpress.stackexchange.com/questions/269016", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121030/" ]
Recently I've locked myself out of my WordPress site by changing the site URL. I fixed that problem by reverting the site URL to the original one in PHPmyadmin database. But what happens now is that my website is working properly but whenever i access the back-end, only the HTML part of WordPress is loading and not the CSS part. Can anyone explain to me what is happening and how to fix this?
You can use this code inside your `404.php` template file to safely redirect to users to homepage: ``` wp_safe_redirect(site_url()); exit(); ``` Use this code before every line of code in your `404.php`. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for. You don't have to delete the content of your `404.php` file, since every line of code after the `exit()` will be ignored.
269,017
<p>I need to know how to write function for registering <code>activation_hook</code> and <code>deactivation_hook</code> following <strong>OOP fashion with best practices</strong>.</p> <p>I know there are some tasks we can do inside plugin activation/deactivation which is really essential in some cases like to create professional plugins.</p> <p>Thanks.</p>
[ { "answer_id": 269023, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 1, "selected": false, "text": "<p>Well there I got the below ways better-</p>\n\n<pre><code>// in the main plugin file\ndefine( 'PLUGIN_BASE...
2017/06/03
[ "https://wordpress.stackexchange.com/questions/269017", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119647/" ]
I need to know how to write function for registering `activation_hook` and `deactivation_hook` following **OOP fashion with best practices**. I know there are some tasks we can do inside plugin activation/deactivation which is really essential in some cases like to create professional plugins. Thanks.
It can be demonstrated like this way: **Step-1:** Create a folder named *`includes`* (or any name you like) inside the plugin root folder. Create two new files named `class-responsive-slider-activator.php` and `class-responsive-slider-deactivator.php` Now, in *class-responsive-slider-activator.php* create a class - ``` class Responsive_Slider_Activator { public static function activate() { //do your codes to execute upon activation } } ``` and in *class-responsive-slider-deactivator.php* create another class- ``` class Responsive_Slider_Deactivator { public static function deactivate() { //do your codes to execute upon deactivation } } ``` **Step-2:** In main plugin file create functions and register the two hooks - ``` // this code runs during plugin activation function activate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-activator.php'; Responsive_Slider_Activator::activate(); } register_activation_hook( __FILE__, 'activate_responsive_slider' ); // this code runs during plugin deactivation function deactivate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-deactivator.php'; Responsive_Slider_Deactivator::activate(); } register_deactivation_hook( __FILE__, 'deactivate_responsive_slider' ); ``` That's it. N.B. - As per your interest, I would like to denote that there are *some essential tasks* which can be accomplished through activation and deactivation hooks like: 1. Validating other dependent plugin on activation. 2. Creating custom database tables on activation to store data and removing tables on deactivation. 3. Creating custom options for plugins in activation and reset in deactivation. 4. Any other necessary task need to execute in activation. etc
269,037
<p>I'm very new to WP theming and I know there are several types of functions to add Widget areas.</p> <p>The following one, for example, adds a widget area dedicated for menus:</p> <pre><code># functions.php (register a new widget area): function newMenuWidgetArea() { register_nav_menus( array ( 'my-custom-menu' =&gt; __('newMenu'), 'extra-menu' =&gt; __('newMenu') ) ); } add_action('init', 'newMenuWidgetArea'); # header.php (declare widgets in the new area to appear): &lt;?php wp_nav_menu(array ( 'theme_location' =&gt; 'newMenu', 'container_class' =&gt; 'newMenu') ); ?&gt; </code></pre> <h2>The problem:</h2> <p>I don't want to add custom menus manually for example, so I don't look for a functions that add menus and their widget areas manually.</p> <p>I wish to add menus from the GUI, hence I am looking forward to use a function that create global widget areas that can serve for any purpose, and then I will add into them anything I wish directly from the GUI (menu, text area, or whatever other widget).</p> <h2>The question:</h2> <p>What is the general function to add a general-purpose/multi-purpose Widget area?</p> <p>The one I have for now creates a menu. not a widget area in which I could place widgets.</p>
[ { "answer_id": 269023, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 1, "selected": false, "text": "<p>Well there I got the below ways better-</p>\n\n<pre><code>// in the main plugin file\ndefine( 'PLUGIN_BASE...
2017/06/03
[ "https://wordpress.stackexchange.com/questions/269037", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121038/" ]
I'm very new to WP theming and I know there are several types of functions to add Widget areas. The following one, for example, adds a widget area dedicated for menus: ``` # functions.php (register a new widget area): function newMenuWidgetArea() { register_nav_menus( array ( 'my-custom-menu' => __('newMenu'), 'extra-menu' => __('newMenu') ) ); } add_action('init', 'newMenuWidgetArea'); # header.php (declare widgets in the new area to appear): <?php wp_nav_menu(array ( 'theme_location' => 'newMenu', 'container_class' => 'newMenu') ); ?> ``` The problem: ------------ I don't want to add custom menus manually for example, so I don't look for a functions that add menus and their widget areas manually. I wish to add menus from the GUI, hence I am looking forward to use a function that create global widget areas that can serve for any purpose, and then I will add into them anything I wish directly from the GUI (menu, text area, or whatever other widget). The question: ------------- What is the general function to add a general-purpose/multi-purpose Widget area? The one I have for now creates a menu. not a widget area in which I could place widgets.
It can be demonstrated like this way: **Step-1:** Create a folder named *`includes`* (or any name you like) inside the plugin root folder. Create two new files named `class-responsive-slider-activator.php` and `class-responsive-slider-deactivator.php` Now, in *class-responsive-slider-activator.php* create a class - ``` class Responsive_Slider_Activator { public static function activate() { //do your codes to execute upon activation } } ``` and in *class-responsive-slider-deactivator.php* create another class- ``` class Responsive_Slider_Deactivator { public static function deactivate() { //do your codes to execute upon deactivation } } ``` **Step-2:** In main plugin file create functions and register the two hooks - ``` // this code runs during plugin activation function activate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-activator.php'; Responsive_Slider_Activator::activate(); } register_activation_hook( __FILE__, 'activate_responsive_slider' ); // this code runs during plugin deactivation function deactivate_responsive_slider() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-responsive-slider-deactivator.php'; Responsive_Slider_Deactivator::activate(); } register_deactivation_hook( __FILE__, 'deactivate_responsive_slider' ); ``` That's it. N.B. - As per your interest, I would like to denote that there are *some essential tasks* which can be accomplished through activation and deactivation hooks like: 1. Validating other dependent plugin on activation. 2. Creating custom database tables on activation to store data and removing tables on deactivation. 3. Creating custom options for plugins in activation and reset in deactivation. 4. Any other necessary task need to execute in activation. etc
269,061
<p>I've tried a few solutions I found online on this site and many others, but most issues are with theme users and not theme developers. There is a issue with my theme that I am building it is not setting Featured Image/Thumbnail in any type of template meaning pages, post, etc... I also can't remove ones that I preset manually!</p> <p>I also noticed if I click <code>Set Featured Image</code> before the WordPress post page <strong>before</strong> it has full time to load it loads like a low bandwith window showing the media library and that <strong>allows</strong> me to select/set the image! Image of low bandwith media library below: <a href="https://i.stack.imgur.com/imUlc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/imUlc.png" alt="enter image description here"></a></p> <p>What I tried:</p> <ul> <li>Removing Plugins</li> <li>Changing themes (which did allow me to set image)</li> <li>Looking in the themes PHP for errors and reviewed documents on WP official development guide</li> </ul> <p>But one thing I did notice is that on the media library when I go in to set a featured image there is this blank attachment that shows nothing no information. It only shows when setting featured image, does not show in the Media Library page. (See Image below)</p> <p><a href="https://i.stack.imgur.com/PNZuW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PNZuW.jpg" alt="enter image description here"></a></p> <p>I've added code that may be relevant to the issue:</p> <pre><code>if ( $post_type !== 'post' ) { register_post_type( $post_type, array( 'labels' =&gt; array( 'name' =&gt; __( ucfirst( $post_type ) ), 'singular_name' =&gt; __( $post_type ), ), 'supports' =&gt; array( 'title', 'thumbnail', 'editor', 'excerpt', 'author', 'comments', 'revisions', 'custom-fields'), 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_in_admin_bar' =&gt; true, 'taxonomies' =&gt; array( 'category' ), 'public' =&gt; true, 'has_archive' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; strtolower( $post_type ), ), ) ); </code></pre> <p>The error in the console shows: <code>load-scripts.php?c=1&amp;load[]=utils,jquery-core,jquery-migrate,plupload,quicktags&amp;ver=4.7.5:5 POST admin-ajax.php 403 (Forbidden)</code></p>
[ { "answer_id": 269372, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": -1, "selected": false, "text": "<p>Add below function to function.php</p>\n\n<pre>\nif (function_exists('add_theme_support')) { add_t...
2017/06/04
[ "https://wordpress.stackexchange.com/questions/269061", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94807/" ]
I've tried a few solutions I found online on this site and many others, but most issues are with theme users and not theme developers. There is a issue with my theme that I am building it is not setting Featured Image/Thumbnail in any type of template meaning pages, post, etc... I also can't remove ones that I preset manually! I also noticed if I click `Set Featured Image` before the WordPress post page **before** it has full time to load it loads like a low bandwith window showing the media library and that **allows** me to select/set the image! Image of low bandwith media library below: [![enter image description here](https://i.stack.imgur.com/imUlc.png)](https://i.stack.imgur.com/imUlc.png) What I tried: * Removing Plugins * Changing themes (which did allow me to set image) * Looking in the themes PHP for errors and reviewed documents on WP official development guide But one thing I did notice is that on the media library when I go in to set a featured image there is this blank attachment that shows nothing no information. It only shows when setting featured image, does not show in the Media Library page. (See Image below) [![enter image description here](https://i.stack.imgur.com/PNZuW.jpg)](https://i.stack.imgur.com/PNZuW.jpg) I've added code that may be relevant to the issue: ``` if ( $post_type !== 'post' ) { register_post_type( $post_type, array( 'labels' => array( 'name' => __( ucfirst( $post_type ) ), 'singular_name' => __( $post_type ), ), 'supports' => array( 'title', 'thumbnail', 'editor', 'excerpt', 'author', 'comments', 'revisions', 'custom-fields'), 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'show_in_admin_bar' => true, 'taxonomies' => array( 'category' ), 'public' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => strtolower( $post_type ), ), ) ); ``` The error in the console shows: `load-scripts.php?c=1&load[]=utils,jquery-core,jquery-migrate,plupload,quicktags&ver=4.7.5:5 POST admin-ajax.php 403 (Forbidden)`
You added your own answer in the comments section: > > There is only one total php warning/error: > > > ``` wp-admin/admin-header.php:9 - Cannot modify header information - headers already sent by (output started at /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php:413‌​8) include('wp-admin/edit-form-advanced.php'), require_once('wp-admin/admin-header.php'), header… ``` The other half of the errors (it's two different problems you are facing) can also be found in your comments **1)** > > I also get 6x of these that come up but not sure if has anything to do with the theme. > > > ``` Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php on line 4138 ``` The first problem is an *error*, which was raised in your AJAX call. The reason you do not get to see the error directly is, that —and this is what defines AJAX, the *A* is for *asyncronous*— the error was not in your current request, but in a request *spawned* by your current request, which ran in its own process in the background. Meaning: You will have to inspect the AJAX callback, the functionality that was called, to find the actual error. Chrome has a nice set of debugging options available: 1. You can replay that request without loading the whole page again, without repeating the process (e.g. opening a modal) and without bringing the request to a specific state. If you have a callback failing and are in local dev mode, simply change your AJAX endpoint handler, the callback script, hit *Replay XHR* and you will execute the callback with the changed code. Logical? Yes! Overseen? Yes, often. 2. You can open any script that runs in the background, during an AJAX request, in a separate tab. That often makes error messages visible as they printed to the screen. Same here: Easy solution, but overseen by most devs. The second problem is a [race condition](https://en.wikipedia.org/wiki/Race_condition), a *timing* issue. A good indicator for a race condition is using a *slow* connection, something that you can for e.g. set and test in the Chrome developer tools. When things go slow, it's easier to notice and watch when one script finishes its task earlier than another one that relies on the result. If the result is not available, it will fail. When WordPress tells you, that you enqueued a script too early, then for the reason that some script, shipped with core and noted as a dependency, is not yet ready. Another thing that is noted there is that you enqueued the script before the *Dependency API* is not yet ready to *accept* enqueuing a new script. This means that WP will not take and load and output your script, making WP fail at this point. [![enter image description here](https://i.stack.imgur.com/I92Cd.png)](https://i.stack.imgur.com/I92Cd.png)[![enter image description here](https://i.stack.imgur.com/BFCiB.png)](https://i.stack.imgur.com/BFCiB.png) **1)** Please, do **not** hide important information in comments. **Always** add them as edits to your question.
269,071
<p>I've got my HTML Custom Nav set up and it works fine for static template. I want to convert it into wordpress navigation menu. I am totally new to wordpress and i want help to convert html menu to wordpress.</p> <p>Here is the HTML code : </p> <pre><code>&lt;div id="cs-header-menu"&gt; &lt;div class="cs-container"&gt; &lt;!-- Main navigation --&gt; &lt;div class="cs-toggle-main-navigation"&gt;&lt;i class="fa fa-bars"&gt;&lt;/i&gt;&lt;/div&gt; &lt;nav id="cs-main-navigation" class="cs-clearfix"&gt; &lt;ul class="cs-main-navigation cs-clearfix"&gt; &lt;li class="current-menu-item"&gt;&lt;a href="#"&gt;&lt;span&gt;Homepages&lt;/span&gt;&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href="index-1.html"&gt;Homepage 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index-2.html"&gt;Homepage 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index-3.html"&gt;Homepage 3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index-4.html"&gt;Homepage 4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="blog_layout_1.html"&gt;Lifestyle&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="blog_layout_1.html"&gt;Beauty&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="blog_layout_1.html"&gt;Travel&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;!-- Search icon show --&gt; &lt;div id="cs-header-menu-search-button-show"&gt;&lt;i class="fa fa-search"&gt;&lt;/i&gt;&lt;/div&gt; &lt;!-- Search icon --&gt; &lt;div id="cs-header-menu-search-form"&gt; &lt;div id="cs-header-menu-search-button-hide"&gt;&lt;i class="fa fa-close"&gt;&lt;/i&gt;&lt;/div&gt; &lt;form&gt; &lt;input type="text" placeholder="Type and press enter..."&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I don't know how to use class and ids for div, nav, ul and li, and also for sub-menu items. Would anyone please help me with this. Thanks in advance.</p>
[ { "answer_id": 269372, "author": "Roshan Deshapriya", "author_id": 97402, "author_profile": "https://wordpress.stackexchange.com/users/97402", "pm_score": -1, "selected": false, "text": "<p>Add below function to function.php</p>\n\n<pre>\nif (function_exists('add_theme_support')) { add_t...
2017/06/04
[ "https://wordpress.stackexchange.com/questions/269071", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119438/" ]
I've got my HTML Custom Nav set up and it works fine for static template. I want to convert it into wordpress navigation menu. I am totally new to wordpress and i want help to convert html menu to wordpress. Here is the HTML code : ``` <div id="cs-header-menu"> <div class="cs-container"> <!-- Main navigation --> <div class="cs-toggle-main-navigation"><i class="fa fa-bars"></i></div> <nav id="cs-main-navigation" class="cs-clearfix"> <ul class="cs-main-navigation cs-clearfix"> <li class="current-menu-item"><a href="#"><span>Homepages</span></a> <ul class="sub-menu"> <li><a href="index-1.html">Homepage 1</a></li> <li><a href="index-2.html">Homepage 2</a></li> <li><a href="index-3.html">Homepage 3</a></li> <li><a href="index-4.html">Homepage 4</a></li> </ul> </li> <li><a href="blog_layout_1.html">Lifestyle</a></li> <li><a href="blog_layout_1.html">Beauty</a></li> <li><a href="blog_layout_1.html">Travel</a></li> </ul> </nav> <!-- Search icon show --> <div id="cs-header-menu-search-button-show"><i class="fa fa-search"></i></div> <!-- Search icon --> <div id="cs-header-menu-search-form"> <div id="cs-header-menu-search-button-hide"><i class="fa fa-close"></i></div> <form> <input type="text" placeholder="Type and press enter..."> </form> </div> </div> </div> </div> ``` I don't know how to use class and ids for div, nav, ul and li, and also for sub-menu items. Would anyone please help me with this. Thanks in advance.
You added your own answer in the comments section: > > There is only one total php warning/error: > > > ``` wp-admin/admin-header.php:9 - Cannot modify header information - headers already sent by (output started at /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php:413‌​8) include('wp-admin/edit-form-advanced.php'), require_once('wp-admin/admin-header.php'), header… ``` The other half of the errors (it's two different problems you are facing) can also be found in your comments **1)** > > I also get 6x of these that come up but not sure if has anything to do with the theme. > > > ``` Notice: wp_enqueue_style was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.0.) in /home/content/p3pnexwpnas13_data03/47/3056147/html/wp-includ‌​es/functions.php on line 4138 ``` The first problem is an *error*, which was raised in your AJAX call. The reason you do not get to see the error directly is, that —and this is what defines AJAX, the *A* is for *asyncronous*— the error was not in your current request, but in a request *spawned* by your current request, which ran in its own process in the background. Meaning: You will have to inspect the AJAX callback, the functionality that was called, to find the actual error. Chrome has a nice set of debugging options available: 1. You can replay that request without loading the whole page again, without repeating the process (e.g. opening a modal) and without bringing the request to a specific state. If you have a callback failing and are in local dev mode, simply change your AJAX endpoint handler, the callback script, hit *Replay XHR* and you will execute the callback with the changed code. Logical? Yes! Overseen? Yes, often. 2. You can open any script that runs in the background, during an AJAX request, in a separate tab. That often makes error messages visible as they printed to the screen. Same here: Easy solution, but overseen by most devs. The second problem is a [race condition](https://en.wikipedia.org/wiki/Race_condition), a *timing* issue. A good indicator for a race condition is using a *slow* connection, something that you can for e.g. set and test in the Chrome developer tools. When things go slow, it's easier to notice and watch when one script finishes its task earlier than another one that relies on the result. If the result is not available, it will fail. When WordPress tells you, that you enqueued a script too early, then for the reason that some script, shipped with core and noted as a dependency, is not yet ready. Another thing that is noted there is that you enqueued the script before the *Dependency API* is not yet ready to *accept* enqueuing a new script. This means that WP will not take and load and output your script, making WP fail at this point. [![enter image description here](https://i.stack.imgur.com/I92Cd.png)](https://i.stack.imgur.com/I92Cd.png)[![enter image description here](https://i.stack.imgur.com/BFCiB.png)](https://i.stack.imgur.com/BFCiB.png) **1)** Please, do **not** hide important information in comments. **Always** add them as edits to your question.
269,109
<p>I'm trying to add a dynamic attribute to an existing (3rd party) shortcode. The shortcode appears several times on the same page. When I do this (in my functions.php), I can get the first shortcode to output correctly but the others don't.</p> <pre class="lang-php prettyprint-override"><code>function testOne(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student1" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode1', 'testOne'); function testTwo(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student2" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode2', 'testTwo'); function testThree(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student3" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode3', 'testThree'); </code></pre> <p>So as you can see, each shortcode is pulling the slug of the page it resides on (that's what I'm trying to achieve anyway). They're using "and" logic, and in each case, the student is different.</p> <p>Why is only the first instance working? I wish I knew more about all this stuff!</p> <p>Thanks in advance folks, Mike</p>
[ { "answer_id": 269113, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 0, "selected": false, "text": "<p>I think you're just missing some single quotes to escape out to php:</p>\n\n<pre><code>function testOne(){\n re...
2017/06/04
[ "https://wordpress.stackexchange.com/questions/269109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121089/" ]
I'm trying to add a dynamic attribute to an existing (3rd party) shortcode. The shortcode appears several times on the same page. When I do this (in my functions.php), I can get the first shortcode to output correctly but the others don't. ```php function testOne(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student1" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode1', 'testOne'); function testTwo(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student2" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode2', 'testTwo'); function testThree(){ return do_shortcode('[abc type="contact" orderby="menu_order" order="asc" style="list-post" logic="and" abc_tax_student="student3" abc_tax_teacher="'.basename(get_permalink()).'"]'); } add_shortcode('shortcode3', 'testThree'); ``` So as you can see, each shortcode is pulling the slug of the page it resides on (that's what I'm trying to achieve anyway). They're using "and" logic, and in each case, the student is different. Why is only the first instance working? I wish I knew more about all this stuff! Thanks in advance folks, Mike
I think you are having syntax errors in the shortcode like missing single quotes.Please check the code properly.
269,121
<p>I've been having some issues since Google requires an API code (which I already have) to display the map on the theme page, but the thing is I'm not sure where and how it should be enqueued.</p> <p>This is what it looks like on the code:</p> <pre><code>function sano_footer_scripts() { // wp_enqueue_script( 'jquery_1.11.2_min_js', get_template_directory_uri() . '/js/jquery-1.11.2.min.js','','', true); // wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&amp;amp;sensor=false','','', true); // wp_enqueue_script( 'jquery_autosize_js', get_template_directory_uri() . '/js/jquery.autosize.js','','', true); // wp_enqueue_script( 'jquery_smooth_scroll_min_js', get_template_directory_uri() . '/js/jquery.smooth-scroll.min.js','','', true); // wp_enqueue_script( 'selectivizr_min_js', get_template_directory_uri() . '/js/selectivizr-min.js','','', true); // wp_enqueue_script( 'jquery_watermark_min_js', get_template_directory_uri() . '/js/jquery.watermark.min.js','','', true); // wp_enqueue_script( 'read_more_js', get_template_directory_uri() . '/js/read_more.js','','', true); // wp_enqueue_script( 'jquery_mixitup_min_js', get_template_directory_uri() . '/js/jquery.mixitup.min.js','','', true); // wp_enqueue_script( 'jquery_magnific_popup_min_js', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js','','', true); // wp_enqueue_script( 'jquery_animateNumber_min_js', get_template_directory_uri() . '/js/jquery.animateNumber.min.js','','', true); // wp_enqueue_script( 'select2_min_js', get_template_directory_uri() . '/js/select2.min.js','','', true); // wp_enqueue_script( 'owl_carousel_min_js', get_template_directory_uri() . '/js/owl.carousel.min.js','','', true); // wp_enqueue_script( 'parallax_plugin_min_js', get_template_directory_uri() . '/js/parallax-plugin.min.js','','', true); // wp_enqueue_script( 'jquery_nicescroll_min_js', get_template_directory_uri() . '/js/jquery.nicescroll.min.js','','', true); // wp_enqueue_script( 'jquery_inview_min_js', get_template_directory_uri() . '/js/jquery.inview.min.js','','', true); // wp_enqueue_script( 'jquery_validate_js', get_template_directory_uri() . '/js/jquery.validate.js','','', true); // wp_enqueue_script( 'jquery_hoverdir_js', get_template_directory_uri() . '/js/jquery.hoverdir.js','','', true); //wp_enqueue_script( 'map_default_js', get_template_directory_uri() . '/js/map-default.js','','', true); //wp_enqueue_script( 'responsiveslides_min_js', get_template_directory_uri() . '/js/responsiveslides.min.js','','', true); //wp_enqueue_script( 'jquery_ui_js', get_template_directory_uri() . '/js/jquery-ui.js','','', true); //wp_enqueue_script( 'init_js', get_template_directory_uri() . '/js/init.js','','', true); //wp_enqueue_script( 'respond_src_js', get_template_directory_uri() . '/js/respond.src.js','','', true); } //add_action( 'wp_enqueue_scripts', 'sano_footer_scripts' ); </code></pre> <p>Can anyone tell me where my API code should be?</p>
[ { "answer_id": 269122, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You are using <code>wp_enqueue_scripts()</code> in the proper way, however you are enqueuing everything in ...
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269121", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121097/" ]
I've been having some issues since Google requires an API code (which I already have) to display the map on the theme page, but the thing is I'm not sure where and how it should be enqueued. This is what it looks like on the code: ``` function sano_footer_scripts() { // wp_enqueue_script( 'jquery_1.11.2_min_js', get_template_directory_uri() . '/js/jquery-1.11.2.min.js','','', true); // wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false','','', true); // wp_enqueue_script( 'jquery_autosize_js', get_template_directory_uri() . '/js/jquery.autosize.js','','', true); // wp_enqueue_script( 'jquery_smooth_scroll_min_js', get_template_directory_uri() . '/js/jquery.smooth-scroll.min.js','','', true); // wp_enqueue_script( 'selectivizr_min_js', get_template_directory_uri() . '/js/selectivizr-min.js','','', true); // wp_enqueue_script( 'jquery_watermark_min_js', get_template_directory_uri() . '/js/jquery.watermark.min.js','','', true); // wp_enqueue_script( 'read_more_js', get_template_directory_uri() . '/js/read_more.js','','', true); // wp_enqueue_script( 'jquery_mixitup_min_js', get_template_directory_uri() . '/js/jquery.mixitup.min.js','','', true); // wp_enqueue_script( 'jquery_magnific_popup_min_js', get_template_directory_uri() . '/js/jquery.magnific-popup.min.js','','', true); // wp_enqueue_script( 'jquery_animateNumber_min_js', get_template_directory_uri() . '/js/jquery.animateNumber.min.js','','', true); // wp_enqueue_script( 'select2_min_js', get_template_directory_uri() . '/js/select2.min.js','','', true); // wp_enqueue_script( 'owl_carousel_min_js', get_template_directory_uri() . '/js/owl.carousel.min.js','','', true); // wp_enqueue_script( 'parallax_plugin_min_js', get_template_directory_uri() . '/js/parallax-plugin.min.js','','', true); // wp_enqueue_script( 'jquery_nicescroll_min_js', get_template_directory_uri() . '/js/jquery.nicescroll.min.js','','', true); // wp_enqueue_script( 'jquery_inview_min_js', get_template_directory_uri() . '/js/jquery.inview.min.js','','', true); // wp_enqueue_script( 'jquery_validate_js', get_template_directory_uri() . '/js/jquery.validate.js','','', true); // wp_enqueue_script( 'jquery_hoverdir_js', get_template_directory_uri() . '/js/jquery.hoverdir.js','','', true); //wp_enqueue_script( 'map_default_js', get_template_directory_uri() . '/js/map-default.js','','', true); //wp_enqueue_script( 'responsiveslides_min_js', get_template_directory_uri() . '/js/responsiveslides.min.js','','', true); //wp_enqueue_script( 'jquery_ui_js', get_template_directory_uri() . '/js/jquery-ui.js','','', true); //wp_enqueue_script( 'init_js', get_template_directory_uri() . '/js/init.js','','', true); //wp_enqueue_script( 'respond_src_js', get_template_directory_uri() . '/js/respond.src.js','','', true); } //add_action( 'wp_enqueue_scripts', 'sano_footer_scripts' ); ``` Can anyone tell me where my API code should be?
Your API key is URL encoded as a GET variable like so: ``` wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=yourKeyHere', '', '' ); ``` I don't urlencode the handle. The function/class does that. So if you're having problems getting the script to load, don't urlencode the handle.
269,133
<p>I am finding a way to add <em>A</em> before the menu if we are on desktop and to add <em>B</em> if we are on mobile device.</p> <p>As such, this is are my functions for <em>A</em> and <em>B</em>:</p> <pre><code>add_action( 'wp_head', 'A_function' ); function A_function() { //add A } add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 ); function B_function() { //add B } </code></pre> <p>I know I need to put these hooks in functions file but I don't know the way to do it, I know we can use <code>wp_is_mobile()</code>.</p> <p>How can I achieve that?</p>
[ { "answer_id": 269122, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You are using <code>wp_enqueue_scripts()</code> in the proper way, however you are enqueuing everything in ...
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269133", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102551/" ]
I am finding a way to add *A* before the menu if we are on desktop and to add *B* if we are on mobile device. As such, this is are my functions for *A* and *B*: ``` add_action( 'wp_head', 'A_function' ); function A_function() { //add A } add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 ); function B_function() { //add B } ``` I know I need to put these hooks in functions file but I don't know the way to do it, I know we can use `wp_is_mobile()`. How can I achieve that?
Your API key is URL encoded as a GET variable like so: ``` wp_enqueue_script( 'google_js', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=yourKeyHere', '', '' ); ``` I don't urlencode the handle. The function/class does that. So if you're having problems getting the script to load, don't urlencode the handle.
269,153
<p>I am aware that contributors cannot publish posts, and that by design WP will not show contributors in the author dropdown list (this has been discussed here: <a href="https://wordpress.stackexchange.com/questions/168665/contributors-missing-from-author-dropdown">Contributors missing from author dropdown</a>), however I am looking for a way to force listing contributors in the dropdown menu, when an author will create content to allow him/her to start creating content for a given contributor.</p> <p>Possible?</p>
[ { "answer_id": 269209, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Here's a solution that will remove the original author meta box and replace it with a similar, but customize...
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1210/" ]
I am aware that contributors cannot publish posts, and that by design WP will not show contributors in the author dropdown list (this has been discussed here: [Contributors missing from author dropdown](https://wordpress.stackexchange.com/questions/168665/contributors-missing-from-author-dropdown)), however I am looking for a way to force listing contributors in the dropdown menu, when an author will create content to allow him/her to start creating content for a given contributor. Possible?
Here's a solution that will remove the original author meta box and replace it with a similar, but customized version which includes users with the `contributor` role. The logic for adding/removing the author meta box is pulled directly from the core. The meta box display callback is also cloned from the core, but we use the `role__in` parameter of [`wp_dropdown_users()`](https://developer.wordpress.org/reference/functions/wp_dropdown_users/) which lets us specify which roles we want to include within the dropdown. ``` /** * Removes the original author meta box and replaces it * with a customized version. */ add_action( 'add_meta_boxes', 'wpse_replace_post_author_meta_box' ); function wpse_replace_post_author_meta_box() { $post_type = get_post_type(); $post_type_object = get_post_type_object( $post_type ); if ( post_type_supports( $post_type, 'author' ) ) { if ( is_super_admin() || current_user_can( $post_type_object->cap->edit_others_posts ) ) { remove_meta_box( 'authordiv', $post_type, 'core' ); add_meta_box( 'authordiv', __( 'Author', 'text-domain' ), 'wpse_post_author_meta_box', null, 'normal' ); } } } /** * Display form field with list of authors. * Modified version of post_author_meta_box(). * * @global int $user_ID * * @param object $post */ function wpse_post_author_meta_box( $post ) { global $user_ID; ?> <label class="screen-reader-text" for="post_author_override"><?php _e( 'Author', 'text-domain' ); ?></label> <?php wp_dropdown_users( array( 'role__in' => [ 'administrator', 'author', 'contributor' ], // Add desired roles here. 'name' => 'post_author_override', 'selected' => empty( $post->ID ) ? $user_ID : $post->post_author, 'include_selected' => true, 'show' => 'display_name_with_login', ) ); } ```
269,160
<p>When using a 3rd party theme, some external dependancies are enqueued using the HTTP protocol, which is fine if you don't use SSL and if the child theme is allowing complete control over all of these elements, which in this case something is either being missed by myself or enqueued through another stylesheet - I've used grep via terminal to look for where this could be happening, without luck.</p> <p>Unfortunately, I have found in some cases logic goes right out of the window when these themes have been built, and can't be forced to HTTPS through theme code (bar editting the parent theme, which defeats the point).</p> <p>I had hoped there might be a way to force all (or be selective if need be) HTTP requests through HTAccess with something along the lines of:</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} ^fonts.googleapis\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://fonts.googleapis.com/$1 [R,L] </code></pre> <p>This does not work - unless I'm doing something glaring obviously wrong?</p> <p>Has anyone encountered this before and found a solution?</p> <p>On a side note, I thought it was best practice to enqueue without any prefix like so:</p> <pre><code>//fonts.googleapis.com </code></pre> <p>Is that correct?</p>
[ { "answer_id": 269209, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Here's a solution that will remove the original author meta box and replace it with a similar, but customize...
2017/06/05
[ "https://wordpress.stackexchange.com/questions/269160", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52020/" ]
When using a 3rd party theme, some external dependancies are enqueued using the HTTP protocol, which is fine if you don't use SSL and if the child theme is allowing complete control over all of these elements, which in this case something is either being missed by myself or enqueued through another stylesheet - I've used grep via terminal to look for where this could be happening, without luck. Unfortunately, I have found in some cases logic goes right out of the window when these themes have been built, and can't be forced to HTTPS through theme code (bar editting the parent theme, which defeats the point). I had hoped there might be a way to force all (or be selective if need be) HTTP requests through HTAccess with something along the lines of: ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^fonts.googleapis\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://fonts.googleapis.com/$1 [R,L] ``` This does not work - unless I'm doing something glaring obviously wrong? Has anyone encountered this before and found a solution? On a side note, I thought it was best practice to enqueue without any prefix like so: ``` //fonts.googleapis.com ``` Is that correct?
Here's a solution that will remove the original author meta box and replace it with a similar, but customized version which includes users with the `contributor` role. The logic for adding/removing the author meta box is pulled directly from the core. The meta box display callback is also cloned from the core, but we use the `role__in` parameter of [`wp_dropdown_users()`](https://developer.wordpress.org/reference/functions/wp_dropdown_users/) which lets us specify which roles we want to include within the dropdown. ``` /** * Removes the original author meta box and replaces it * with a customized version. */ add_action( 'add_meta_boxes', 'wpse_replace_post_author_meta_box' ); function wpse_replace_post_author_meta_box() { $post_type = get_post_type(); $post_type_object = get_post_type_object( $post_type ); if ( post_type_supports( $post_type, 'author' ) ) { if ( is_super_admin() || current_user_can( $post_type_object->cap->edit_others_posts ) ) { remove_meta_box( 'authordiv', $post_type, 'core' ); add_meta_box( 'authordiv', __( 'Author', 'text-domain' ), 'wpse_post_author_meta_box', null, 'normal' ); } } } /** * Display form field with list of authors. * Modified version of post_author_meta_box(). * * @global int $user_ID * * @param object $post */ function wpse_post_author_meta_box( $post ) { global $user_ID; ?> <label class="screen-reader-text" for="post_author_override"><?php _e( 'Author', 'text-domain' ); ?></label> <?php wp_dropdown_users( array( 'role__in' => [ 'administrator', 'author', 'contributor' ], // Add desired roles here. 'name' => 'post_author_override', 'selected' => empty( $post->ID ) ? $user_ID : $post->post_author, 'include_selected' => true, 'show' => 'display_name_with_login', ) ); } ```
269,215
<p>I am trying to add this to functions.php. In my test lab on a different site it adds the test info information fine. But on the website I am trying to add it to nothing happens. The website is running a builder thrifty theme with the latest woocommerce. Any ideas? I'm basically just wanting to add a line of text on every product page that is like a disclaimer but can't.</p> <pre><code>add_action('woocommerce_before_add_to_cart_form','print_something_below_short_description'); function print_something_below_short_description() { echo 'Test Info.'; } </code></pre>
[ { "answer_id": 269220, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 1, "selected": false, "text": "<p>It's possible the theme or another plugin are using that hook with a later priority. Your <code>add_action</cod...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121164/" ]
I am trying to add this to functions.php. In my test lab on a different site it adds the test info information fine. But on the website I am trying to add it to nothing happens. The website is running a builder thrifty theme with the latest woocommerce. Any ideas? I'm basically just wanting to add a line of text on every product page that is like a disclaimer but can't. ``` add_action('woocommerce_before_add_to_cart_form','print_something_below_short_description'); function print_something_below_short_description() { echo 'Test Info.'; } ```
It's possible the theme or another plugin are using that hook with a later priority. Your `add_action` would have the default of 10; try giving it a 12 or a 20, etc. and see if the text shows up. `add_action('woocommerce_before_add_to_cart_form','print_something_below_short_description', 10);` You can [read about Priority with Action Hooks here](https://developer.wordpress.org/reference/functions/add_action/#parameters).
269,231
<p><a href="https://i.stack.imgur.com/XQVgH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XQVgH.jpg" alt="enter image description here"></a> I am writing a query for inserting data in to database but when I am printing query at output it turns into "SHOW COLUMNS from tbl_name" query. I am writing below query . But it executes like shown in image</p> <pre><code>$table_name1 = $wpdb-&gt;prefix . 'fullcontact'; $sql1=$wpdb-&gt;insert( $table_name1, array( 'status' =&gt; $status, 'request_id' =&gt; $req_id, 'likelihood' =&gt; $likelihood, 'photos' =&gt; $photos, 'chats' =&gt; $chats, 'websites' =&gt; $websites, 'fullname' =&gt; $fullname, 'familyname' =&gt; $familyname, 'givenname' =&gt; $givenname, 'organisation' =&gt; $organisation, 'normalizedlocation' =&gt; $normalizedlocation, 'city' =&gt; $city, 'state' =&gt; $state, 'country' =&gt; $country, 'age' =&gt; $age, 'agerange' =&gt; $agerange, 'gender' =&gt; $gender, 'locationgeneral' =&gt; $locationgeneral, 'socialprofiles' =&gt; $socialprofiles, 'scores' =&gt; $scores, 'topics' =&gt; $topics ) ); //exit( var_dump( $wpdb-&gt;last_query ) ); $wpdb-&gt;show_errors(); $wpdb-&gt;print_error($sql1); </code></pre>
[ { "answer_id": 269251, "author": "Roger Bücker", "author_id": 121189, "author_profile": "https://wordpress.stackexchange.com/users/121189", "pm_score": 0, "selected": false, "text": "<p>Just had the same Problem, the fix was i tried to add varchar longer than the database field can hold....
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269231", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121179/" ]
[![enter image description here](https://i.stack.imgur.com/XQVgH.jpg)](https://i.stack.imgur.com/XQVgH.jpg) I am writing a query for inserting data in to database but when I am printing query at output it turns into "SHOW COLUMNS from tbl\_name" query. I am writing below query . But it executes like shown in image ``` $table_name1 = $wpdb->prefix . 'fullcontact'; $sql1=$wpdb->insert( $table_name1, array( 'status' => $status, 'request_id' => $req_id, 'likelihood' => $likelihood, 'photos' => $photos, 'chats' => $chats, 'websites' => $websites, 'fullname' => $fullname, 'familyname' => $familyname, 'givenname' => $givenname, 'organisation' => $organisation, 'normalizedlocation' => $normalizedlocation, 'city' => $city, 'state' => $state, 'country' => $country, 'age' => $age, 'agerange' => $agerange, 'gender' => $gender, 'locationgeneral' => $locationgeneral, 'socialprofiles' => $socialprofiles, 'scores' => $scores, 'topics' => $topics ) ); //exit( var_dump( $wpdb->last_query ) ); $wpdb->show_errors(); $wpdb->print_error($sql1); ```
For anyone else finding this question. Wordpress seems to do a `SHOW FULL COLUMNS` query before executing the `INSERT` query. If it determines that the `INSERT` query would fail/store bad data, for example because the given data types would not fit in the column, it does not execute the insert query at all and return false. Check: * Have you filled all fields that can not be null and do not have a default value * Does the data type for every field match the data type in the database * Does the data passed to the function violate any constraints? A string cannot be longer than the maximum length of the field you are trying to put it into. An integer field has a minimum and maximum value. Unsigned integers cannot contain negative values.
269,254
<p>I have used bootstrap nav walker but it works good with just 1 and 2 level , 3 level is not supported correctly.</p> <p>I found one here <a href="http://www.dangtrinh.com/2015/05/multilevel-drop-down-menu-in-wordpress.html" rel="nofollow noreferrer">http://www.dangtrinh.com/2015/05/multilevel-drop-down-menu-in-wordpress.html</a></p> <p>but it is not that good . </p> <p>How can I make navigation like one in blazok theme on themeforest. </p>
[ { "answer_id": 269302, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 2, "selected": true, "text": "<p>Download <a href=\"https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8\" rel=\"nofollow nore...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269254", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78103/" ]
I have used bootstrap nav walker but it works good with just 1 and 2 level , 3 level is not supported correctly. I found one here <http://www.dangtrinh.com/2015/05/multilevel-drop-down-menu-in-wordpress.html> but it is not that good . How can I make navigation like one in blazok theme on themeforest.
Download [Bootstrap nav walker file](https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8).Call this file to your functions.php. Then Put this code to dynamic your nav menu: ``` <?php $args = array( 'theme_location' => 'primary', 'menu' => 'Main', 'container' => 'false', 'container_class' => '', 'container_id' => '', 'menu_class' => 'nav navbar-nav navbar-right', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 5, 'walker' => new my_custom_walker_nav_menu() ); wp_nav_menu ($args); ?> ``` You can choose the value to the 'depth' key how many depth you need
269,267
<p>I am using a plugin called AddThis on a website at: <a href="http://minionsphotography.com/" rel="nofollow noreferrer">http://minionsphotography.com/</a>. With AddThis enabled I am getting some extra P tags in-between the header and the text on the page: <code>&lt;p&gt;&lt;!-- AddThis Sharing Buttons above --&gt;&lt;/p&gt;</code>, this adds a lot of extra space and shouldn't be there. *On the homepage it's the space between the Welcome header and the slideshow image.</p> <p>Is there a function or something out there that I could use to find and remove the html comment on the page to eliminate the extra space? I use a plugin called pSquirrel to detect and remove empty P tags, but it won't remove this one (I'm guessing because pSquirrel doesn't think it's empty because of the html comment).</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 269302, "author": "Porosh Ahammed", "author_id": 68186, "author_profile": "https://wordpress.stackexchange.com/users/68186", "pm_score": 2, "selected": true, "text": "<p>Download <a href=\"https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8\" rel=\"nofollow nore...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I am using a plugin called AddThis on a website at: <http://minionsphotography.com/>. With AddThis enabled I am getting some extra P tags in-between the header and the text on the page: `<p><!-- AddThis Sharing Buttons above --></p>`, this adds a lot of extra space and shouldn't be there. \*On the homepage it's the space between the Welcome header and the slideshow image. Is there a function or something out there that I could use to find and remove the html comment on the page to eliminate the extra space? I use a plugin called pSquirrel to detect and remove empty P tags, but it won't remove this one (I'm guessing because pSquirrel doesn't think it's empty because of the html comment). Thanks, Josh
Download [Bootstrap nav walker file](https://drive.google.com/open?id=0B1mlr5jLh4p8TEFya1JsQmQzWW8).Call this file to your functions.php. Then Put this code to dynamic your nav menu: ``` <?php $args = array( 'theme_location' => 'primary', 'menu' => 'Main', 'container' => 'false', 'container_class' => '', 'container_id' => '', 'menu_class' => 'nav navbar-nav navbar-right', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 5, 'walker' => new my_custom_walker_nav_menu() ); wp_nav_menu ($args); ?> ``` You can choose the value to the 'depth' key how many depth you need
269,277
<p>I can't figure how to get the ID of the custom taxonomy I'm using to loop through the custom post type called "test_values". </p> <pre><code>function prefix_load_term_posts () { $term_slug = $_POST[ 'term' ]; $args = array ( 'post_type' =&gt; 'test_values', 'posts_per_page' =&gt; 1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'test_value_category', 'field' =&gt; 'slug', 'terms' =&gt; $term_slug , ), ), ); global $post; $myposts = get_posts( $args ); ob_start (); foreach( $myposts as $post ) : setup_postdata($post); ?&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>Anyone have any suggestions how to get this taxonomy ID within the loop? </p>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109345/" ]
I can't figure how to get the ID of the custom taxonomy I'm using to loop through the custom post type called "test\_values". ``` function prefix_load_term_posts () { $term_slug = $_POST[ 'term' ]; $args = array ( 'post_type' => 'test_values', 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'test_value_category', 'field' => 'slug', 'terms' => $term_slug , ), ), ); global $post; $myposts = get_posts( $args ); ob_start (); foreach( $myposts as $post ) : setup_postdata($post); ?> <?php endforeach; ?> ``` Anyone have any suggestions how to get this taxonomy ID within the loop?
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,291
<p>i'm using (<a href="https://codex.wordpress.org/Javascript_Reference/wp.media" rel="nofollow noreferrer">media library</a>) in my theme on Frontend.</p> <p>It's possible load only attachment of current user logged? For example, my wp user id is 55 and load only my attachment and not others by different users?</p> <p>There isn't a documentation about how work js in WP...</p>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269291", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110442/" ]
i'm using ([media library](https://codex.wordpress.org/Javascript_Reference/wp.media)) in my theme on Frontend. It's possible load only attachment of current user logged? For example, my wp user id is 55 and load only my attachment and not others by different users? There isn't a documentation about how work js in WP...
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,308
<p>I want to add class to caption shortcode, pulled from custom attachment field. I add the field via:</p> <pre><code>function add_img_class( $form_fields, $post ) { $form_fields['img_class_field'] = array( 'label' =&gt; __( 'Image class', 'text-domain' ), 'input' =&gt; 'text', 'value' =&gt; get_post_meta( $post-&gt;ID, 'img_class_field', true ) ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'add_img_class', 10, 2 ); function save_img_class( $post, $attachment ) { if( isset( $attachment['img_class_field'] ) ) update_post_meta( $post['ID'], 'img_class_field', $attachment['img_class_field']); return $post; } add_filter( 'attachment_fields_to_save', 'save_img_class', 10, 2 ); </code></pre> <p>How do I dynamically add "class" attribute with the field value to caption shortcode now? </p> <pre><code>[caption ... class="img_class_field"]&lt;img src...&gt;[/caption] </code></pre>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I want to add class to caption shortcode, pulled from custom attachment field. I add the field via: ``` function add_img_class( $form_fields, $post ) { $form_fields['img_class_field'] = array( 'label' => __( 'Image class', 'text-domain' ), 'input' => 'text', 'value' => get_post_meta( $post->ID, 'img_class_field', true ) ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'add_img_class', 10, 2 ); function save_img_class( $post, $attachment ) { if( isset( $attachment['img_class_field'] ) ) update_post_meta( $post['ID'], 'img_class_field', $attachment['img_class_field']); return $post; } add_filter( 'attachment_fields_to_save', 'save_img_class', 10, 2 ); ``` How do I dynamically add "class" attribute with the field value to caption shortcode now? ``` [caption ... class="img_class_field"]<img src...>[/caption] ```
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,316
<pre><code>&lt;p&gt; &lt;?php the_author_meta('description'); ?&gt; &lt;a href="#"&gt; Read More &lt;/a&gt; &lt;/p&gt; </code></pre> <p>I just wanted to pull authors link here "#", but I tried many options such as →</p> <pre><code>get_the_author() the_author_link() the_author_posts_link() </code></pre> <p>All of them are pulling authors name also. Any solution that will help me pull Just the authors link?</p>
[ { "answer_id": 269380, "author": "Shefali", "author_id": 117047, "author_profile": "https://wordpress.stackexchange.com/users/117047", "pm_score": 4, "selected": true, "text": "<p>You can try this function <code>get_term_by($field, $value, $taxonomy, $output, $filter )</code> or </p>\n...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269316", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
``` <p> <?php the_author_meta('description'); ?> <a href="#"> Read More </a> </p> ``` I just wanted to pull authors link here "#", but I tried many options such as → ``` get_the_author() the_author_link() the_author_posts_link() ``` All of them are pulling authors name also. Any solution that will help me pull Just the authors link?
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or ``` $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } ``` or `get_queried_object_id()`
269,323
<p>Hoping someone can help.</p> <p>I am trying to change the "Notice of Email Change" text within the email you receive when updating an email address.</p> <p>Here is what I have so far</p> <pre><code>add_filter( 'password_change_email', 'red_change_password_mail_message', 10, 3 ); function red_change_password_mail_message( $pass_change_mail, $user, $userdata ) { $new_message_txt = __( 'Hi [first_name] [last_name], This notice confirms that your email was changed on IBEW Local 353. If you did not change your email, please contact the Site Administrator at support@redsealcreative.com This email has been sent to [user_email] Regards, All at IBEW Local 353' ); $pass_change_mail[ 'message' ] = $new_message_txt; return $pass_change_mail; } </code></pre> <p>As you can see I want to personalize the email message with their first and last name. What would be the best way to do this and would anyone be able to provide me with a example to start me off please.</p>
[ { "answer_id": 269326, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You're already passing a <code>$user</code> object into your function, so you should be able to substitut...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111895/" ]
Hoping someone can help. I am trying to change the "Notice of Email Change" text within the email you receive when updating an email address. Here is what I have so far ``` add_filter( 'password_change_email', 'red_change_password_mail_message', 10, 3 ); function red_change_password_mail_message( $pass_change_mail, $user, $userdata ) { $new_message_txt = __( 'Hi [first_name] [last_name], This notice confirms that your email was changed on IBEW Local 353. If you did not change your email, please contact the Site Administrator at support@redsealcreative.com This email has been sent to [user_email] Regards, All at IBEW Local 353' ); $pass_change_mail[ 'message' ] = $new_message_txt; return $pass_change_mail; } ``` As you can see I want to personalize the email message with their first and last name. What would be the best way to do this and would anyone be able to provide me with a example to start me off please.
The filter to use to modify the e-mail sent to a user when they change their *e-mail* address is `email_change_email`. Note that this is different from `password_change_email` which you've used in your original code. That filter allows you to modify the e-mail sent to the user when their *password* is changed. These two filters work similarly but it's important to make a distinction between the two. Both filters appear in `wp-includes/user.php`. * In the code below, we use the `email_change_email` to modify the message text. The new placeholders, `###FIRST_NAME###` and `###LAST_NAME###` have been added to the code (and docs) below. * The standard placeholders wherever possible in the message text, instead of hardcoding the strings. * Also, a text domain was added to the customized message text. It's always a good practice to add a text domain to strings that are passed to gettext functions ( `__()`, `_e()`, etc.). ``` /** * Filters the contents of the email sent when the user's email is changed. * * @param array $email_change_email { * Used to build wp_mail(). * @type string $to The intended recipients. * @type string $subject The subject of the email. * @type string $message The content of the email. * The following strings have a special meaning and will get replaced dynamically: * - ###USERNAME### The current user's username. * - ###FIRST_NAME### The current user's first name. * - ###LAST_NAME### The current user's last name. * - ###ADMIN_EMAIL### The admin email in case this was unexpected. * - ###EMAIL### The old email. * - ###SITENAME### The name of the site. * - ###SITEURL### The URL to the site. * @type string $headers Headers. * } * @param array $user The original user array. * @param array $userdata The updated user array. */ add_filter( 'email_change_email', 'red_email_change_email', 10, 3 ); function red_email_change_email( $email_change_email, $user, $userdata ) { $new_message_txt = __( 'Hi ###FIRST_NAME### ###LAST_NAME###, This notice confirms that your email was changed on ###SITENAME###. If you did not change your email, please contact the Site Administrator at ###ADMIN_EMAIL### This email has been sent to ###EMAIL### Regards, All at ###SITENAME###' ); $email_change_email['message'] = $new_message_txt; $email_change_email['message'] = str_replace( '###FIRST_NAME###', $user['first_name'], $email_change_email['message'] ); $email_change_email['message'] = str_replace( '###LAST_NAME###', $user['last_name'], $email_change_email['message'] ); // Debugging helper. Uncomment to turn on. // update_option( 'wpse_debug_email_change_email_user', $user ); return $email_change_email; } ``` Debugging --------- I've verified that this code does output the first and last names of the user. This information is coming from the user meta table, but it's already set up for us via the `$user` array by the core. I've manually replaced any personal info with`**REMOVED**`. Example e-mail: > > > ``` > Hi Dave (first name) Romsey (last name), > > This notice confirms that your email was changed on WP Theme Testing. > > If you did not change your email, please contact the Site Administrator at > **REMOVED** > > This email has been sent to **REMOVED** > > Regards, > All at WP Theme Testing > > ``` > > Here's the contents of the `$user` array: > > > ``` > Array > ( > [ID] => 1 > [user_login] => dave > [user_pass] => **REMOVED** > [user_nicename] => dave > [user_email] => **REMOVED** > [user_url] => http://example.com/ > [user_registered] => 2016-02-14 05:29:13 > [user_activation_key] => > [user_status] => 0 > [display_name] => dave > [first_name] => Dave (first name) > [last_name] => Romsey (last name) > [nickname] => dave > [description] => This is the author’s test! <a href=\"#\">test link</a> > [rich_editing] => true > [comment_shortcuts] => false > [admin_color] => fresh > [use_ssl] => 0 > [show_admin_bar_front] => true > [locale] => > ) > > ``` > > Here's a function that will display the `$user` array in the console of the admin area once the debugging line has been activated in the original code above. ``` /** * Debugging helper. Outputs $user array to console in admin area. * This data is saved via debugging line in red_email_change_email(). */ add_action( 'admin_head', 'wpse_debug_option' ); function wpse_debug_option() { $value = get_option( 'wpse_debug_email_change_email_user' ); echo '<script>console.log( ' . json_encode( $value ) . ');</script>'; } ```
269,336
<p>I am trying to locate the correct file to edit my internal linking anchor tags i.e.<code>&lt;a href=</code></p> <p>Can anyone point me to to the correct file? When I view the source code I see about 50 of them but I am not able to locate them in any files for editing????</p> <p>I have looked in Header, Footer, Functions and many other hooks but could not locate the anchor tags???</p>
[ { "answer_id": 269326, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You're already passing a <code>$user</code> object into your function, so you should be able to substitut...
2017/06/06
[ "https://wordpress.stackexchange.com/questions/269336", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117358/" ]
I am trying to locate the correct file to edit my internal linking anchor tags i.e.`<a href=` Can anyone point me to to the correct file? When I view the source code I see about 50 of them but I am not able to locate them in any files for editing???? I have looked in Header, Footer, Functions and many other hooks but could not locate the anchor tags???
The filter to use to modify the e-mail sent to a user when they change their *e-mail* address is `email_change_email`. Note that this is different from `password_change_email` which you've used in your original code. That filter allows you to modify the e-mail sent to the user when their *password* is changed. These two filters work similarly but it's important to make a distinction between the two. Both filters appear in `wp-includes/user.php`. * In the code below, we use the `email_change_email` to modify the message text. The new placeholders, `###FIRST_NAME###` and `###LAST_NAME###` have been added to the code (and docs) below. * The standard placeholders wherever possible in the message text, instead of hardcoding the strings. * Also, a text domain was added to the customized message text. It's always a good practice to add a text domain to strings that are passed to gettext functions ( `__()`, `_e()`, etc.). ``` /** * Filters the contents of the email sent when the user's email is changed. * * @param array $email_change_email { * Used to build wp_mail(). * @type string $to The intended recipients. * @type string $subject The subject of the email. * @type string $message The content of the email. * The following strings have a special meaning and will get replaced dynamically: * - ###USERNAME### The current user's username. * - ###FIRST_NAME### The current user's first name. * - ###LAST_NAME### The current user's last name. * - ###ADMIN_EMAIL### The admin email in case this was unexpected. * - ###EMAIL### The old email. * - ###SITENAME### The name of the site. * - ###SITEURL### The URL to the site. * @type string $headers Headers. * } * @param array $user The original user array. * @param array $userdata The updated user array. */ add_filter( 'email_change_email', 'red_email_change_email', 10, 3 ); function red_email_change_email( $email_change_email, $user, $userdata ) { $new_message_txt = __( 'Hi ###FIRST_NAME### ###LAST_NAME###, This notice confirms that your email was changed on ###SITENAME###. If you did not change your email, please contact the Site Administrator at ###ADMIN_EMAIL### This email has been sent to ###EMAIL### Regards, All at ###SITENAME###' ); $email_change_email['message'] = $new_message_txt; $email_change_email['message'] = str_replace( '###FIRST_NAME###', $user['first_name'], $email_change_email['message'] ); $email_change_email['message'] = str_replace( '###LAST_NAME###', $user['last_name'], $email_change_email['message'] ); // Debugging helper. Uncomment to turn on. // update_option( 'wpse_debug_email_change_email_user', $user ); return $email_change_email; } ``` Debugging --------- I've verified that this code does output the first and last names of the user. This information is coming from the user meta table, but it's already set up for us via the `$user` array by the core. I've manually replaced any personal info with`**REMOVED**`. Example e-mail: > > > ``` > Hi Dave (first name) Romsey (last name), > > This notice confirms that your email was changed on WP Theme Testing. > > If you did not change your email, please contact the Site Administrator at > **REMOVED** > > This email has been sent to **REMOVED** > > Regards, > All at WP Theme Testing > > ``` > > Here's the contents of the `$user` array: > > > ``` > Array > ( > [ID] => 1 > [user_login] => dave > [user_pass] => **REMOVED** > [user_nicename] => dave > [user_email] => **REMOVED** > [user_url] => http://example.com/ > [user_registered] => 2016-02-14 05:29:13 > [user_activation_key] => > [user_status] => 0 > [display_name] => dave > [first_name] => Dave (first name) > [last_name] => Romsey (last name) > [nickname] => dave > [description] => This is the author’s test! <a href=\"#\">test link</a> > [rich_editing] => true > [comment_shortcuts] => false > [admin_color] => fresh > [use_ssl] => 0 > [show_admin_bar_front] => true > [locale] => > ) > > ``` > > Here's a function that will display the `$user` array in the console of the admin area once the debugging line has been activated in the original code above. ``` /** * Debugging helper. Outputs $user array to console in admin area. * This data is saved via debugging line in red_email_change_email(). */ add_action( 'admin_head', 'wpse_debug_option' ); function wpse_debug_option() { $value = get_option( 'wpse_debug_email_change_email_user' ); echo '<script>console.log( ' . json_encode( $value ) . ');</script>'; } ```
269,358
<p>This is my careers first WordPress theme: <a href="http://codepen.trafficopedia.com/site01/" rel="nofollow noreferrer">Click Here</a>.</p> <p>If you search anything than the design breaks. Search for example this string → The Authors Name </p> <p>I could not understand why only search results breaks the design, and I remember 2 weeks back I think all this was working fine?</p> <p>Please let me Know if you need code. i think the code is not required so initially I am not posting the code.</p> <p>This is the code in <code>searchform.php</code>:</p> <pre><code>&lt;form role="search" method="get" class="search-form" action="&lt;?php echo home_url( '/' ); ?&gt;"&gt; &lt;label&gt; &lt;span class="screen-reader-text"&gt;&lt;?php echo _x( '', 'label','simplisto' ) ?&gt;&lt;/span&gt; &lt;input type="search" class="search-field" placeholder="&lt;?php echo esc_attr_x( 'Search', 'placeholder','simplisto' ) ?&gt;" value="&lt;?php echo get_search_query() ?&gt;" name="s" title="&lt;?php echo esc_attr_x( 'Search for:', 'label','simplisto' ) ?&gt;" /&gt; &lt;/label&gt; &lt;input type="submit" class="search-submit" value="&lt;?php echo esc_attr_x( 'Search', 'submit button','simplisto' ) ?&gt;" /&gt; &lt;/form&gt; </code></pre> <p>Please let me know if some other code is needed.</p>
[ { "answer_id": 269361, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Check out the markup. On the search results page, the <code>&lt;body&gt;</code> element is assigned the clas...
2017/06/07
[ "https://wordpress.stackexchange.com/questions/269358", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
This is my careers first WordPress theme: [Click Here](http://codepen.trafficopedia.com/site01/). If you search anything than the design breaks. Search for example this string → The Authors Name I could not understand why only search results breaks the design, and I remember 2 weeks back I think all this was working fine? Please let me Know if you need code. i think the code is not required so initially I am not posting the code. This is the code in `searchform.php`: ``` <form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>"> <label> <span class="screen-reader-text"><?php echo _x( '', 'label','simplisto' ) ?></span> <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search', 'placeholder','simplisto' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label','simplisto' ) ?>" /> </label> <input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button','simplisto' ) ?>" /> </form> ``` Please let me know if some other code is needed.
Check out the markup. On the search results page, the `<body>` element is assigned the classes `search` and `search-no-results`. ``` <body class="search search-no-results"> ``` Looking at the CSS, the styles for `.search` are intended to be used for the search input. They are working for that, but they are also being applied to the body due to the use of a weak selector: ``` .search { border: 1px solid #CCCCCC; padding: 5px 7px; /*margin-left: 15px;*/ width: 175px; -webkit-transition: all .5s ease; -moz-transition: all .5s ease; transition: all .5s ease; /*position: absolute;*/ right: 0; /*float: right;*/ } ``` That's no good. I'd update the selector to be more specific: ``` input.search { ... } ```
269,416
<p>I need to get only the custom posts which have <code>meta_key</code> <code>landing_exported</code> as <code>meta_value</code> <code>NULL</code>.</p> <p>I know that exists at least 2 custom posts in my database, but my code print "nothing found".</p> <pre><code>$args = array( 'post_type' =&gt; LANDING__CUSTOM_POST, 'meta_query' =&gt; array( array( 'key' =&gt; 'landing_exported', 'value' =&gt; false, 'type' =&gt; 'BOOLEAN' ) ) ); // query $the_query = new WP_Query( $args ); if( $the_query-&gt;have_posts() ) { // do funny things } else { echo 'nothing found'; } </code></pre>
[ { "answer_id": 269422, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>I am not sure where are you getting that <code>BOOLEAN</code> type from. I don’t think it is a type supported by <c...
2017/06/07
[ "https://wordpress.stackexchange.com/questions/269416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115372/" ]
I need to get only the custom posts which have `meta_key` `landing_exported` as `meta_value` `NULL`. I know that exists at least 2 custom posts in my database, but my code print "nothing found". ``` $args = array( 'post_type' => LANDING__CUSTOM_POST, 'meta_query' => array( array( 'key' => 'landing_exported', 'value' => false, 'type' => 'BOOLEAN' ) ) ); // query $the_query = new WP_Query( $args ); if( $the_query->have_posts() ) { // do funny things } else { echo 'nothing found'; } ```
I depends if you're looking for an empty value: ``` $args = array( 'post_type' => LANDING__CUSTOM_POST, 'meta_query' => array( array( 'key' => 'landing_exported', 'value' => '', 'compare' => '=' ) ) ); // query $the_query = new WP_Query( $args ); ``` which searches for value like: `meta_value = ''` or if you are looking for actually a `NULL` value which is more difficult (or I couldn't find an easier solution): ``` add_filter( 'posts_where', 'my_modify_the_posts_where' ); function lets_modify_the_posts_where( $clause = '' ) { global $wpdb; $clause .= " AND " . $wpdb->prefix . "postmeta.meta_value IS NULL" return $clause; } $args = array( 'post_type' => LANDING__CUSTOM_POST, 'meta_query' => array( array( 'key' => 'landing_exported', 'compare' => 'EXISTS' ) ) ); // query $the_query = new WP_Query( $args ); remove_filter('posts_where', 'my_modify_the_posts_where'); ``` which searches for value like: `meta_value IS NULL`
269,439
<p>I've been using the <code>document_title_parts</code> hook to change the page title for some front end pages. However, this doesn't seem to work for the login, register and password management pages.</p> <p>How can I change the wp-login.php page <code>&lt;title&gt;</code>?</p>
[ { "answer_id": 269446, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>It looks like it's not easily accessible as it's displayed as <sup><a href=\"https://github.com/WordPress/Word...
2017/06/07
[ "https://wordpress.stackexchange.com/questions/269439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
I've been using the `document_title_parts` hook to change the page title for some front end pages. However, this doesn't seem to work for the login, register and password management pages. How can I change the wp-login.php page `<title>`?
It looks like it's not easily accessible as it's displayed as [src](https://github.com/WordPress/WordPress/blob/1d34043e8cd2eead37048bc8aed379d57ff32408/wp-login.php#L69): ``` <title><?php echo get_bloginfo( 'name', 'display' ) . $separator . $title; ?></title> ``` where the separator is: ``` $separator = is_rtl() ? ' &rsaquo; ' : ' &lsaquo; '; ``` and the `$title` part comes from: ``` login_header( $title = 'Some title' , ... ); ``` But it looks like you've already checked this out, as I see you've filed a ticket [#40812](https://core.trac.wordpress.org/ticket/40812) for an extra filter to change the *separator*. A workaround that comes to mind, to change the *separator*, would be to use *output buffering* hacks to replace it.
269,468
<p>I am creating a child theme. I noticed my parent theme is adding some inline CSS in its functions.php:</p> <pre><code>wp_add_inline_style( 'persona-style-css', $custom_css ); </code></pre> <p>Since I cannot change some values there, is it possible to dequeue it? I have tried to dequeue it using <code>wp_dequeue_style ('persona-style-css')</code> but it didn't really help.</p> <p>Thanks in advance.</p>
[ { "answer_id": 269471, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>If <code>wp_add_inline_css</code> is fired within an action you can use <code>remove_action</code> with the sam...
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269468", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90981/" ]
I am creating a child theme. I noticed my parent theme is adding some inline CSS in its functions.php: ``` wp_add_inline_style( 'persona-style-css', $custom_css ); ``` Since I cannot change some values there, is it possible to dequeue it? I have tried to dequeue it using `wp_dequeue_style ('persona-style-css')` but it didn't really help. Thanks in advance.
If `wp_add_inline_css` is fired within an action you can use `remove_action` with the same parameters. You also might use `wp_enqueue_scripts` action to dequeue any scripts or styles in a proper way. But, inline style are not included in the `$wp_styles` global, you can unset them with the action `print_styles_array`, you need to know the handle name to unset it. Hope it gives you some hints to make it works.
269,486
<p>I have added following code in my theme functions.php </p> <pre><code>function my_loginlcustomization() { wp_register_style('custom_loginstyle', get_template_directory_uri() . '/login/login-styles.css', __FILE__); wp_enqueue_style('custom_loginstyle'); } add_action('login_head', 'my_loginlcustomization'); </code></pre> <p>Custom login page:</p> <pre><code>&lt;?php /* Template Name: Login */ ?&gt; &lt;!DOCTYPE html&gt; &lt;html &gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Login Form&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php wp_login_form(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>But no effect on page.</p>
[ { "answer_id": 269471, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>If <code>wp_add_inline_css</code> is fired within an action you can use <code>remove_action</code> with the sam...
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269486", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95126/" ]
I have added following code in my theme functions.php ``` function my_loginlcustomization() { wp_register_style('custom_loginstyle', get_template_directory_uri() . '/login/login-styles.css', __FILE__); wp_enqueue_style('custom_loginstyle'); } add_action('login_head', 'my_loginlcustomization'); ``` Custom login page: ``` <?php /* Template Name: Login */ ?> <!DOCTYPE html> <html > <head> <meta charset="UTF-8"> <title>Login Form</title> </head> <body> <?php wp_login_form(); ?> </body> </html> ``` But no effect on page.
If `wp_add_inline_css` is fired within an action you can use `remove_action` with the same parameters. You also might use `wp_enqueue_scripts` action to dequeue any scripts or styles in a proper way. But, inline style are not included in the `$wp_styles` global, you can unset them with the action `print_styles_array`, you need to know the handle name to unset it. Hope it gives you some hints to make it works.
269,529
<p>After reading several posts regarding post category manipulation with a given time I wanted to create a plugin that would manipulate posts after a date. My original post reference is from six years ago: "<a href="https://wordpress.stackexchange.com/questions/7571/plugin-for-changing-a-posts-category-based-on-its-post-date">Plugin for changing a post's category based on it's post date?</a>" but I've referenced several posts regarding manipulation:</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/157253/i-need-to-bulk-update-all-wordpress-posts-on-a-scheduled-time">I need to bulk update all wordpress posts on a scheduled time</a></li> <li><a href="https://wordpress.stackexchange.com/questions/268239/how-can-i-hide-posts-that-are-over-2-years-old">How can I hide posts that are over 2 years old</a></li> </ul> <p>However it isn't removing the category and adding the new one:</p> <p><strong>Code:</strong></p> <pre><code>function check_if_cat_has_reached_time() { // test if term exists and if doesn't return $test_term1 = term_exists('Uncategorized', 'category'); if ($test_term1 !== 0 &amp;&amp; $test_term1 !== null) : // $default_cat = get_term_by('id', 'Uncategorized', 'category'); $default_cat = get_cat_ID('uncategorized'); else : return; endif; // test if term exists and if doesn't return $test_term2 = term_exists('failed', 'category'); if ($test_term2 !== 0 &amp;&amp; $test_term2 !== null) : $new_cat = get_cat_ID('failed'); else : return; endif; global $post; // the Post ID $the_ID = $post-&gt;ID; // Post creation time in epoch // $post_creation = get_the_time('U',$the_ID); // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time &gt;= $post_plus_two &amp;&amp; has_category($default_cat,$the_ID)) : wp_remove_object_terms($the_ID, $default_cat, 'category'); $update_post_cat = array( 'post_category' =&gt; array($new_cat), ); wp_insert_post($update_post_cat); endif; } add_action('save_post', 'check_if_cat_has_reached_time'); </code></pre> <p>Is there a reason why <code>wp_remove_object_terms()</code> doesn't work? I used this after reading <a href="https://wordpress.stackexchange.com/questions/135602/remove-specific-category-from-a-post">Remove specific category from a post</a>. </p> <p>So my questions are:</p> <ul> <li>Am I removing the category correctly?</li> <li>Am I updating the category correctly?</li> <li>Is there better hook for manipulating posts in a plugin?</li> <li>Would there be any performance issues if this was implemented on a site that had several thousand posts?</li> </ul> <hr> <p><strong>EDIT:</strong></p> <p>The below answer I've tried to implement in my theme's function.php but it still doesn't work. I'm using a default theme with <a href="http://wptest.io/" rel="nofollow noreferrer">WP Test</a>. Before the function I make sure to create the categories with:</p> <pre><code>function create_foo_category() { wp_insert_term( 'Foo', 'category', array( 'description' =&gt; 'This is the Foo', 'slug' =&gt; 'foo' ) ); } add_action('after_setup_theme', 'create_foo_category'); </code></pre> <p>then for <code>bar</code>:</p> <pre><code>function create_bar_category() { wp_insert_term( 'Bar', 'category', array( 'description' =&gt; 'This is the bar', 'slug' =&gt; 'bar' ) ); } add_action('after_setup_theme', 'create_bar_category'); </code></pre> <p>I tried to manipulate the provided answer with:</p> <pre><code>function check_if_cat_has_reached_time() { global $post; $the_ID = $post-&gt;ID; if (!wp_is_post_revision($the_ID)) { // unhook this function so it doesn't loop infinitely remove_action('save_post', 'check_if_cat_has_reached_time'); // test if term exists and if doesn't return $check_default_cat = term_exists('Foo', 'category'); if ($check_default_cat !== 0 &amp;&amp; $check_default_cat !== null) { $default_cat = get_cat_ID('foo'); } else { return; } // test if term exists and if doesn't return $check_new_cat = term_exists('Bar', 'category'); if ($check_new_cat !== 0 &amp;&amp; $check_new_cat !== null) { $new_cat = get_cat_ID('bar'); } else { return; } // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time &gt;= $post_plus_two &amp;&amp; has_category($default_cat,$the_ID)) { wp_remove_object_terms($the_ID, $default_cat, 'category'); $args = array( 'ID' =&gt; $the_ID, 'post_category' =&gt; array($new_cat), ); wp_update_post($args); } // re-hook this function add_action('save_post', 'check_if_cat_has_reached_time'); } } add_action('publish_post', 'check_if_cat_has_reached_time'); </code></pre> <hr> <p><strong>EDIT:</strong></p> <p>After talking to a few people I think it was somewhat unclear what the intended purpose of the above was for. I'm looking to modify the posts without actually going into them with something like an event daily. After discussing this issue further I was made aware of <a href="https://developer.wordpress.org/reference/functions/wp_schedule_event/" rel="nofollow noreferrer"><code>wp_schedule_event()</code></a> that I'm going to test out and edit. </p>
[ { "answer_id": 269471, "author": "Benoti", "author_id": 58141, "author_profile": "https://wordpress.stackexchange.com/users/58141", "pm_score": 3, "selected": true, "text": "<p>If <code>wp_add_inline_css</code> is fired within an action you can use <code>remove_action</code> with the sam...
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
After reading several posts regarding post category manipulation with a given time I wanted to create a plugin that would manipulate posts after a date. My original post reference is from six years ago: "[Plugin for changing a post's category based on it's post date?](https://wordpress.stackexchange.com/questions/7571/plugin-for-changing-a-posts-category-based-on-its-post-date)" but I've referenced several posts regarding manipulation: * [I need to bulk update all wordpress posts on a scheduled time](https://wordpress.stackexchange.com/questions/157253/i-need-to-bulk-update-all-wordpress-posts-on-a-scheduled-time) * [How can I hide posts that are over 2 years old](https://wordpress.stackexchange.com/questions/268239/how-can-i-hide-posts-that-are-over-2-years-old) However it isn't removing the category and adding the new one: **Code:** ``` function check_if_cat_has_reached_time() { // test if term exists and if doesn't return $test_term1 = term_exists('Uncategorized', 'category'); if ($test_term1 !== 0 && $test_term1 !== null) : // $default_cat = get_term_by('id', 'Uncategorized', 'category'); $default_cat = get_cat_ID('uncategorized'); else : return; endif; // test if term exists and if doesn't return $test_term2 = term_exists('failed', 'category'); if ($test_term2 !== 0 && $test_term2 !== null) : $new_cat = get_cat_ID('failed'); else : return; endif; global $post; // the Post ID $the_ID = $post->ID; // Post creation time in epoch // $post_creation = get_the_time('U',$the_ID); // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time >= $post_plus_two && has_category($default_cat,$the_ID)) : wp_remove_object_terms($the_ID, $default_cat, 'category'); $update_post_cat = array( 'post_category' => array($new_cat), ); wp_insert_post($update_post_cat); endif; } add_action('save_post', 'check_if_cat_has_reached_time'); ``` Is there a reason why `wp_remove_object_terms()` doesn't work? I used this after reading [Remove specific category from a post](https://wordpress.stackexchange.com/questions/135602/remove-specific-category-from-a-post). So my questions are: * Am I removing the category correctly? * Am I updating the category correctly? * Is there better hook for manipulating posts in a plugin? * Would there be any performance issues if this was implemented on a site that had several thousand posts? --- **EDIT:** The below answer I've tried to implement in my theme's function.php but it still doesn't work. I'm using a default theme with [WP Test](http://wptest.io/). Before the function I make sure to create the categories with: ``` function create_foo_category() { wp_insert_term( 'Foo', 'category', array( 'description' => 'This is the Foo', 'slug' => 'foo' ) ); } add_action('after_setup_theme', 'create_foo_category'); ``` then for `bar`: ``` function create_bar_category() { wp_insert_term( 'Bar', 'category', array( 'description' => 'This is the bar', 'slug' => 'bar' ) ); } add_action('after_setup_theme', 'create_bar_category'); ``` I tried to manipulate the provided answer with: ``` function check_if_cat_has_reached_time() { global $post; $the_ID = $post->ID; if (!wp_is_post_revision($the_ID)) { // unhook this function so it doesn't loop infinitely remove_action('save_post', 'check_if_cat_has_reached_time'); // test if term exists and if doesn't return $check_default_cat = term_exists('Foo', 'category'); if ($check_default_cat !== 0 && $check_default_cat !== null) { $default_cat = get_cat_ID('foo'); } else { return; } // test if term exists and if doesn't return $check_new_cat = term_exists('Bar', 'category'); if ($check_new_cat !== 0 && $check_new_cat !== null) { $new_cat = get_cat_ID('bar'); } else { return; } // current time in epoch $current_time = time(); // two years in epoch $two_years = 31556926*2; // post time plus two years $post_plus_two = (int)$two_years + (int)get_the_time('U',$the_ID); if ($current_time >= $post_plus_two && has_category($default_cat,$the_ID)) { wp_remove_object_terms($the_ID, $default_cat, 'category'); $args = array( 'ID' => $the_ID, 'post_category' => array($new_cat), ); wp_update_post($args); } // re-hook this function add_action('save_post', 'check_if_cat_has_reached_time'); } } add_action('publish_post', 'check_if_cat_has_reached_time'); ``` --- **EDIT:** After talking to a few people I think it was somewhat unclear what the intended purpose of the above was for. I'm looking to modify the posts without actually going into them with something like an event daily. After discussing this issue further I was made aware of [`wp_schedule_event()`](https://developer.wordpress.org/reference/functions/wp_schedule_event/) that I'm going to test out and edit.
If `wp_add_inline_css` is fired within an action you can use `remove_action` with the same parameters. You also might use `wp_enqueue_scripts` action to dequeue any scripts or styles in a proper way. But, inline style are not included in the `$wp_styles` global, you can unset them with the action `print_styles_array`, you need to know the handle name to unset it. Hope it gives you some hints to make it works.
269,570
<p>If you have like 20 text box widgets and you are using widget logic or something to selectively display them on various pages, it gets confusing what content is in each box IF you are not using the title box. they will all then just say "text."</p> <p>Would be nice if the text widgets had a descriptive field where you can enter a title that the system will not display, but users can identify what code or text is in a particular text widget. I hope this makes sense.</p> <p>is there a way to do this that I can't see?</p> <p>I know I can enter a title and then remove all titles with CSS, but I want to display some titles.</p> <p>I feel there is a way</p>
[ { "answer_id": 269577, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>It looks like the suggestion by @DaveRomsey will solve the problem. </p>\n\n<p>Another simple idea is from a ...
2017/06/08
[ "https://wordpress.stackexchange.com/questions/269570", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121412/" ]
If you have like 20 text box widgets and you are using widget logic or something to selectively display them on various pages, it gets confusing what content is in each box IF you are not using the title box. they will all then just say "text." Would be nice if the text widgets had a descriptive field where you can enter a title that the system will not display, but users can identify what code or text is in a particular text widget. I hope this makes sense. is there a way to do this that I can't see? I know I can enter a title and then remove all titles with CSS, but I want to display some titles. I feel there is a way
It looks like the suggestion by @DaveRomsey will solve the problem. Another simple idea is from a [plugin](https://wordpress.org/plugins/remove-widget-titles/) by [Stephen Cronin](https://profiles.wordpress.org/stephencronin), (*I'm not related to that plugin in any way.*) that uses the `widget_title` filter: ``` add_filter( 'widget_title', function( $title ) { return '!' === mb_substr ( $title, 0, 1 ) ? '' : $title; } ); ``` where I've adjusted the code a little bit. It simply removes the widget's title if it starts with `!`. This is handy for e.g. Text Widgets containing ads where we don't want the widget's title to display on the front-end. This approach makes it easier to manage the widgets as we can still see their titles in the backend. Hope it helps!
269,579
<p>I have a post that contain images, let's say image with id 19, 12, 10. I attach image 19 first, 12 below the first and 10 as the last, and I need to retrieve them. I </p> <pre><code>$post_images = get_children( array( 'post_parent' =&gt; $id, 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', )); </code></pre> <p>But i receive them sorted by id (10,12,19), how i get them with the order as i needed</p>
[ { "answer_id": 269580, "author": "Jared Cobb", "author_id": 6737, "author_profile": "https://wordpress.stackexchange.com/users/6737", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_children\" rel=\"nofollow noreferrer\">The docu...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121420/" ]
I have a post that contain images, let's say image with id 19, 12, 10. I attach image 19 first, 12 below the first and 10 as the last, and I need to retrieve them. I ``` $post_images = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', )); ``` But i receive them sorted by id (10,12,19), how i get them with the order as i needed
[The documentation for `get_children`](https://codex.wordpress.org/Function_Reference/get_children) isn't great (at the time of this answer), however `get_children` is simply a wrapper for [`get_posts()`](https://codex.wordpress.org/Template_Tags/get_posts). This means that `orderby` and `order` are valid arguments for your query. When you ask, "*how i get them with the order as i needed*", is the property you wish to order them by a [valid `orderby` value](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters)? If so, your function call might look like this: ``` $post_images = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'title' 'order' => 'ASC', )); ```
269,606
<p>I have a custom div (holder for extra settings) which I need to load some specific controls from a specific section in there. I can get the controls in JavaScript but I can't generate the necessary HTML as WordPress do in sections.</p> <pre><code>wp.customize.section( 'custom_div_1' ).controls(); </code></pre> <p>It gives an array of controls but how to generate the HTML like <strong>Site title</strong> or <strong>Tagline</strong> controls in default WordPress section.</p> <p>This custom div will toggle by the left button <strong>Open extra settings</strong>.</p> <p>Screenshot for easier understanding:<a href="https://i.stack.imgur.com/scfZA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/scfZA.jpg" alt="screenshot"></a></p> <p>Any help is appreciated.</p>
[ { "answer_id": 269601, "author": "hilaryk", "author_id": 121431, "author_profile": "https://wordpress.stackexchange.com/users/121431", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/qt38l.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgu...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269606", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24688/" ]
I have a custom div (holder for extra settings) which I need to load some specific controls from a specific section in there. I can get the controls in JavaScript but I can't generate the necessary HTML as WordPress do in sections. ``` wp.customize.section( 'custom_div_1' ).controls(); ``` It gives an array of controls but how to generate the HTML like **Site title** or **Tagline** controls in default WordPress section. This custom div will toggle by the left button **Open extra settings**. Screenshot for easier understanding:[![screenshot](https://i.stack.imgur.com/scfZA.jpg)](https://i.stack.imgur.com/scfZA.jpg) Any help is appreciated.
[![enter image description here](https://i.stack.imgur.com/Tp9QG.jpg)](https://i.stack.imgur.com/Tp9QG.jpg) Here is how it looks like at my end. I have checked it in chrome, mozilla and IE as well. It look fine in all browsers.
269,612
<p>I need to show the various content of a post in a modal overlay.</p> <p>How do I call Wordpress through AJAX from the front end (directly from a .js file), using the classic jQuery method?</p> <pre><code>$.ajax({ 'url' : ? data : { 'id' : 247 &lt;-- post ID } ... }); </code></pre> <p>This is NOT a PHP file, so no:</p> <p><code>admin_url('admin-ajax.php?action=my_action&amp;post_id='.$post-&gt;ID.'&amp;nonce='.$nonce);</code></p> <p>Or?</p>
[ { "answer_id": 269623, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": true, "text": "<p>You can output your javascript via <code>wp_add_inline_script()</code>. This way you can set the post's id a...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269612", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120374/" ]
I need to show the various content of a post in a modal overlay. How do I call Wordpress through AJAX from the front end (directly from a .js file), using the classic jQuery method? ``` $.ajax({ 'url' : ? data : { 'id' : 247 <-- post ID } ... }); ``` This is NOT a PHP file, so no: `admin_url('admin-ajax.php?action=my_action&post_id='.$post->ID.'&nonce='.$nonce);` Or?
You can output your javascript via `wp_add_inline_script()`. This way you can set the post's id and AJAX URL before outputting the code: ``` wp_add_inline_script('my-js', ' jQuery.ajax({ \'url\' : '.admin_url('admin-ajax.php?action=my_action').' data : { \'id\' : '.get_the_ID().' } });'); ``` Note that you need to hook to an existing js file to be able to add inline script, so `my-js` must be a valid enqueued script.
269,625
<p>How can i put a youtube video on my post without show the default title from youtube?</p> <p>I tried to put this code in the theme´s functions, but not worked.</p> <pre><code>function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\"&gt;s]*)@", "src=$1$2&amp;showinfo=0&amp;rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls'); </code></pre> <p>Someone can help?</p> <p>Thanks</p>
[ { "answer_id": 269732, "author": "Bikash Waiba", "author_id": 121069, "author_profile": "https://wordpress.stackexchange.com/users/121069", "pm_score": -1, "selected": true, "text": "<p>Update: Try this one.. it works for youtube url in your post which is converted to iframe by wordpress...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269625", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116787/" ]
How can i put a youtube video on my post without show the default title from youtube? I tried to put this code in the theme´s functions, but not worked. ``` function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\">s]*)@", "src=$1$2&showinfo=0&rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls'); ``` Someone can help? Thanks
Update: Try this one.. it works for youtube url in your post which is converted to iframe by wordpress. ``` function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\">]*)@", "src=$1$2&showinfo=0&rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls'); ```
269,627
<p>I need to make WordPress call a specific REST endpoint when a new post is published, passing the most important post data via JSON.</p> <p>I found a plugin, HookPress, that apparently did just that by letting you configure webhooks for various events. Unfortunately it has not been updated in over 2 years and does not work with recent versions of Wordpress (>4.6).</p> <p>Is there any way I can achieve this?</p>
[ { "answer_id": 269633, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>You can use a post status transition hook. In this case, it sounds like {status}_{post_type} may be the m...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269627", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121459/" ]
I need to make WordPress call a specific REST endpoint when a new post is published, passing the most important post data via JSON. I found a plugin, HookPress, that apparently did just that by letting you configure webhooks for various events. Unfortunately it has not been updated in over 2 years and does not work with recent versions of Wordpress (>4.6). Is there any way I can achieve this?
You don't have to write a new plugin. You can either add the code to your theme's `functions.php` file, or create a [child theme](https://codex.wordpress.org/Child_Themes). To wrap your data in a JSON format, you can use the `json_encode` function. Hook into the post when it's published, and send the data. In the following function, i will send the post's title, excerpt and featured image URL to the endpoint. ``` add_action('publish_post', 'call_the_endpoint',10,2); function call_the_endpoint($post_id, $post){ // Define an empty array $data = array(); // Store the title into the array $data['title'] = get_the_title(); // If there is a post thumbnail, get the link if (has_post_thumbnail()) { $data['thumbnail'] = get_the_post_thumbnail_url( get_the_ID(),'thumbnail' ); } // Get the excerpt and save it into the array $data['excerpt'] = get_the_excerpt(); // Encode the data to be sent $json_data = json_encode($data); // Initiate the cURL $url = curl_init('YOUR API URL HERE'); curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($url, CURLOPT_POSTFIELDS, $json_data); curl_setopt($url, CURLOPT_RETURNTRANSFER, true); curl_setopt($url, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($json_data)) ); // The results of our request, to use later if we want. $result = curl_exec($url); } ``` It would be possible to write an accurate answer if you could provide more information about your API and how you interact with it. However this was a simple example for you to know how to use the `publish_post` hook to achieve what you are looking for.
269,629
<p>I'm stuck right now. For my project, I have to create login not using WP user system but another system. </p> <p>Now, when with my system API login, I created some cookie but, obviously I didn't also create wp cookie for user logged in. So, I want to allow a user upload with media library of WP (<a href="https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/" rel="nofollow noreferrer">link of WP codex</a>) some files, but it doesn't work.</p> <p>I have also edited (temporary core wordpress change) admin-ajax.php for forcing it to create post attachment also in the case of user not logged in:</p> <pre><code>if ( is_user_logged_in() ) { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } else { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } </code></pre> <p>but async-upload.php responds with 302 and I don't know how to go forward.</p> <p><strong><em>UPDATE</em></strong>:<br> the problem is the same of this user: <a href="https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/" rel="nofollow noreferrer">click here</a></p> <p>I tried to use wp_ajax_my_action and wp_ajax_nopriv_myaction but nothing change. My need is allow to not logged user in WP to upload attachment, and assign this attachment with his ID author (for example, 12345), cause each user must see only yours media (i will use pre_get_posts and yet work). </p>
[ { "answer_id": 269640, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 1, "selected": false, "text": "<p>First, you do not want to edit core WP files, because your changes will disappear when there's an update. That'...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110442/" ]
I'm stuck right now. For my project, I have to create login not using WP user system but another system. Now, when with my system API login, I created some cookie but, obviously I didn't also create wp cookie for user logged in. So, I want to allow a user upload with media library of WP ([link of WP codex](https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/)) some files, but it doesn't work. I have also edited (temporary core wordpress change) admin-ajax.php for forcing it to create post attachment also in the case of user not logged in: ``` if ( is_user_logged_in() ) { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } else { do_action( 'wp_ajax_' . $_REQUEST['action'] ); } ``` but async-upload.php responds with 302 and I don't know how to go forward. ***UPDATE***: the problem is the same of this user: [click here](https://wordpress.org/support/topic/allow-media-uploader-while-not-logged-in/) I tried to use wp\_ajax\_my\_action and wp\_ajax\_nopriv\_myaction but nothing change. My need is allow to not logged user in WP to upload attachment, and assign this attachment with his ID author (for example, 12345), cause each user must see only yours media (i will use pre\_get\_posts and yet work).
First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes. Second, you may want to peruse this [Codex page](https://codex.wordpress.org/AJAX_in_Plugins) on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in): ``` add_action( 'wp_ajax_my_action', 'my_action' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); ``` The `my_action` function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX). Hope this starts you down the right path.
269,639
<p>I want to have one header page for the front page of the site and all other pages that follow by clicking "next" and a different header for all other pages, categories, articles, etc. on the site. Is there a way to do this within the header.php file or do I have to do something differently?</p> <p>I'm using a free theme for the backbone of the site and have implemented a child theme to create a unique header as well as add functions separately so that I don't lose changes when the parent theme is updated, so I have minimal space to maneuver in order to affect these changes.</p>
[ { "answer_id": 269640, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 1, "selected": false, "text": "<p>First, you do not want to edit core WP files, because your changes will disappear when there's an update. That'...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100669/" ]
I want to have one header page for the front page of the site and all other pages that follow by clicking "next" and a different header for all other pages, categories, articles, etc. on the site. Is there a way to do this within the header.php file or do I have to do something differently? I'm using a free theme for the backbone of the site and have implemented a child theme to create a unique header as well as add functions separately so that I don't lose changes when the parent theme is updated, so I have minimal space to maneuver in order to affect these changes.
First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes. Second, you may want to peruse this [Codex page](https://codex.wordpress.org/AJAX_in_Plugins) on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in): ``` add_action( 'wp_ajax_my_action', 'my_action' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); ``` The `my_action` function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX). Hope this starts you down the right path.
269,644
<p>I'm having a hard time figuring out why my repeatable fields javascript doesn't work. I'm using the following plugin: Rhyzz (repeatable-fields): <a href="http://www.rhyzz.com/repeatable-fields.html" rel="nofollow noreferrer">http://www.rhyzz.com/repeatable-fields.html</a>. I scraped the website and I see he ran the script inside html and also ran his javascript all on the same page. My website is a lot larger. I'm using Wordpress and I did the following to call the script in <code>functions.php</code>.</p> <pre><code> wp_enqueue_script( 'jquery', 'https://code.jquery.com/jquery-1.11.2.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-ui', 'https://code.jquery.com/ui/1.11.4/jquery-ui.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-repeatable', get_template_directory_uri() . '/js/repeatable.js', array( 'jquery', 'jquery-ui' ), '20120206', true ); </code></pre> <p>I also have about another 10 scripts. The files are all in the proper directories. I then have a particular page on my site (PHP) implementing the repeatable fields, but none of the buttons work. I don't have the following anywhere, and I don't know if it's necessary, but on Rhyzz's site he puts it in his HTML: </p> <pre><code>jQuery(function() { jQuery('.repeat').each(function() { jQuery(this).repeatable_fields(); }); }); </code></pre> <p>I'm very frustrated and don't know what to do. I also don't know if I'm enqueueing the script properly, as in if I should pass in jquery and jquery-ui into the array field. If anyone can help me with this please do so!</p> <p>Note: This is Rhyzz's GitHub with a tutorial on how to implement in HTML, <a href="https://github.com/Rhyzz/repeatable-fields" rel="nofollow noreferrer">https://github.com/Rhyzz/repeatable-fields</a>.</p>
[ { "answer_id": 269640, "author": "scott", "author_id": 93587, "author_profile": "https://wordpress.stackexchange.com/users/93587", "pm_score": 1, "selected": false, "text": "<p>First, you do not want to edit core WP files, because your changes will disappear when there's an update. That'...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269644", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121469/" ]
I'm having a hard time figuring out why my repeatable fields javascript doesn't work. I'm using the following plugin: Rhyzz (repeatable-fields): <http://www.rhyzz.com/repeatable-fields.html>. I scraped the website and I see he ran the script inside html and also ran his javascript all on the same page. My website is a lot larger. I'm using Wordpress and I did the following to call the script in `functions.php`. ``` wp_enqueue_script( 'jquery', 'https://code.jquery.com/jquery-1.11.2.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-ui', 'https://code.jquery.com/ui/1.11.4/jquery-ui.min.js', array(), '20120206', true ); wp_enqueue_script( 'jquery-repeatable', get_template_directory_uri() . '/js/repeatable.js', array( 'jquery', 'jquery-ui' ), '20120206', true ); ``` I also have about another 10 scripts. The files are all in the proper directories. I then have a particular page on my site (PHP) implementing the repeatable fields, but none of the buttons work. I don't have the following anywhere, and I don't know if it's necessary, but on Rhyzz's site he puts it in his HTML: ``` jQuery(function() { jQuery('.repeat').each(function() { jQuery(this).repeatable_fields(); }); }); ``` I'm very frustrated and don't know what to do. I also don't know if I'm enqueueing the script properly, as in if I should pass in jquery and jquery-ui into the array field. If anyone can help me with this please do so! Note: This is Rhyzz's GitHub with a tutorial on how to implement in HTML, <https://github.com/Rhyzz/repeatable-fields>.
First, you do not want to edit core WP files, because your changes will disappear when there's an update. That's why you are encouraged to create child themes. Second, you may want to peruse this [Codex page](https://codex.wordpress.org/AJAX_in_Plugins) on AJAX. Note that it shows how to handle both kinds of users (logged in and not logged in): ``` add_action( 'wp_ajax_my_action', 'my_action' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); ``` The `my_action` function would go in your theme files (when I was working on mine, I created my own plugin to handle AJAX). Hope this starts you down the right path.
269,645
<p>I am using this code below to specify a post template for a specific category in my functions.php file.</p> <pre><code>function get_custom_cat_template($single_template) { global $post; if ( in_category( 'ms-conversations' )) { $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ; </code></pre> <p>The code technically works, however I need to specify about 20 categories for that same post template.</p> <p>When I copy and paste the code again and again I get this fatal error because I am declaring it twice, but I do not know how to include all of the categories I need.</p> <pre><code>Fatal error: Cannot redeclare get_custom_cat_template() (previously declared in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php:152) in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php on line 174 </code></pre> <p>Here is a list of all the categories I need for that post template.</p> <p>ms-conversations, artist-of-the-month, exercise, hiking-for-multiple-sclerosis, msaa, caregiving-msaa, updates, ms-resources, ms-tips-msaa, recipe-of-the-month, stories-to-inspire, well-being, guest-bloggers, ms-publications, videos, multiplesclerosis-net, sharkfest, surveys, swim-for-ms, the-motivator</p> <p>When I try to use commas or &amp; signs to separate the categories I get further errors, how do I declare multiple categories for this chunk of code?</p> <p>Thank you.</p>
[ { "answer_id": 269647, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You don't need multiple functions. Use an <code>array</code> with <code>in_category</code> to pass multiple slugs:...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269645", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78325/" ]
I am using this code below to specify a post template for a specific category in my functions.php file. ``` function get_custom_cat_template($single_template) { global $post; if ( in_category( 'ms-conversations' )) { $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ; ``` The code technically works, however I need to specify about 20 categories for that same post template. When I copy and paste the code again and again I get this fatal error because I am declaring it twice, but I do not know how to include all of the categories I need. ``` Fatal error: Cannot redeclare get_custom_cat_template() (previously declared in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php:152) in /home/content/12/9195112/html/wp-hoff-testing/wp-content/themes/dw-focus/functions.php on line 174 ``` Here is a list of all the categories I need for that post template. ms-conversations, artist-of-the-month, exercise, hiking-for-multiple-sclerosis, msaa, caregiving-msaa, updates, ms-resources, ms-tips-msaa, recipe-of-the-month, stories-to-inspire, well-being, guest-bloggers, ms-publications, videos, multiplesclerosis-net, sharkfest, surveys, swim-for-ms, the-motivator When I try to use commas or & signs to separate the categories I get further errors, how do I declare multiple categories for this chunk of code? Thank you.
This is my final code. ``` function get_custom_cat_template($single_template) { global $post; if( in_category( array( 'ms-conversations', 'artist-of-the-month', 'exercise', 'hiking-for-multiple-sclerosis', 'msaa', 'caregiving-msaa', 'updates', 'ms-resources', 'ms-tips-msaa', 'recipe-of-the-month', 'stories-to-inspire', 'well-being', 'guest-bloggers', 'ms-publications', 'videos', 'multiplesclerosis-net', 'sharkfest', 'surveys', 'swim-for-ms', 'the-motivator' ) ) ){ $single_template = dirname( __FILE__ ) . '/CUSTOM-POST-BLOG-POST.php'; } return $single_template; } add_filter( "single_template", "get_custom_cat_template" ) ; ```
269,656
<p>How can I retrieve the values ​​passed to the shortcode using only one parameter?</p> <p>Example:</p> <pre><code>[related type="2,3,4,5,6"] </code></pre> <p>Is it possible to do that?</p>
[ { "answer_id": 269657, "author": "JItendra Rana", "author_id": 87433, "author_profile": "https://wordpress.stackexchange.com/users/87433", "pm_score": 1, "selected": false, "text": "<p>You can pass a JSON object in a short code:</p>\n\n<pre><code>[related values='{\"a\":\"foo\",\"b\":\"b...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269656", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121477/" ]
How can I retrieve the values ​​passed to the shortcode using only one parameter? Example: ``` [related type="2,3,4,5,6"] ``` Is it possible to do that?
The solution below will parse the comma separated values passed to the shortcode's `type` parameter. We'll also strip out any whitespace surrounding the values which is a usability improvement (see example 2 after the code below). ``` add_shortcode( 'related', 'wpse_related' ); function wpse_related( $atts, $content = '' ) { // User provided values are stored in $atts. // Default values are passed to shortcode_atts() below. // Merged values are stored in the $a array. $a = shortcode_atts( [ 'type' => false, ], $atts ); $output = ''; if ( $a['type'] ) { // Parse type into an array. Whitespace will be stripped. $a['type'] = array_map( 'trim', str_getcsv( $a['type'], ',' ) ); } // Debugging: Display the type parameter as a formatted array. $output .= '<pre>' . print_r( $a['type'], true ) . '</pre>'; return $output; } ``` **Example 1:** ``` [related type="2,3,4,5,6"] ``` **Output:** ``` Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 ) ``` **Example 2:** ``` [related type="8, 6, 7,5,30, 9"] ``` **Output:** ``` Array ( [0] => 8 [1] => 6 [2] => 7 [3] => 5 [4] => 30 [5] => 9 ) ```
269,676
<p>I would like to update a post on every new comment, so that the <code>Last Modified Date</code> is always up to date on the sitemap.</p> <p>How can i do this?</p> <p>Thanks.</p>
[ { "answer_id": 269686, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>That may change the order of posts on your main page, depending on your theme. </p>\n\n<p>There are wa...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269676", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117210/" ]
I would like to update a post on every new comment, so that the `Last Modified Date` is always up to date on the sitemap. How can i do this? Thanks.
From what i understand, you want to change the post's modification time whenever a comment is left on your post. For this, you need to hook into the `wp_insert_comment` hook and update the post's date manually: ``` add_action('wp_insert_comment','update_post_time',99,2); function update_post_time($comment_id, $comment_object) { // Get the post's ID $post_id = $comment_object->comment_post_ID; // Double check for post's ID, since this value is mandatory in wp_update_post() if ($post_id) { // Get the current time $time = current_time('mysql'); // Form an array of data to be updated $post_data = array( 'ID' => $post_id, 'post_modified' => $time, 'post_modified_gmt' => get_gmt_from_date( $time ) ); // Update the post wp_update_post( $post_data ); } } ``` Note that this will create a revision for the post each time a comment is created. If your sitemap plugin uses the `post_date` instead of `post_modified`, you can use this instead: ``` $post_data = array( 'ID' => $post_id, 'post_date' => $time, 'post_date_gmt' => get_gmt_from_date( $time ) ); ``` However, this might cause problems, and mess post's order in archives and homepage, since it changes the post's **creation** date, not modification date.
269,679
<p>I'm in trouble with Bootstrap and Wordpress.</p> <p>I want to get Taxonomy list to expand (show custom posts from Taxonomy). But it is hard!!!!</p> <p>Its basically a custom sidebar</p> <p>My code:</p> <pre><code>&lt;h3&gt; Portfólio &lt;/h3&gt; &lt;?php $catprod = get_terms( array( 'taxonomy' =&gt; 'categoria-produto', 'order' =&gt; 'DESC' )); // Todas as categorias $args = array( 'post_type' =&gt; 'produto' ); $prodtype = new WP_Query($args); ?&gt; &lt;div class="panel-group"&gt; &lt;div class="panel-heading"&gt; &lt;?php foreach( $catprod as $cat ) { ?&gt; &lt;h3 class="panel-title"&gt; &lt;a data-toggle="collapse" href="#&lt;?php echo $cat-&gt;slug ?&gt;" class="accordion-toggle" data-parent="#accordion"&gt; &lt;?php echo $cat-&gt;name ?&gt; &lt;/a&gt; &lt;/h3&gt; &lt;div id="&lt;?php echo $cat-&gt;slug ?&gt;" class="panel-collapse collapse in"&gt; &lt;div class="panel-body"&gt; &lt;?php foreach( $prodtype as $prod ) { ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt; &lt;?php the_field('titulo') ?&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 269686, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>That may change the order of posts on your main page, depending on your theme. </p>\n\n<p>There are wa...
2017/06/09
[ "https://wordpress.stackexchange.com/questions/269679", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121494/" ]
I'm in trouble with Bootstrap and Wordpress. I want to get Taxonomy list to expand (show custom posts from Taxonomy). But it is hard!!!! Its basically a custom sidebar My code: ``` <h3> Portfólio </h3> <?php $catprod = get_terms( array( 'taxonomy' => 'categoria-produto', 'order' => 'DESC' )); // Todas as categorias $args = array( 'post_type' => 'produto' ); $prodtype = new WP_Query($args); ?> <div class="panel-group"> <div class="panel-heading"> <?php foreach( $catprod as $cat ) { ?> <h3 class="panel-title"> <a data-toggle="collapse" href="#<?php echo $cat->slug ?>" class="accordion-toggle" data-parent="#accordion"> <?php echo $cat->name ?> </a> </h3> <div id="<?php echo $cat->slug ?>" class="panel-collapse collapse in"> <div class="panel-body"> <?php foreach( $prodtype as $prod ) { ?> <li> <a href="<?php the_permalink() ?>"> <?php the_field('titulo') ?> </a> </li> <?php } ?> </div> </div> <?php } ?> </div> </div> ```
From what i understand, you want to change the post's modification time whenever a comment is left on your post. For this, you need to hook into the `wp_insert_comment` hook and update the post's date manually: ``` add_action('wp_insert_comment','update_post_time',99,2); function update_post_time($comment_id, $comment_object) { // Get the post's ID $post_id = $comment_object->comment_post_ID; // Double check for post's ID, since this value is mandatory in wp_update_post() if ($post_id) { // Get the current time $time = current_time('mysql'); // Form an array of data to be updated $post_data = array( 'ID' => $post_id, 'post_modified' => $time, 'post_modified_gmt' => get_gmt_from_date( $time ) ); // Update the post wp_update_post( $post_data ); } } ``` Note that this will create a revision for the post each time a comment is created. If your sitemap plugin uses the `post_date` instead of `post_modified`, you can use this instead: ``` $post_data = array( 'ID' => $post_id, 'post_date' => $time, 'post_date_gmt' => get_gmt_from_date( $time ) ); ``` However, this might cause problems, and mess post's order in archives and homepage, since it changes the post's **creation** date, not modification date.
269,699
<p>I wanted to know if i can change the way i display views count in WordPress.</p> <p>Example: 1000 views = 1k - 10000 views = 10k</p> <p>I'm counting and viewing post views by using this code:</p> <pre><code>// Count views function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); } else { $count++; update_post_meta($postID, $count_key, $count); } } // Show views function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } return $count.' Views'; } // Show views in WP-Admin add_filter('manage_posts_columns', 'posts_column_views'); add_action('manage_posts_custom_column', 'posts_custom_column_views', 5, 2); function posts_column_views($defaults) { $defaults['post_views'] = __('Views'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views') { echo getPostViews(get_the_ID()); } } </code></pre>
[ { "answer_id": 269700, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return i...
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117100/" ]
I wanted to know if i can change the way i display views count in WordPress. Example: 1000 views = 1k - 10000 views = 10k I'm counting and viewing post views by using this code: ``` // Count views function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); } else { $count++; update_post_meta($postID, $count_key, $count); } } // Show views function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } return $count.' Views'; } // Show views in WP-Admin add_filter('manage_posts_columns', 'posts_column_views'); add_action('manage_posts_custom_column', 'posts_custom_column_views', 5, 2); function posts_column_views($defaults) { $defaults['post_views'] = __('Views'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views') { echo getPostViews(get_the_ID()); } } ```
Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return it: ``` function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } if ($count > 1000) { return round ( $count / 1000 ,1 ).'K Views'; } else { return $count.' Views'; } } ```
269,708
<p>I have used thumbnail like this in my wordpress theme's one template →</p> <pre><code>&lt;?php the_post_thumbnail( 'medium' ); ?&gt; </code></pre> <p>In the browser it is rendering like this →</p> <pre><code>&lt;img width="300" height="220" src="http://example.com/image-300x220.jpg" class="attachment-medium size-medium wp-post-image" alt="" srcset=" http://example.com/image-300x220.jpg 300w, http://example.com/image.jpg 640w" sizes="(max-width: 300px) 100vw, 300px" &gt; </code></pre> <p>My first question is how to put height = auto is there any function that can help us to achieve this? such as <code>responsive-img</code></p> <p>In short, I am asking should I control the width through the CSS or WordPress gives some function to do this?</p>
[ { "answer_id": 269700, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return i...
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269708", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I have used thumbnail like this in my wordpress theme's one template → ``` <?php the_post_thumbnail( 'medium' ); ?> ``` In the browser it is rendering like this → ``` <img width="300" height="220" src="http://example.com/image-300x220.jpg" class="attachment-medium size-medium wp-post-image" alt="" srcset=" http://example.com/image-300x220.jpg 300w, http://example.com/image.jpg 640w" sizes="(max-width: 300px) 100vw, 300px" > ``` My first question is how to put height = auto is there any function that can help us to achieve this? such as `responsive-img` In short, I am asking should I control the width through the CSS or WordPress gives some function to do this?
Yes you can. You have to check if the post view count is higher than 1000, is so, then round it and return it: ``` function getPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count=='') { delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 View"; } if ($count > 1000) { return round ( $count / 1000 ,1 ).'K Views'; } else { return $count.' Views'; } } ```
269,719
<p>Can the new 4.8 widget visual editor in the default text widget be unhooked or removed and the widget restored to the pre-4.8 editor style?</p> <p>I don't need or want the visual editor in widgets; I use them for plain text and html and don't need other users adding anything other than plain text.</p> <p>I did learn how to <em>remove</em> the new video, audio and image widgets in <code>functions.php</code> as I don't need them:</p> <pre><code>// Unregister default WP Widgets function unregister_default_wp_widgets() { unregister_widget('WP_Widget_Media_Audio' ); unregister_widget('WP_Widget_Media_Image'); unregister_widget( 'WP_Widget_Media_Video' ); } add_action('widgets_init', 'unregister_default_wp_widgets', 1); </code></pre> <p>But I also want to remove the visual editor tab from the default text widget.</p> <p><strong>Edit:</strong> I can use the PHP Code Widget <a href="https://wordpress.org/plugins/php-code-widget/" rel="noreferrer">https://wordpress.org/plugins/php-code-widget/</a> which does not have the visual editor, and though I don't usually need <code>php</code> execution, it is useful. But this adds the "break things" vector for users who might play with <code>php</code>.</p>
[ { "answer_id": 269724, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>The answer is mostly no. The \"enhanced\" text widget was designed to work like the post editor as much as...
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269719", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101490/" ]
Can the new 4.8 widget visual editor in the default text widget be unhooked or removed and the widget restored to the pre-4.8 editor style? I don't need or want the visual editor in widgets; I use them for plain text and html and don't need other users adding anything other than plain text. I did learn how to *remove* the new video, audio and image widgets in `functions.php` as I don't need them: ``` // Unregister default WP Widgets function unregister_default_wp_widgets() { unregister_widget('WP_Widget_Media_Audio' ); unregister_widget('WP_Widget_Media_Image'); unregister_widget( 'WP_Widget_Media_Video' ); } add_action('widgets_init', 'unregister_default_wp_widgets', 1); ``` But I also want to remove the visual editor tab from the default text widget. **Edit:** I can use the PHP Code Widget <https://wordpress.org/plugins/php-code-widget/> which does not have the visual editor, and though I don't usually need `php` execution, it is useful. But this adds the "break things" vector for users who might play with `php`.
The answer is mostly no. The "enhanced" text widget was designed to work like the post editor as much as possible, including autop which might break whatever HTML that can not stand the conversion of lines into paragraphs. Several people have released plugins to restore the former functionality, but 4.8.1 will also include an "code" widget that can be used to add unaltered HTML. The problem is that there is no, and unlikely to be a plain upgrade path. Best advice right now if you use the html widget is to skip 4.8 and wait for 4.8.1 and allocate some time in advance to migrate the widgets. If you are just looking to hide the "visual" tab, you are most like also out of luck best to open a ticket at trac to add such possibility, specifically for the widget without impact on the post editor (4.8.1 plan right now is to use the same setting for both)
269,736
<p>I was able to add the file last modified time as version to css and js files. As you can see I have to repeatly adding <code>filemtime(get_theme_file_path('...'))</code> every time when a new link is added.</p> <pre><code>function _enqueue_scripts() { wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css'))); wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js'))); } add_action('wp_enqueue_scripts', '_enqueue_scripts'); </code></pre> <p>Is there a way to use a custom filter or so for it rather than manually add that line every time?</p> <p>Similar to the below function (for removing version numbers), but I'd like to add version numbers. </p> <pre><code>function _remove_script_version($src) { return $src ? esc_url(remove_query_arg('ver', $src)) : false; } add_filter('style_loader_src', '_remove_script_version', 15, 1); add_filter('script_loader_src', '_remove_script_version', 15, 1); </code></pre>
[ { "answer_id": 269740, "author": "inarilo", "author_id": 17923, "author_profile": "https://wordpress.stackexchange.com/users/17923", "pm_score": 4, "selected": true, "text": "<p>You could use <a href=\"http://developer.wordpress.org/reference/functions/add_query_arg\" rel=\"noreferrer\">...
2017/06/10
[ "https://wordpress.stackexchange.com/questions/269736", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9508/" ]
I was able to add the file last modified time as version to css and js files. As you can see I have to repeatly adding `filemtime(get_theme_file_path('...'))` every time when a new link is added. ``` function _enqueue_scripts() { wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css'))); wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js'))); } add_action('wp_enqueue_scripts', '_enqueue_scripts'); ``` Is there a way to use a custom filter or so for it rather than manually add that line every time? Similar to the below function (for removing version numbers), but I'd like to add version numbers. ``` function _remove_script_version($src) { return $src ? esc_url(remove_query_arg('ver', $src)) : false; } add_filter('style_loader_src', '_remove_script_version', 15, 1); add_filter('script_loader_src', '_remove_script_version', 15, 1); ```
You could use [add\_query\_arg()](http://developer.wordpress.org/reference/functions/add_query_arg) but then you'd have to parse the uri everytime, I'd rather create a wrapper function for wp\_enqueue\_script/style: ``` function my_enqueuer($my_handle, $relpath, $type='script', $my_deps=array()) { $uri = get_theme_file_uri($relpath); $vsn = filemtime(get_theme_file_path($relpath)); if($type == 'script') wp_enqueue_script($my_handle, $uri, $my_deps, $vsn); else if($type == 'style') wp_enqueue_style($my_handle, $uri, $my_deps, $vsn); } ``` Add this in your functions file and then in place of e.g. ``` wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js'))); ``` call: ``` my_enqueuer('_base', '/assets/js/base.js'); ``` and in place of e.g. ``` wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css'))); ``` call: ``` my_enqueuer('_base', '/assets/css/base.css', 'style'); ``` You can pass the dependency array as the last argument when needed. For scripts, if you pass the dependency array, you will have to pass the third parameter 'script' as well, even though I've set it as the default value.
269,794
<p><a href="https://i.stack.imgur.com/RIKPa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RIKPa.jpg" alt="Can You plz guide me"></a> how to create the logic that makes those posts sortable either by the first letter of title or numbers?</p> <p>I want when I click on a "letter" the posts must get updated with the given first letter I want when I click on a "letter" the posts must get updated with the given first letter</p> <p>If you want to check the original page: <a href="https://neverquit.000webhostapp.com/library" rel="nofollow noreferrer">https://neverquit.000webhostapp.com/library</a></p>
[ { "answer_id": 296408, "author": "Alex Sancho", "author_id": 2536, "author_profile": "https://wordpress.stackexchange.com/users/2536", "pm_score": 4, "selected": true, "text": "<p>I think there's a better approach, just create a custom taxonomy that holds the alphanumeric terms, then ass...
2017/06/11
[ "https://wordpress.stackexchange.com/questions/269794", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116722/" ]
[![Can You plz guide me](https://i.stack.imgur.com/RIKPa.jpg)](https://i.stack.imgur.com/RIKPa.jpg) how to create the logic that makes those posts sortable either by the first letter of title or numbers? I want when I click on a "letter" the posts must get updated with the given first letter I want when I click on a "letter" the posts must get updated with the given first letter If you want to check the original page: <https://neverquit.000webhostapp.com/library>
I think there's a better approach, just create a custom taxonomy that holds the alphanumeric terms, then assign each post to the correct term. You can use the save post action to auto assign posts to correct term on post save: ``` function save_index( $post_id ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } $slug = 'post'; $letter = ''; // only run for posts if ( isset( $_POST['post_type'] ) && ( $slug != $_POST['post_type'] ) ) { return; } // Check user capabilities if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } $taxonomy = 'index'; // our custom taxonomy if ( isset( $_POST['post_type'] ) ) { // Get the title of the post $title = strtolower( $_POST['post_title'] ); // The next few lines remove A, An, or The from the start of the title $splitTitle = explode( ' ', $title ); $blacklist = [ 'an ', 'a ', 'the ' ]; $splitTitle[0] = str_replace( $blacklist, '', strtolower( $splitTitle[0] ) ); $title = implode( ' ', $splitTitle ); // Get the first letter of the title $letter = substr( $title, 0, 1 ); // Set to 0-9 if it's a number if ( is_numeric( $letter ) ) { $letter = '0-9'; } // set term as first letter of post title, lower case wp_set_post_terms( $post_id, $letter, $taxonomy ); } } add_action( 'save_post', 'save_index' ); ```
269,798
<p>I freshly installed a WordPress site and I configured it behind a reverse proxy with site URL - <code>http://example.com/hello</code></p> <h2>Problem</h2> <p>I can reach the admin dashboard page, however I cannot go further as the link becomes <code>http://example.com/wp-admin</code> instead of <code>http://example.com/hello/wp-admin</code>. How could I get rid of this weird behaviour?</p> <h2>Details that might help...</h2> <ol> <li>I am quite sure that the WordPress Address (URL) and Site Address (URL) are configured as <code>http://example.com/hello</code>, I even checked the database table <code>wp_options</code>.</li> <li>When it arrives the admin dashboard page with correct CSS, the browser will show the correct link for half seconds and suddenly change to the wrong one. I even checked the network log in my Chrome and Firefox, the requested URL is <code>http://example.com/hello/wp-admin</code>.</li> <li><p>I have tried to configure the <code>.htaccess</code> as well, but no luck.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /hello RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /hello/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre></li> </ol>
[ { "answer_id": 269801, "author": "Victor Wong", "author_id": 121572, "author_profile": "https://wordpress.stackexchange.com/users/121572", "pm_score": 2, "selected": false, "text": "<p>Eventually, I found the reason of this weird behaviour.</p>\n\n<p>It is caused by the JavaScript embedd...
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269798", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121572/" ]
I freshly installed a WordPress site and I configured it behind a reverse proxy with site URL - `http://example.com/hello` Problem ------- I can reach the admin dashboard page, however I cannot go further as the link becomes `http://example.com/wp-admin` instead of `http://example.com/hello/wp-admin`. How could I get rid of this weird behaviour? Details that might help... -------------------------- 1. I am quite sure that the WordPress Address (URL) and Site Address (URL) are configured as `http://example.com/hello`, I even checked the database table `wp_options`. 2. When it arrives the admin dashboard page with correct CSS, the browser will show the correct link for half seconds and suddenly change to the wrong one. I even checked the network log in my Chrome and Firefox, the requested URL is `http://example.com/hello/wp-admin`. 3. I have tried to configure the `.htaccess` as well, but no luck. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /hello RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /hello/index.php [L] </IfModule> # END WordPress ```
Eventually, I found the reason of this weird behaviour. It is caused by the JavaScript embedded in `wp_admin_canonical_url()` (<https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/>) The URL is determined by this piece of code ``` $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ``` where the latter one returns `wp-admin` instead of `hello/wp-admin`. By manipulating the value in `$_SERVER['REQUEST_URI']`, I can successfully get the correct behaviour in admin dashboard. But I still hope for an elegant solution without touching WordPress code.
269,836
<p>I have a WordPress site, which has a list of playlists, which are essentially custom post types.</p> <p>There is a screenshot below. I want to extend this so it also includes <code>playlist_id</code> as an option of input. </p> <p>Currently you see it just has Image, Portfolio Title, Categories and Date.</p> <p>Can anyone advise which file/files I should be looking at to include this new header?</p> <p>I have searched the entire project for Portolio Title but for some reason it cannot be found.</p> <p>It is important to note the <code>post_id</code> and <code>playlist_id</code> are the same thing. The <code>playlist_id</code> will actually come from spotify, and i want to be able to insert this to correspond with a playlist.</p> <p><a href="https://i.stack.imgur.com/kz47A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kz47A.png" alt="enter image description here"></a></p>
[ { "answer_id": 269801, "author": "Victor Wong", "author_id": 121572, "author_profile": "https://wordpress.stackexchange.com/users/121572", "pm_score": 2, "selected": false, "text": "<p>Eventually, I found the reason of this weird behaviour.</p>\n\n<p>It is caused by the JavaScript embedd...
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121592/" ]
I have a WordPress site, which has a list of playlists, which are essentially custom post types. There is a screenshot below. I want to extend this so it also includes `playlist_id` as an option of input. Currently you see it just has Image, Portfolio Title, Categories and Date. Can anyone advise which file/files I should be looking at to include this new header? I have searched the entire project for Portolio Title but for some reason it cannot be found. It is important to note the `post_id` and `playlist_id` are the same thing. The `playlist_id` will actually come from spotify, and i want to be able to insert this to correspond with a playlist. [![enter image description here](https://i.stack.imgur.com/kz47A.png)](https://i.stack.imgur.com/kz47A.png)
Eventually, I found the reason of this weird behaviour. It is caused by the JavaScript embedded in `wp_admin_canonical_url()` (<https://developer.wordpress.org/reference/functions/wp_admin_canonical_url/>) The URL is determined by this piece of code ``` $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ``` where the latter one returns `wp-admin` instead of `hello/wp-admin`. By manipulating the value in `$_SERVER['REQUEST_URI']`, I can successfully get the correct behaviour in admin dashboard. But I still hope for an elegant solution without touching WordPress code.
269,853
<p>With WP 4.8 extending the widgets API, the simple text widget is using TinyMCE. The advantage is that TinyMCE scripts are already enqueued in Ajax requests.</p> <p>However, for a client, I need a widget which has <strong>multiple editors</strong> inside it. This widget is not only used on the Widgets' Page but also within the Plugin <strong><em>Page builder by SiteOrigin</em></strong>.</p> <p><em>With the new WordPress the following works in the widget form() function:</em></p> <pre><code>public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?&gt;&lt;div class="cis_editor_bwrap" &lt;?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?&gt;&gt;&lt;?php wp_editor(cisI8Extract($instance, 'text', $suf), 'text'.$suf ); ?&gt;&lt;/div&gt;&lt;?php } $this-&gt;containerInputHTML($instance); $this-&gt;linkWrapperInputHTML($instance); } </code></pre> <p>However, it only works as long as I have only one widget as the IDs will be duplicated as soon as a second widget is created. I need either a random number or the widget ID (note: the str_replace is needed as wp_editor does not accept the minus sign in ids).</p> <p><em>The following unfortunatly fails:</em></p> <pre><code>public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?&gt;&lt;div class="cis_editor_bwrap" &lt;?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?&gt;&gt;&lt;?php wp_editor(cisI8Extract($instance, 'text', $suf), str_replace("-","_",$this-&gt;get_field_id('text'.$suf)) ); ?&gt;&lt;/div&gt;&lt;?php } } </code></pre> <p>Somehow WordPress does not correctly instantiate TinyMCE if a random number or the widget ID are within the editor ID. Error message is like this: </p> <pre><code>wp-tinymce.php?c=1&amp;ver=4603-20170530:15 Uncaught TypeError: Cannot read property 'onpageload' of undefined at h (wp-tinymce.php?c=1&amp;ver=4603-20170530:15) at m (wp-tinymce.php?c=1&amp;ver=4603-20170530:15) at h.l.bind (wp-tinymce.php?c=1&amp;ver=4603-20170530:3) at o.bind (wp-tinymce.php?c=1&amp;ver=4603-20170530:5) at Object.init (wp-tinymce.php?c=1&amp;ver=4603-20170530:15) at e (editor.min.js?ver=4.8:1) at HTMLDocument.&lt;anonymous&gt; (editor.min.js?ver=4.8:1) at a (wp-tinymce.php?c=1&amp;ver=4603-20170530:3) at HTMLDocument.p (wp-tinymce.php?c=1&amp;ver=4603-20170530:3) </code></pre> <p>This is the HTML outputted by wp_editor if using possibility two:</p> <pre><code>&lt;div class="wp-core-ui wp-editor-wrap html-active" id="wp-widget_ciseditor_c27_text-wrap"&gt; &lt;link href="http://localhost/hiedler/wp-includes/css/dashicons.min.css?ver=4.8" id="dashicons-css" media="all" rel="stylesheet" type="text/css"&gt; &lt;link href="http://localhost/hiedler/wp-includes/css/editor.min.css?ver=4.8" id="editor-buttons-css" media="all" rel="stylesheet" type="text/css"&gt; &lt;div class="wp-editor-tools hide-if-no-js" id="wp-widget_ciseditor_c27_text-editor-tools"&gt; &lt;div class="wp-media-buttons" id="wp-widget_ciseditor_c27_text-media-buttons"&gt; &lt;button class="button insert-media add_media" data-editor="widget_ciseditor_c27_text" id="insert-media-button" type="button"&gt;&lt;span class="wp-media-buttons-icon"&gt;&lt;/span&gt; Dateien hinzufügen&lt;/button&gt; &lt;/div&gt; &lt;div class="wp-editor-tabs"&gt; &lt;button class="wp-switch-editor switch-tmce" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-tmce" type="button"&gt;Visuell&lt;/button&gt; &lt;button class="wp-switch-editor switch-html" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-html" type="button"&gt;Text&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="wp-editor-container" id="wp-widget_ciseditor_c27_text-editor-container"&gt; &lt;div class="quicktags-toolbar" id="qt_widget_ciseditor_c27_text_toolbar"&gt;&lt;/div&gt; &lt;textarea class="wp-editor-area" cols="40" id="widget_ciseditor_c27_text" name="widget_ciseditor_c27_text" rows="20"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>So my question is how can I solve this?</p> <p>I have the two ideas:</p> <ol> <li><p>Register the dynamic editor ID after widget creation/load and make it work. HOW?</p></li> <li><p>Do not use wp_editor() at all but use textareas and apply TinyMCE to them dynamically. Problems: File Upload will be missing. How to apply TinyMCE scripts on every new widget/widget load?</p></li> </ol> <p>Tried a lot of things so far but no luck.</p>
[ { "answer_id": 270853, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly the ID supplied to <code>wp_editor</code> needs to already exist. </p>\n\n<p>Perhaps it ...
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269853", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12035/" ]
With WP 4.8 extending the widgets API, the simple text widget is using TinyMCE. The advantage is that TinyMCE scripts are already enqueued in Ajax requests. However, for a client, I need a widget which has **multiple editors** inside it. This widget is not only used on the Widgets' Page but also within the Plugin ***Page builder by SiteOrigin***. *With the new WordPress the following works in the widget form() function:* ``` public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?><div class="cis_editor_bwrap" <?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?>><?php wp_editor(cisI8Extract($instance, 'text', $suf), 'text'.$suf ); ?></div><?php } $this->containerInputHTML($instance); $this->linkWrapperInputHTML($instance); } ``` However, it only works as long as I have only one widget as the IDs will be duplicated as soon as a second widget is created. I need either a random number or the widget ID (note: the str\_replace is needed as wp\_editor does not accept the minus sign in ids). *The following unfortunatly fails:* ``` public function form( $instance ) { // ... foreach(cisI8Suffixes(true) as $suf) { ?><div class="cis_editor_bwrap" <?php echo (CIS_I8_ENABLE) ? 'data-cislan="'.cisLanFromSuf($suf).'"': ""; ?>><?php wp_editor(cisI8Extract($instance, 'text', $suf), str_replace("-","_",$this->get_field_id('text'.$suf)) ); ?></div><?php } } ``` Somehow WordPress does not correctly instantiate TinyMCE if a random number or the widget ID are within the editor ID. Error message is like this: ``` wp-tinymce.php?c=1&ver=4603-20170530:15 Uncaught TypeError: Cannot read property 'onpageload' of undefined at h (wp-tinymce.php?c=1&ver=4603-20170530:15) at m (wp-tinymce.php?c=1&ver=4603-20170530:15) at h.l.bind (wp-tinymce.php?c=1&ver=4603-20170530:3) at o.bind (wp-tinymce.php?c=1&ver=4603-20170530:5) at Object.init (wp-tinymce.php?c=1&ver=4603-20170530:15) at e (editor.min.js?ver=4.8:1) at HTMLDocument.<anonymous> (editor.min.js?ver=4.8:1) at a (wp-tinymce.php?c=1&ver=4603-20170530:3) at HTMLDocument.p (wp-tinymce.php?c=1&ver=4603-20170530:3) ``` This is the HTML outputted by wp\_editor if using possibility two: ``` <div class="wp-core-ui wp-editor-wrap html-active" id="wp-widget_ciseditor_c27_text-wrap"> <link href="http://localhost/hiedler/wp-includes/css/dashicons.min.css?ver=4.8" id="dashicons-css" media="all" rel="stylesheet" type="text/css"> <link href="http://localhost/hiedler/wp-includes/css/editor.min.css?ver=4.8" id="editor-buttons-css" media="all" rel="stylesheet" type="text/css"> <div class="wp-editor-tools hide-if-no-js" id="wp-widget_ciseditor_c27_text-editor-tools"> <div class="wp-media-buttons" id="wp-widget_ciseditor_c27_text-media-buttons"> <button class="button insert-media add_media" data-editor="widget_ciseditor_c27_text" id="insert-media-button" type="button"><span class="wp-media-buttons-icon"></span> Dateien hinzufügen</button> </div> <div class="wp-editor-tabs"> <button class="wp-switch-editor switch-tmce" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-tmce" type="button">Visuell</button> <button class="wp-switch-editor switch-html" data-wp-editor-id="widget_ciseditor_c27_text" id="widget_ciseditor_c27_text-html" type="button">Text</button> </div> </div> <div class="wp-editor-container" id="wp-widget_ciseditor_c27_text-editor-container"> <div class="quicktags-toolbar" id="qt_widget_ciseditor_c27_text_toolbar"></div> <textarea class="wp-editor-area" cols="40" id="widget_ciseditor_c27_text" name="widget_ciseditor_c27_text" rows="20"></textarea> </div> </div> ``` So my question is how can I solve this? I have the two ideas: 1. Register the dynamic editor ID after widget creation/load and make it work. HOW? 2. Do not use wp\_editor() at all but use textareas and apply TinyMCE to them dynamically. Problems: File Upload will be missing. How to apply TinyMCE scripts on every new widget/widget load? Tried a lot of things so far but no luck.
It's hard to say without seeing *all* the code. Yes if you don't refer to the instance - then it won't really be a unique ID. Something like this would work - you would just reference the class property $id: ``` for ( $i = 0; $i <= count( $suffixes ); $i++) { wp_editor( 'your content', "{$this->id}_$i" ); } ``` The js in core for the text widget create a random ID for the editor instances before it handles the instantiation, so you could translate that over to PHP if you wanted to follow that: ``` $el = 'el' . preg_replace( '/\D/', '', ( rand()/getrandmax() ) ) . '_'; ``` Since your developing locally - you should turn on SCRIPT\_DEBUG in your wp-config.php: define( 'SCRIPT\_DEBUG', true ); to help you troubleshoot your issues with javascript. Doing so would make that error from minified files be a little more meaningful. The error is being caused by switchEditor method in editor.min.js. There's special handling of the tinymce text widget in the customizer - and it's not just as simple as calling wp\_editor - though it could probably be done. You could try enabling the wp\_skip\_init process and adding your own initialization code perhaps: ``` add_filter( 'wp_editor_settings', 'ciseditor_wp_editor_settings', 5, 2 ); function ciseditor_wp_editor_settings( $settings, $id ) { // look for your prefixed id and return the id associated with it. if ( $ed = strstr( $id, 'foo_widget' ) ) { $settings['tinymce'] = array( 'wp_skip_init' => true, 'wp_autoresize_on' => false, // turn off the auto resize height of editor. ); $settings['editor_height'] = 300; // set the height } return $settings; } ``` I'm pretty sure that won't be the way to go though. I would recommend looking at wp-admin/js/text-widgets.js to see the handling of how core is implementing the text widget and the switch editor functionality - along with properly handling the data for the customizer. You should also reference wp-includes/widgets/class-wp-widget-text.php since you're essentially wanting to make the same thing that already exists. Generally having that error in tinymce means that the instance isn't being removed and added back properly - so it makes sense that WordPress' switchEditor in this context is throwing errors for you. There's a lot of documentation in the text-widgets.js about how tinymce and dynamic DOM components will interact that have to be accounted for or you'll end up with issues. One quick solution might just be to disable quicktags for your editor instances, which could be done in the wp\_editor\_settings filter or you can also pass it in the settings array when you're making the editors, ie: ``` wp_editor( 'your content', "{$this->id}_$i", array( 'quicktags' => false ) ); ``` I did dynamically create tinymce instances on a project once in wordpress, and I just remember looking at the editor code in core to see what arguments and scripts they included to get everything working, so that's always an option too. If you go that route - most of the things translate over 1:1 in terms of the php abstraction to js for the params. I think for the add media button I ended up creating my own thing, but there is the action 'media\_buttons' so you should be able to just add that where it needs to be displayed. Also consider why it is that you need multiple editors in one widget. Another way to handle this would be to remove the instances in an accordion style within the widget itself, and rebuild them as accordions are expanded so only one widget is displayed at a time. I think ultimately though - having one editor in a widget suits most use cases, and gives the end user flexibility to move content where they find it most fitting for their own use.
269,856
<p>I need to add custom item to WooCommerce My Account navigation. I can add the item with no problem. Since it is a link to user's profile I use the following code:</p> <pre><code>&lt;?php global $switched; switch_to_blog(2); ?&gt; &lt;a href=”&lt;?php echo bp_loggedin_user_domain(); ?&gt;”&gt;Profile&lt;/a&gt; &lt;?php restore_current_blog(); //switched back to main site ?&gt; </code></pre> <p>First I switch to BuddyPress which handles users (multisite newtork). Then I use bp_loggedin_user_domain to get user profile url.</p> <p>But the actual output of the link is incorrect, I get: www.domain.com/my-account/"www.subdomain.domain.com/members/profile/"</p> <p>I know that My Account page treats all links as child pages with WooCommerce endpoints, but is there a way to get the external url there? Without WooCommerce's default domain.com/my-account/ prefix</p>
[ { "answer_id": 270853, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly the ID supplied to <code>wp_editor</code> needs to already exist. </p>\n\n<p>Perhaps it ...
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269856", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93413/" ]
I need to add custom item to WooCommerce My Account navigation. I can add the item with no problem. Since it is a link to user's profile I use the following code: ``` <?php global $switched; switch_to_blog(2); ?> <a href=”<?php echo bp_loggedin_user_domain(); ?>”>Profile</a> <?php restore_current_blog(); //switched back to main site ?> ``` First I switch to BuddyPress which handles users (multisite newtork). Then I use bp\_loggedin\_user\_domain to get user profile url. But the actual output of the link is incorrect, I get: www.domain.com/my-account/"www.subdomain.domain.com/members/profile/" I know that My Account page treats all links as child pages with WooCommerce endpoints, but is there a way to get the external url there? Without WooCommerce's default domain.com/my-account/ prefix
It's hard to say without seeing *all* the code. Yes if you don't refer to the instance - then it won't really be a unique ID. Something like this would work - you would just reference the class property $id: ``` for ( $i = 0; $i <= count( $suffixes ); $i++) { wp_editor( 'your content', "{$this->id}_$i" ); } ``` The js in core for the text widget create a random ID for the editor instances before it handles the instantiation, so you could translate that over to PHP if you wanted to follow that: ``` $el = 'el' . preg_replace( '/\D/', '', ( rand()/getrandmax() ) ) . '_'; ``` Since your developing locally - you should turn on SCRIPT\_DEBUG in your wp-config.php: define( 'SCRIPT\_DEBUG', true ); to help you troubleshoot your issues with javascript. Doing so would make that error from minified files be a little more meaningful. The error is being caused by switchEditor method in editor.min.js. There's special handling of the tinymce text widget in the customizer - and it's not just as simple as calling wp\_editor - though it could probably be done. You could try enabling the wp\_skip\_init process and adding your own initialization code perhaps: ``` add_filter( 'wp_editor_settings', 'ciseditor_wp_editor_settings', 5, 2 ); function ciseditor_wp_editor_settings( $settings, $id ) { // look for your prefixed id and return the id associated with it. if ( $ed = strstr( $id, 'foo_widget' ) ) { $settings['tinymce'] = array( 'wp_skip_init' => true, 'wp_autoresize_on' => false, // turn off the auto resize height of editor. ); $settings['editor_height'] = 300; // set the height } return $settings; } ``` I'm pretty sure that won't be the way to go though. I would recommend looking at wp-admin/js/text-widgets.js to see the handling of how core is implementing the text widget and the switch editor functionality - along with properly handling the data for the customizer. You should also reference wp-includes/widgets/class-wp-widget-text.php since you're essentially wanting to make the same thing that already exists. Generally having that error in tinymce means that the instance isn't being removed and added back properly - so it makes sense that WordPress' switchEditor in this context is throwing errors for you. There's a lot of documentation in the text-widgets.js about how tinymce and dynamic DOM components will interact that have to be accounted for or you'll end up with issues. One quick solution might just be to disable quicktags for your editor instances, which could be done in the wp\_editor\_settings filter or you can also pass it in the settings array when you're making the editors, ie: ``` wp_editor( 'your content', "{$this->id}_$i", array( 'quicktags' => false ) ); ``` I did dynamically create tinymce instances on a project once in wordpress, and I just remember looking at the editor code in core to see what arguments and scripts they included to get everything working, so that's always an option too. If you go that route - most of the things translate over 1:1 in terms of the php abstraction to js for the params. I think for the add media button I ended up creating my own thing, but there is the action 'media\_buttons' so you should be able to just add that where it needs to be displayed. Also consider why it is that you need multiple editors in one widget. Another way to handle this would be to remove the instances in an accordion style within the widget itself, and rebuild them as accordions are expanded so only one widget is displayed at a time. I think ultimately though - having one editor in a widget suits most use cases, and gives the end user flexibility to move content where they find it most fitting for their own use.
269,862
<p>How to set custom title of custom page template?</p> <p>I try use <code>wp_title</code> filter but it's not working.</p>
[ { "answer_id": 269864, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You can do a conditional and check if you are on a custom post type page, and then update the title:</p>\n\...
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269862", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117356/" ]
How to set custom title of custom page template? I try use `wp_title` filter but it's not working.
[Reference](https://wordpress.stackexchange.com/questions/62415/changing-document-title-only-on-a-custom-page-template/62417?newreg=9e9601805cd5461e9ab988dc3e605854) Got success by adding this code to `your-page-template.php` file before `get_header()` function: ``` function my_page_title() { return 'Your value is '; // add dynamic content to this title (if needed) } add_action( 'pre_get_document_title', 'my_page_title' ); ```
269,868
<p>I migrated my WordPress site to a new host and new URL. I've done all the typical search and replace in mysql and the site works great.</p> <p>However, the links of my images are all missing <code>.co.uk</code>, thus not working.</p> <p><a href="https://i.stack.imgur.com/T9Rmn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T9Rmn.jpg" alt="Image below"></a></p> <p>The odd thing is, all the image URLs are correct in the source code of blogs. But in my media library, they are all missing .co.uk.</p> <p>How do I add .co.uk back into my media library URLs?</p>
[ { "answer_id": 269881, "author": "DaveLak", "author_id": 119673, "author_profile": "https://wordpress.stackexchange.com/users/119673", "pm_score": 3, "selected": false, "text": "<p>As mentioned in the comments under your question, some data in the WordPress database is serialized and the...
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81862/" ]
I migrated my WordPress site to a new host and new URL. I've done all the typical search and replace in mysql and the site works great. However, the links of my images are all missing `.co.uk`, thus not working. [![Image below](https://i.stack.imgur.com/T9Rmn.jpg)](https://i.stack.imgur.com/T9Rmn.jpg) The odd thing is, all the image URLs are correct in the source code of blogs. But in my media library, they are all missing .co.uk. How do I add .co.uk back into my media library URLs?
As mentioned in the comments under your question, some data in the WordPress database is serialized and therefore not possible to change with a simple find and replace. You should read through the [Moving WordPress](https://codex.wordpress.org/Moving_WordPress) section of the codex. Specifically the [Changing Your Domain Name and URLs](https://codex.wordpress.org/Moving_WordPress#Changing_Your_Domain_Name_and_URLs) portion. I usually use a plugin or a command line tool depending on what's available to me. ### Plugin: [Better Search Replace](https://wordpress.org/plugins/better-search-replace/#description) is a useful plugin recommended in the entry above. There are other plugins that will do the same things but this is my preference. Some features that I enjoy are: * Support for serialized data. * The ability to select single or multiple tables. * A "dry run" feature to test and verify your changes before actually performing them. * Very few server requirements (all you *need* is a WP instance.) --- ### CLI Tool: Another option that handles serialized data is the [WP-CLI's search-replace tool](https://developer.wordpress.org/cli/commands/search-replace/). This option is used from the command line via something like SSH and requires the wp-cli to be installed on the server. You can [take a look at the docs](https://developer.wordpress.org/cli/commands/search-replace/) for all available options and examples but the basic usage is: ``` # Search for old domain name and replace it with a new one $ wp search-replace 'http://old.example.dev' 'http://new.example.com' ```
269,878
<p>I'm struggling with WordPress Multisite page creation when newly site created. I found some hooks to achieve this but the hook is not responding. Some of the resources I found on stack and other sites are <a href="https://stackoverflow.com/questions/40014419/wordpress-multisite-default-page-for-newly-created-site">https://stackoverflow.com/questions/40014419/wordpress-multisite-default-page-for-newly-created-site</a> and <a href="http://www.wpbeginner.com/wp-tutorials/how-to-add-remove-default-pages-in-wordpress-multisite/" rel="nofollow noreferrer">http://www.wpbeginner.com/wp-tutorials/how-to-add-remove-default-pages-in-wordpress-multisite/</a></p> <p>The hook mentioned in these resources not working in my multisite setup.</p> <pre><code>add_action('wpmu_new_blog', 'wpb_create_my_pages', 10, 2); function wpb_create_my_pages($blog_id, $user_id){ switch_to_blog($blog_id); // create new page $page_id = wp_insert_post(array( 'post_title' =&gt; 'About', 'post_name' =&gt; 'about', 'post_content' =&gt; 'This is an about page. Feel free to edit or delete this page.', 'post_status' =&gt; 'publish', 'post_author' =&gt; $user_id, // or "1" (super-admin?) 'post_type' =&gt; 'page', 'menu_order' =&gt; 1, 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', )); // Find and delete the WP default 'Sample Page' $defaultPage = get_page_by_title( 'Sample Page' ); wp_delete_post( $defaultPage-&gt;ID ); restore_current_blog(); } </code></pre> <p>I'm adding this code in my child theme functions.php file. Any suggestion to fix this issue.</p>
[ { "answer_id": 269888, "author": "Nikolay", "author_id": 100555, "author_profile": "https://wordpress.stackexchange.com/users/100555", "pm_score": 3, "selected": true, "text": "<p>The code you provided works great on my multisite. I am putting it in a network activated plugin though. Try...
2017/06/12
[ "https://wordpress.stackexchange.com/questions/269878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60914/" ]
I'm struggling with WordPress Multisite page creation when newly site created. I found some hooks to achieve this but the hook is not responding. Some of the resources I found on stack and other sites are <https://stackoverflow.com/questions/40014419/wordpress-multisite-default-page-for-newly-created-site> and <http://www.wpbeginner.com/wp-tutorials/how-to-add-remove-default-pages-in-wordpress-multisite/> The hook mentioned in these resources not working in my multisite setup. ``` add_action('wpmu_new_blog', 'wpb_create_my_pages', 10, 2); function wpb_create_my_pages($blog_id, $user_id){ switch_to_blog($blog_id); // create new page $page_id = wp_insert_post(array( 'post_title' => 'About', 'post_name' => 'about', 'post_content' => 'This is an about page. Feel free to edit or delete this page.', 'post_status' => 'publish', 'post_author' => $user_id, // or "1" (super-admin?) 'post_type' => 'page', 'menu_order' => 1, 'comment_status' => 'closed', 'ping_status' => 'closed', )); // Find and delete the WP default 'Sample Page' $defaultPage = get_page_by_title( 'Sample Page' ); wp_delete_post( $defaultPage->ID ); restore_current_blog(); } ``` I'm adding this code in my child theme functions.php file. Any suggestion to fix this issue.
The code you provided works great on my multisite. I am putting it in a network activated plugin though. Try the same.
269,934
<p>I'm using <em>Knowall</em> theme for WordPress. I've developed a child theme with the following code placed in my <code>style.css</code> file in my child theme's folder:</p> <pre><code>/* Theme Name: KnowAll Child Theme Theme URI: help.mysite.com Description: Help site Author: myurl.com Template: knowall Version: 1.0 */ @import url("../knowall/css/style.css"); </code></pre> <p>This works (child theme is shown in WordPress) but created the following broken link:</p> <pre><code>http://help.mysite.com/wp-content/themes/knowall-child/css/style.css?ver=4.8 </code></pre> <p>So it looks like it's trying to locate the core Knowall style.css from within the child theme rather than the parent folder.</p> <p>I've 'fixed' this by importing the parent style.css directly into the child theme folder. I've also had to do the same for the 'img' folder. </p> <p>How can I re-target these assets so it finds them in the parent theme? I don't want to have to re-import assets to the child theme every time I update Wordpress...</p>
[ { "answer_id": 269961, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>There is most likely some issues about using <a href=\"https://developer.wordpress.org/reference/functions/g...
2017/06/13
[ "https://wordpress.stackexchange.com/questions/269934", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121660/" ]
I'm using *Knowall* theme for WordPress. I've developed a child theme with the following code placed in my `style.css` file in my child theme's folder: ``` /* Theme Name: KnowAll Child Theme Theme URI: help.mysite.com Description: Help site Author: myurl.com Template: knowall Version: 1.0 */ @import url("../knowall/css/style.css"); ``` This works (child theme is shown in WordPress) but created the following broken link: ``` http://help.mysite.com/wp-content/themes/knowall-child/css/style.css?ver=4.8 ``` So it looks like it's trying to locate the core Knowall style.css from within the child theme rather than the parent folder. I've 'fixed' this by importing the parent style.css directly into the child theme folder. I've also had to do the same for the 'img' folder. How can I re-target these assets so it finds them in the parent theme? I don't want to have to re-import assets to the child theme every time I update Wordpress...
There is most likely some issues about using [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) or [`get_stylesheet_directory_uri()`](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri). According to WordPress Code reference: > > `get_template_directory_uri()` function returns the URL to the root theme. If a child theme is > used and you want to return the URL to the current child theme, use > `get_stylesheet_directory_uri()` instead. > > > Also, it is [noted](https://codex.wordpress.org/Child_Themes) that importing the parent CSS file is not a good practice anymore: > > Note that the previous method was to import the parent theme > stylesheet using @import: this is no longer best practice, as it > increases the amount of time it takes style sheets to load. The > correct method of enqueuing the parent theme stylesheet is to add a > `wp_enqueue_scripts` action and use `wp_enqueue_style()` in your child > theme's functions.php. > > > So, what you have to do is to enqueue the style by using the following code in your child theme's functions.php file: ``` add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' ); function my_child_theme_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ``` And then enqueue your own CSS files if there is any.
269,970
<p>I'have this structure:</p> <ul> <li><strong>News</strong> (CPT. A page showing all news) </li> <li><strong>Works</strong> (CPT. A page showing all works)</li> </ul> <p>Then, inside a single page of <strong>works</strong> I want to show the news related to this work:</p> <ul> <li>Single work <ul> <li>title</li> <li>content</li> <li>news related to this single work</li> </ul></li> </ul> <p>How can I make a relation between a single post in <strong>News</strong> and single post in <strong>Works</strong>?</p> <p>AFAIK, I can create a category term with same name of each single work, by hand, and then to assign that term to News single post. But there is high risk of typos and a lot of work in the content editor. Is it possible to get a more automated method?</p> <p>Thank you.</p>
[ { "answer_id": 269961, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>There is most likely some issues about using <a href=\"https://developer.wordpress.org/reference/functions/g...
2017/06/13
[ "https://wordpress.stackexchange.com/questions/269970", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77722/" ]
I'have this structure: * **News** (CPT. A page showing all news) * **Works** (CPT. A page showing all works) Then, inside a single page of **works** I want to show the news related to this work: * Single work + title + content + news related to this single work How can I make a relation between a single post in **News** and single post in **Works**? AFAIK, I can create a category term with same name of each single work, by hand, and then to assign that term to News single post. But there is high risk of typos and a lot of work in the content editor. Is it possible to get a more automated method? Thank you.
There is most likely some issues about using [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) or [`get_stylesheet_directory_uri()`](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri). According to WordPress Code reference: > > `get_template_directory_uri()` function returns the URL to the root theme. If a child theme is > used and you want to return the URL to the current child theme, use > `get_stylesheet_directory_uri()` instead. > > > Also, it is [noted](https://codex.wordpress.org/Child_Themes) that importing the parent CSS file is not a good practice anymore: > > Note that the previous method was to import the parent theme > stylesheet using @import: this is no longer best practice, as it > increases the amount of time it takes style sheets to load. The > correct method of enqueuing the parent theme stylesheet is to add a > `wp_enqueue_scripts` action and use `wp_enqueue_style()` in your child > theme's functions.php. > > > So, what you have to do is to enqueue the style by using the following code in your child theme's functions.php file: ``` add_action( 'wp_enqueue_scripts', 'my_child_theme_styles' ); function my_child_theme_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ``` And then enqueue your own CSS files if there is any.
270,005
<p>I have a custom endpoint defined like so:</p> <pre><code> add_action( 'rest_api_init', function () { register_rest_route( 'menc/v1', '/crosscat/(?P&lt;dept&gt;[\w-]+)/(?P&lt;cat&gt;[\w-]+)', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'dept_cat_api', 'args' =&gt; array( 'dept' =&gt; array( 'sanitize_callback' =&gt; function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'cat' =&gt; array( 'sanitize_callback' =&gt; function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'per_page' =&gt; array( 'default' =&gt; 10, 'sanitize_callback' =&gt; 'absint', ), 'page' =&gt; array( 'default' =&gt; 1, 'sanitize_callback' =&gt; 'absint', ), 'orderby' =&gt; array( 'default' =&gt; 'date', 'sanitize_callback' =&gt; 'sanitize_text_field', ), 'order' =&gt; array( 'default' =&gt; 'desc', 'sanitize_callback' =&gt; 'sanitize_text_field', ), ), ) ); } ); function dept_cat_api( $request ) { $args = array( 'post_type' =&gt; 'post', 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'crosspost', 'field' =&gt; 'slug', 'terms' =&gt; array( $request['dept'] ), ), array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; array( $request['cat'] ), ), ), 'per_page' =&gt; $request['per_page'], 'page' =&gt; $request['page'], 'orderby' =&gt; $request['orderby'], 'order' =&gt; $request['order'] ); $posts = get_posts( $args ); if ( empty( $posts ) ) return new WP_Error( 'no_posts', 'Invalid term(s)', array( 'status' =&gt; 404 ) ); $controller = new WP_REST_Posts_Controller('post'); foreach ( $posts as $post ) { $response = $controller-&gt;prepare_item_for_response( $post, $request ); $data[] = $controller-&gt;prepare_response_for_collection( $response ); } // return results return new WP_REST_Response($data, 200); } </code></pre> <p>Remotely I'm having a problem. When I call the route everything seems fine with the content, however both <code>X-WP-TotalPages</code> and <code>X-WP-Total</code> return empty responses. </p> <pre><code> object(Requests_Utility_CaseInsensitiveDictionary)#991 (1) { ["data":protected]=&gt; array(20) { ["server"]=&gt; string(5) "nginx" ["date"]=&gt; string(29) "Wed, 14 Jun 2017 14:07:51 GMT" ["content-type"]=&gt; string(31) "application/json; charset=UTF-8" ["content-length"]=&gt; string(6) "104787" ["expires"]=&gt; string(29) "Thu, 19 Nov 1981 08:52:00 GMT" ["pragma"]=&gt; string(8) "no-cache" ["x-robots-tag"]=&gt; string(7) "noindex" ["link"]=&gt; string(65) "; rel="https://api.w.org/"" ["x-content-type-options"]=&gt; string(7) "nosniff" ["access-control-expose-headers"]=&gt; string(27) "X-WP-Total, X-WP-TotalPages" ["access-control-allow-headers"]=&gt; string(27) "Authorization, Content-Type" ["allow"]=&gt; string(3) "GET" ["x-cacheable"]=&gt; string(5) "SHORT" ["vary"]=&gt; string(22) "Accept-Encoding,Cookie" ["cache-control"]=&gt; string(28) "max-age=600, must-revalidate" ["accept-ranges"]=&gt; string(5) "bytes" ["x-cache"]=&gt; string(6) "HIT: 1" ["x-pass-why"]=&gt; string(0) "" ["x-cache-group"]=&gt; string(6) "normal" ["x-type"]=&gt; string(7) "default" } } </code></pre> <p>Ideally I need both populated, but I could make do with one. I assumed WordPress calculated/populated these via the controller. Do I have to populate them manually? Have I done something incorrectly? Am I experiencing a bug?</p>
[ { "answer_id": 270128, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>I had a quick look and here's how the headers are set in the <a href=\"https://developer.wordpress.org/referen...
2017/06/13
[ "https://wordpress.stackexchange.com/questions/270005", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98703/" ]
I have a custom endpoint defined like so: ``` add_action( 'rest_api_init', function () { register_rest_route( 'menc/v1', '/crosscat/(?P<dept>[\w-]+)/(?P<cat>[\w-]+)', array( 'methods' => 'GET', 'callback' => 'dept_cat_api', 'args' => array( 'dept' => array( 'sanitize_callback' => function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'cat' => array( 'sanitize_callback' => function($param, $request, $key) { return sanitize_text_field( $param ); } ), 'per_page' => array( 'default' => 10, 'sanitize_callback' => 'absint', ), 'page' => array( 'default' => 1, 'sanitize_callback' => 'absint', ), 'orderby' => array( 'default' => 'date', 'sanitize_callback' => 'sanitize_text_field', ), 'order' => array( 'default' => 'desc', 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } ); function dept_cat_api( $request ) { $args = array( 'post_type' => 'post', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'crosspost', 'field' => 'slug', 'terms' => array( $request['dept'] ), ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array( $request['cat'] ), ), ), 'per_page' => $request['per_page'], 'page' => $request['page'], 'orderby' => $request['orderby'], 'order' => $request['order'] ); $posts = get_posts( $args ); if ( empty( $posts ) ) return new WP_Error( 'no_posts', 'Invalid term(s)', array( 'status' => 404 ) ); $controller = new WP_REST_Posts_Controller('post'); foreach ( $posts as $post ) { $response = $controller->prepare_item_for_response( $post, $request ); $data[] = $controller->prepare_response_for_collection( $response ); } // return results return new WP_REST_Response($data, 200); } ``` Remotely I'm having a problem. When I call the route everything seems fine with the content, however both `X-WP-TotalPages` and `X-WP-Total` return empty responses. ``` object(Requests_Utility_CaseInsensitiveDictionary)#991 (1) { ["data":protected]=> array(20) { ["server"]=> string(5) "nginx" ["date"]=> string(29) "Wed, 14 Jun 2017 14:07:51 GMT" ["content-type"]=> string(31) "application/json; charset=UTF-8" ["content-length"]=> string(6) "104787" ["expires"]=> string(29) "Thu, 19 Nov 1981 08:52:00 GMT" ["pragma"]=> string(8) "no-cache" ["x-robots-tag"]=> string(7) "noindex" ["link"]=> string(65) "; rel="https://api.w.org/"" ["x-content-type-options"]=> string(7) "nosniff" ["access-control-expose-headers"]=> string(27) "X-WP-Total, X-WP-TotalPages" ["access-control-allow-headers"]=> string(27) "Authorization, Content-Type" ["allow"]=> string(3) "GET" ["x-cacheable"]=> string(5) "SHORT" ["vary"]=> string(22) "Accept-Encoding,Cookie" ["cache-control"]=> string(28) "max-age=600, must-revalidate" ["accept-ranges"]=> string(5) "bytes" ["x-cache"]=> string(6) "HIT: 1" ["x-pass-why"]=> string(0) "" ["x-cache-group"]=> string(6) "normal" ["x-type"]=> string(7) "default" } } ``` Ideally I need both populated, but I could make do with one. I assumed WordPress calculated/populated these via the controller. Do I have to populate them manually? Have I done something incorrectly? Am I experiencing a bug?
I had a quick look and here's how the headers are set in the [`WP_REST_Posts_Controller::get_items()`](https://developer.wordpress.org/reference/classes/wp_rest_posts_controller/get_items/) method: ``` $response = rest_ensure_response( $posts ); // ... $response->header( 'X-WP-Total', (int) $total_posts ); $response->header( 'X-WP-TotalPages', (int) $max_pages ); // ... return $response; ``` where: ``` $total_posts = $posts_query->found_posts; ``` and we could use as @jshwlkr [suggested](https://wordpress.stackexchange.com/users/98703/jshwlkr): ``` $max_pages = $posts_query->max_num_pages; ``` You could emulate that for your custom endpoint, by using `WP_Query` instead of `get_posts()`. Thanks to @DenisUyeda for [correcting the typo](https://wordpress.stackexchange.com/questions/270005/custom-endpoint-and-x-wp-totalpages-headers/270128#comment416579_270128).
270,008
<p>I've read a couple of things about the wp.media object and have successfully initialised in the state that I can find to upload images. But for the plug-in that I am building I need to have the same layout as when I click my attachment in de media grid gallery.</p> <p>For now this is my "simple" code that opens the default wp.media object</p> <pre><code>// Create a new media frame frame = wp.media({ title: 'Select or Upload Media Of Your Chosen Persuasion', button: { text: 'Use this media' }, multiple: false // Set to true to allow multiple files to be selected }); // Finally, open the modal on click frame.open(); </code></pre> <p>What I need is the exact same result as you follow the url down below:</p> <pre><code>http://wordpress.dev/wp-admin/upload.php?item=10 </code></pre> <p>Where you need to replace wordpress.dev with your own WP installation en item=10 to any attachment ID you actually have.</p> <p>It should look like the following screenshot:</p> <p><a href="https://i.stack.imgur.com/BBtzU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BBtzU.jpg" alt="Screenshot of edit attachment"></a></p> <p>Is there anyone we has an answer or can send me into the right direction?</p>
[ { "answer_id": 278838, "author": "user63350", "author_id": 83763, "author_profile": "https://wordpress.stackexchange.com/users/83763", "pm_score": 2, "selected": false, "text": "<p>Unfortunately the logic of the attachment details isn't made to be used standalone - it requires the grid t...
2017/06/13
[ "https://wordpress.stackexchange.com/questions/270008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58001/" ]
I've read a couple of things about the wp.media object and have successfully initialised in the state that I can find to upload images. But for the plug-in that I am building I need to have the same layout as when I click my attachment in de media grid gallery. For now this is my "simple" code that opens the default wp.media object ``` // Create a new media frame frame = wp.media({ title: 'Select or Upload Media Of Your Chosen Persuasion', button: { text: 'Use this media' }, multiple: false // Set to true to allow multiple files to be selected }); // Finally, open the modal on click frame.open(); ``` What I need is the exact same result as you follow the url down below: ``` http://wordpress.dev/wp-admin/upload.php?item=10 ``` Where you need to replace wordpress.dev with your own WP installation en item=10 to any attachment ID you actually have. It should look like the following screenshot: [![Screenshot of edit attachment](https://i.stack.imgur.com/BBtzU.jpg)](https://i.stack.imgur.com/BBtzU.jpg) Is there anyone we has an answer or can send me into the right direction?
Unfortunately the logic of the attachment details isn't made to be used standalone - it requires the grid that opens it. You can however use the `get_media_item( attachment_id )` method to receive the HTML of the form for modifying images: <https://developer.wordpress.org/reference/functions/get_media_item/>
270,010
<p>Running NGINX, Wordpress 4.75 after upgrading from a way older version of Wordpress, our images are being served locally and I would like to change that to our CDN. </p> <p>In the past images that were uploaded to the blog were uploaded directly to our CDN using a plugin ( I think Offload S3 Lite ). </p> <p>My goal is that I want post images, thumbnail etc URL to be served from our CDN and not local. </p> <p>For example I have: <a href="https://test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg" rel="nofollow noreferrer">https://test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg</a></p> <p>Needs to point to: <a href="https://cdn.test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg" rel="nofollow noreferrer">https://cdn.test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg</a></p> <p>Before the wordpress site (was not updated for a while) was uploading images directly to the CDN (AWS S3 -> Cloudfront) now that we upgraded to 4.75 the images that get served are pointing to local url instead of our CDN url. </p> <p>images are served through the functions like: the_post_thumbnail()</p> <p>Which I believe uses wp_get_attachment_image under the hood. If I can included a function in my functions.php to rewrite image urls that could work too.</p> <p>So how can I get the image urls to point to our CDN and instead of local url?</p> <p>Thanks for your help!</p>
[ { "answer_id": 270052, "author": "Morgan Estes", "author_id": 26317, "author_profile": "https://wordpress.stackexchange.com/users/26317", "pm_score": 0, "selected": false, "text": "<p>You probably want to use the <a href=\"https://developer.wordpress.org/reference/hooks/wp_get_attachment...
2017/06/13
[ "https://wordpress.stackexchange.com/questions/270010", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51263/" ]
Running NGINX, Wordpress 4.75 after upgrading from a way older version of Wordpress, our images are being served locally and I would like to change that to our CDN. In the past images that were uploaded to the blog were uploaded directly to our CDN using a plugin ( I think Offload S3 Lite ). My goal is that I want post images, thumbnail etc URL to be served from our CDN and not local. For example I have: <https://test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg> Needs to point to: <https://cdn.test.com/blog/wp-content/uploads/2016/07/Wedding1-370x215.jpg> Before the wordpress site (was not updated for a while) was uploading images directly to the CDN (AWS S3 -> Cloudfront) now that we upgraded to 4.75 the images that get served are pointing to local url instead of our CDN url. images are served through the functions like: the\_post\_thumbnail() Which I believe uses wp\_get\_attachment\_image under the hood. If I can included a function in my functions.php to rewrite image urls that could work too. So how can I get the image urls to point to our CDN and instead of local url? Thanks for your help!
Since the major adoption of **Responsive Images** and the addition of new `srcset` attribute to the `<img>` element. WordPress has to evolve too. WordPress 4.4 added the responsive images feature. If you inspect the `src` attribute it might point to the CDN, however, you still need to consider the `srcset` attribute which might still be using the local version of the images. First, we need to provide the algorithm for changing the local URL to the CDN version. The algorithm I use adheres your test case above; i.e. <https://test.com/> to <https://cdn.test.com/> ### Add these to `functions.php` ``` // Add .cdn after http:// or https:// function to_cdn($src) { $dslash_pos = strpos($src, '//') + 2; $src_pre = substr($src, 0, $dslash_pos); // http:// or https:// $src_post = substr($src, $dslash_pos); // The rest after http:// or https:// return $src_pre . 'cdn.' . $src_post; } ``` Then we need to change the `src` attribute of the image using the [wp\_get\_attachment\_image\_src](https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_src/) filter. ``` function test_get_attachment_image_src($image, $attachment_id, $size, $icon) { if(!is_admin()) { if(!image) { return false; } if(is_array($image)) { $src = to_cdn($image[0]); // To CDN $width = $image[1]; $height = $image[2]; return [$src, $width, $height, true]; } else { return false; } } return $image; } add_filter('wp_get_attachment_image_src', 'test_get_attachment_image_src', 10, 4); ``` Next is for the `srcset` attribute this time using [wp\_calculate\_image\_srcset](https://developer.wordpress.org/reference/hooks/wp_calculate_image_srcset/) filter. ``` function test_calculate_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) { if(!is_admin()) { $images = []; foreach($sources as $source) { $src = to_cdn($source['url']); // To CDN $images[] = [ 'url' => $src, 'descriptor' => $source['descriptor'], 'value' => $source['value'] ]; } return $images; } return $sources; } add_filter('wp_calculate_image_srcset', 'test_calculate_image_srcset', 10, 5); ```
270,111
<p>I have a new client who has recently had her site migrated to 1and1.com, and since the migration, none of her images will load, along with other assets.</p> <p>In the Media Library, the path to all of the images display as simply /u/, instead of /wp-content/uploads/:</p> <p><a href="https://i.stack.imgur.com/1B45y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1B45y.png" alt="enter image description here"></a></p> <p>Likewise for the styles.css, instead of looking for it in the /wp-content/themes/ directory, it's looking in a non-existent /t/ directory.</p> <p>This has to be intentional. Where would a change like this be made? I've looked in all of the usual places – wp-config.php, functions.php files, etc. – and found nothing.</p> <p>I've also tried Replace Image, with no success.</p> <p>Also, what would be the purpose of this?</p> <p>Thanks in advance!</p> <p>UPDATE: </p> <p>I found this in the htaccess library, but it doesn't appear to be functioning properly – the images aren't displaying – if that provides a clue:</p> <pre><code>### ### Rewrites /u/anything to /wp-content/uploads/anything if file anything exists there ### RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/wp-content/uploads/$1 -f RewriteRule ^u/(.+)$ /wp-content/uploads/$1 [L,NS,S=500] </code></pre>
[ { "answer_id": 270035, "author": "Pisuke Soramame", "author_id": 120818, "author_profile": "https://wordpress.stackexchange.com/users/120818", "pm_score": 1, "selected": false, "text": "<p>One possible solution is to add a metadata field to your post indicating the status (i.e. completed...
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16909/" ]
I have a new client who has recently had her site migrated to 1and1.com, and since the migration, none of her images will load, along with other assets. In the Media Library, the path to all of the images display as simply /u/, instead of /wp-content/uploads/: [![enter image description here](https://i.stack.imgur.com/1B45y.png)](https://i.stack.imgur.com/1B45y.png) Likewise for the styles.css, instead of looking for it in the /wp-content/themes/ directory, it's looking in a non-existent /t/ directory. This has to be intentional. Where would a change like this be made? I've looked in all of the usual places – wp-config.php, functions.php files, etc. – and found nothing. I've also tried Replace Image, with no success. Also, what would be the purpose of this? Thanks in advance! UPDATE: I found this in the htaccess library, but it doesn't appear to be functioning properly – the images aren't displaying – if that provides a clue: ``` ### ### Rewrites /u/anything to /wp-content/uploads/anything if file anything exists there ### RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/wp-content/uploads/$1 -f RewriteRule ^u/(.+)$ /wp-content/uploads/$1 [L,NS,S=500] ```
> > For example, let's say that Property is the post type. We would like > to display several different views (completed (built), for sale, and > for rent.) > > > Sure. Just make *Completed*, *For Sale*, and *For Rent* [taxonomies](https://codex.wordpress.org/Taxonomies) for the *Property* post type. Look into [WP\_Rewrite](https://developer.wordpress.org/reference/classes/wp_rewrite/generate_rewrite_rules/) class, too, and you can get greater control over url permalink structure.
270,126
<p>The plugin <strong><em>search and filter</em></strong>, doesn't retrieve <code>author_meta</code>. So i need to add <code>post_meta</code> from <code>author_meta</code>. Is it possible?</p> <h2>EDIT</h2> <p>I create user_meta in this way:</p> <pre><code> function custom_user_profile_fields($user){ $previous_value = ''; if( is_object($user) &amp;&amp; isset($user-&gt;ID) ) { $previous_value = get_user_meta( $user-&gt;ID, 'company', true ); } ?&gt; &lt;h3&gt;Extra profile information&lt;/h3&gt; &lt;table class="form-table"&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="company"&gt;Company Name&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input type="text" class="regular-text" name="company" value="&lt;?php echo esc_attr( $previous_value ); ?&gt;" id="company" /&gt;&lt;br /&gt; &lt;span class="description"&gt;Where are you?&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php } add_action( 'show_user_profile', 'custom_user_profile_fields' ); add_action( 'edit_user_profile', 'custom_user_profile_fields' ); add_action( "user_new_form", "custom_user_profile_fields" ); function save_custom_user_profile_fields($user_id){ if(!current_user_can('manage_options')) return false; # save my custom field if( isset($_POST['company']) ) { update_user_meta( $user_id, 'company', sanitize_text_field( $_POST['company'] ) ); } else { //Delete the company field if $_POST['company'] is not set delete_user_meta( $user_id, 'company', $meta_value ); } } add_action('user_register', 'save_custom_user_profile_fields'); add_action( 'personal_options_update', 'save_custom_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_custom_user_profile_fields' ); </code></pre> <p>Now i need to set 'company' as a post_meta.</p> <h2>EDIT</h2> <p>I have added in functions.php your code, and i set every three minutes WP Cron but i didn't found MySql table 'genere' in postmeta. I have changed 'company', now is 'genere', but it's the same.</p> <pre><code>function add_cron_recurrence_interval( $schedules ) { $schedules['every_three_minutes'] = array( 'interval' =&gt; 180, 'display' =&gt; __( 'Every 3 Minutes', 'textdomain' ) ); return $schedules; } add_filter( 'cron_schedules', 'add_cron_recurrence_interval' ); function author_company_post_sync() { global $wpdb; $posts= $wpdb-&gt;get_results("SELECT ID,post_author FROM ".$wpdb- &gt;prefix."posts"); foreach ($posts as $post) { $company = get_user_meta($post-&gt;post_author, 'genere', true); update_user_meta($post-&gt;ID, 'genere', $company); } } // schedule with WP Cron to run sync callback once daily... if (!wp_next_scheduled('author_company_post_sync')) { wp_schedule_event( time(), 'every_three_minutes', 'author_company_post_sync'); } </code></pre> <h2>EDIT</h2> <p>Here the solution: <a href="https://wordpress.stackexchange.com/questions/273198/user-meta-to-post">User meta to post</a></p>
[ { "answer_id": 270035, "author": "Pisuke Soramame", "author_id": 120818, "author_profile": "https://wordpress.stackexchange.com/users/120818", "pm_score": 1, "selected": false, "text": "<p>One possible solution is to add a metadata field to your post indicating the status (i.e. completed...
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121790/" ]
The plugin ***search and filter***, doesn't retrieve `author_meta`. So i need to add `post_meta` from `author_meta`. Is it possible? EDIT ---- I create user\_meta in this way: ``` function custom_user_profile_fields($user){ $previous_value = ''; if( is_object($user) && isset($user->ID) ) { $previous_value = get_user_meta( $user->ID, 'company', true ); } ?> <h3>Extra profile information</h3> <table class="form-table"> <tr> <th><label for="company">Company Name</label></th> <td> <input type="text" class="regular-text" name="company" value="<?php echo esc_attr( $previous_value ); ?>" id="company" /><br /> <span class="description">Where are you?</span> </td> </tr> </table> <?php } add_action( 'show_user_profile', 'custom_user_profile_fields' ); add_action( 'edit_user_profile', 'custom_user_profile_fields' ); add_action( "user_new_form", "custom_user_profile_fields" ); function save_custom_user_profile_fields($user_id){ if(!current_user_can('manage_options')) return false; # save my custom field if( isset($_POST['company']) ) { update_user_meta( $user_id, 'company', sanitize_text_field( $_POST['company'] ) ); } else { //Delete the company field if $_POST['company'] is not set delete_user_meta( $user_id, 'company', $meta_value ); } } add_action('user_register', 'save_custom_user_profile_fields'); add_action( 'personal_options_update', 'save_custom_user_profile_fields' ); add_action( 'edit_user_profile_update', 'save_custom_user_profile_fields' ); ``` Now i need to set 'company' as a post\_meta. EDIT ---- I have added in functions.php your code, and i set every three minutes WP Cron but i didn't found MySql table 'genere' in postmeta. I have changed 'company', now is 'genere', but it's the same. ``` function add_cron_recurrence_interval( $schedules ) { $schedules['every_three_minutes'] = array( 'interval' => 180, 'display' => __( 'Every 3 Minutes', 'textdomain' ) ); return $schedules; } add_filter( 'cron_schedules', 'add_cron_recurrence_interval' ); function author_company_post_sync() { global $wpdb; $posts= $wpdb->get_results("SELECT ID,post_author FROM ".$wpdb- >prefix."posts"); foreach ($posts as $post) { $company = get_user_meta($post->post_author, 'genere', true); update_user_meta($post->ID, 'genere', $company); } } // schedule with WP Cron to run sync callback once daily... if (!wp_next_scheduled('author_company_post_sync')) { wp_schedule_event( time(), 'every_three_minutes', 'author_company_post_sync'); } ``` EDIT ---- Here the solution: [User meta to post](https://wordpress.stackexchange.com/questions/273198/user-meta-to-post)
> > For example, let's say that Property is the post type. We would like > to display several different views (completed (built), for sale, and > for rent.) > > > Sure. Just make *Completed*, *For Sale*, and *For Rent* [taxonomies](https://codex.wordpress.org/Taxonomies) for the *Property* post type. Look into [WP\_Rewrite](https://developer.wordpress.org/reference/classes/wp_rewrite/generate_rewrite_rules/) class, too, and you can get greater control over url permalink structure.
270,129
<p>I am trying to setup rewrite rules for a custom homepage because we are planning on using full-screen slides and using a javascript pushstate to update the url instead of using formal WordPress pages. We decided using GET variables would be easiest in order to allow linking to a certain slide on the homepage, but it's not nice looking so I wanted to use rewrite rules in order to make everything slick and SEO friendly.</p> <p>Here's a few examples of what we are trying to do ("slide" is not a page/post in WP):</p> <pre><code>Nice URL: example.com/slide/something/ Ugly URL: example.com/?slide=something Nice URL: example.com/slide/videos/ Ugly URL: example.com/?slide=videos </code></pre> <p>Now, we have <em>no</em> problem with the ugly URLs, but my rewrite rule for this just isn't working. I have gone through several questions/answers on this but none of the accepted answers have been working. Here's what I have in functions.php:</p> <pre><code>add_action('init', 'add_rewrite_rules'); function add_rewrite_rules() { flush_rewrite_rules(); add_rewrite_rule( '^slide/([^/]*)/?$', 'index.php?slide=$matches[1]', 'top' ); } </code></pre> <p>I'm flushing rewrite rules while I try to get this working; I realize I shouldn't have this in there, being called on every refresh if this was a production site.</p> <p>If I try to go to example.com/slide/something/ I am <em>redirected</em> to the homepage.</p>
[ { "answer_id": 270131, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>Two problems I see- rewrite rules need to set query vars that will result in a successful main query. Setting just...
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270129", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100538/" ]
I am trying to setup rewrite rules for a custom homepage because we are planning on using full-screen slides and using a javascript pushstate to update the url instead of using formal WordPress pages. We decided using GET variables would be easiest in order to allow linking to a certain slide on the homepage, but it's not nice looking so I wanted to use rewrite rules in order to make everything slick and SEO friendly. Here's a few examples of what we are trying to do ("slide" is not a page/post in WP): ``` Nice URL: example.com/slide/something/ Ugly URL: example.com/?slide=something Nice URL: example.com/slide/videos/ Ugly URL: example.com/?slide=videos ``` Now, we have *no* problem with the ugly URLs, but my rewrite rule for this just isn't working. I have gone through several questions/answers on this but none of the accepted answers have been working. Here's what I have in functions.php: ``` add_action('init', 'add_rewrite_rules'); function add_rewrite_rules() { flush_rewrite_rules(); add_rewrite_rule( '^slide/([^/]*)/?$', 'index.php?slide=$matches[1]', 'top' ); } ``` I'm flushing rewrite rules while I try to get this working; I realize I shouldn't have this in there, being called on every refresh if this was a production site. If I try to go to example.com/slide/something/ I am *redirected* to the homepage.
Two problems I see- rewrite rules need to set query vars that will result in a successful main query. Setting just a custom var like `slide` doesn't parse to anything WordPress can load. Additionally, `slide` needs to be [added to the recognized query vars](https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars) for it to get parsed within a rule. So, what would a rule look like that would load the front page posts in the main query? That's a good question- the posts page is a special case, the absence of any other query vars. I haven't found a way to do that with a rule, though it may exist. An easier way to do this is with a rewrite endpoint: ``` function wpd_slide_endpoint(){ add_rewrite_endpoint( 'slide', EP_ROOT ); } add_action( 'init', 'wpd_slide_endpoint' ); ``` Keep in mind that if you have code accessing values via `$_GET`, this still won't work, because WordPress doesn't put query vars there when rules are parsed. You can change the code to use `get_query_var`, or just assign it before the code tries to access it: ``` $_GET['slide'] = get_query_var('slide'); ```
270,141
<p>Inside a WordPress loop, I'd like to conditionally check to see if the post has a title, in order to provide necessary wrapping HTML. If the post does not have a title, I don't want any of the wrapping HTML to appear.</p>
[ { "answer_id": 270142, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 3, "selected": true, "text": "<p>While you're in The Loop you can check against the <a href=\"https://codex.wordpress.org/Class_Reference/WP_...
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270141", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121798/" ]
Inside a WordPress loop, I'd like to conditionally check to see if the post has a title, in order to provide necessary wrapping HTML. If the post does not have a title, I don't want any of the wrapping HTML to appear.
While you're in The Loop you can check against the [WP\_Post Object](https://codex.wordpress.org/Class_Reference/WP_Post) like so: ``` <?php while( have_posts() ) : the_post(); ?> <?php if( ! empty( $post->post_title ) ) : ?> <h1><?php the_title(); ?></h1> <?php endif; ?> <?php endwhile; ?> ```
270,158
<p>Sorry for this, but I really combed everything there is on the subject and cannot come to the solution, although it is probably super-simple:</p> <p>I have a front-page.php set as the static front page of the WordPress site. In it there is a link that I'd like to link to the home.php or index.php.</p> <p>How do I write the url? </p> <pre><code>&lt;a href='&lt;?php echo esc_url( home_url()); ?&gt;' title='&lt;?php echo esc_attr( get_bloginfo( 'title' ) ); ?&gt;' rel='home'&gt; </code></pre> <p>What do i write instead of <em>home_url()</em> , which lands me of course on the front-page.php ? </p> <p>Thank you very much for your help!</p>
[ { "answer_id": 270159, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>There really should be a simpler way to do it but you kind of need to know that WordPress stores both the F...
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121586/" ]
Sorry for this, but I really combed everything there is on the subject and cannot come to the solution, although it is probably super-simple: I have a front-page.php set as the static front page of the WordPress site. In it there is a link that I'd like to link to the home.php or index.php. How do I write the url? ``` <a href='<?php echo esc_url( home_url()); ?>' title='<?php echo esc_attr( get_bloginfo( 'title' ) ); ?>' rel='home'> ``` What do i write instead of *home\_url()* , which lands me of course on the front-page.php ? Thank you very much for your help!
There really should be a simpler way to do it but you kind of need to know that WordPress stores both the Front Page ID and Blog Page ID in the options table. So, to get the URL of the blog you need to use both [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) and [`get_option()`](https://developer.wordpress.org/reference/functions/get_option/) in conjunction. ``` <a href='<?php echo esc_url( get_permalink( get_option( 'page_for_posts' ) ) ); ?>' title='<?php echo esc_attr( get_bloginfo( 'title' ) ); ?>' rel='home'>Blog Page</a> ``` The above will grab `page_for_posts` value from the options table which holds the Page ID of the blog which needs to be set in `Settings -> Readings`. By passing an ID to `get_permalink()` it will return the string URL that we need for the page.
270,166
<p>In <code>category-about.php</code> I have</p> <pre><code>&lt;?php /** * The template for displaying the posts in the About category * */ ?&gt; &lt;!-- category-about.php --&gt; &lt;?php get_header(); ?&gt; &lt;?php $args = array( 'post_type' =&gt; 'post', 'category_name' =&gt; 'about', ); ?&gt; &lt;?php // How to put this part in get_template_part ? $cat_name = $args['category_name']; $query = new WP_Query( $args ); if($query-&gt;have_posts()) : ?&gt; &lt;section id="&lt;?php echo $cat_name ?&gt;-section"&gt; &lt;h1 class="&lt;?php echo $cat_name ?&gt;-section-title"&gt; &lt;strong&gt;&lt;?php echo ucfirst($cat_name) ?&gt; Section&lt;/strong&gt; &lt;/h1&gt;&lt;?php while($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt; &lt;strong&gt;&lt;?php the_title(); ?&gt;&lt;/strong&gt; &lt;div &lt;?php post_class() ?&gt; &gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/section&gt; &lt;?php endif; wp_reset_query(); // end get_template_part ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>How can I have the variables from <code>category-about.php</code> in the template file <code>posts-loop.php</code>?</p> <p>Looking at <a href="http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459" rel="nofollow noreferrer">this comment</a> and <a href="https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part">this answer</a> I have trouble putting it all together.</p> <p>I would like to understand this better instead of using any of the helper functions provided in the answers. I understand that the correct way would be using <code>set_query_var</code> and <code>get_query_var</code> however I require a bit of assistance with that.</p> <p>Instead of writing the core loop code for each category I like to just define the <code>$args</code> in the category template and then make use of that in the template file. Any help is much appreciated.</p>
[ { "answer_id": 270168, "author": "lowtechsun", "author_id": 77054, "author_profile": "https://wordpress.stackexchange.com/users/77054", "pm_score": 3, "selected": false, "text": "<p>In <code>category-about.php</code> I have</p>\n\n<pre><code>&lt;?php\n/**\n * The template for displaying ...
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270166", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77054/" ]
In `category-about.php` I have ``` <?php /** * The template for displaying the posts in the About category * */ ?> <!-- category-about.php --> <?php get_header(); ?> <?php $args = array( 'post_type' => 'post', 'category_name' => 'about', ); ?> <?php // How to put this part in get_template_part ? $cat_name = $args['category_name']; $query = new WP_Query( $args ); if($query->have_posts()) : ?> <section id="<?php echo $cat_name ?>-section"> <h1 class="<?php echo $cat_name ?>-section-title"> <strong><?php echo ucfirst($cat_name) ?> Section</strong> </h1><?php while($query->have_posts()) : $query->the_post(); ?> <strong><?php the_title(); ?></strong> <div <?php post_class() ?> > <?php the_content(); ?> </div> <?php endwhile; ?> </section> <?php endif; wp_reset_query(); // end get_template_part ?> <?php get_footer(); ?> ``` How can I have the variables from `category-about.php` in the template file `posts-loop.php`? Looking at [this comment](http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459) and [this answer](https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part) I have trouble putting it all together. I would like to understand this better instead of using any of the helper functions provided in the answers. I understand that the correct way would be using `set_query_var` and `get_query_var` however I require a bit of assistance with that. Instead of writing the core loop code for each category I like to just define the `$args` in the category template and then make use of that in the template file. Any help is much appreciated.
In `category-about.php` I have ``` <?php /** * The template for displaying the posts in the About category * */ ?> <!-- category-about.php --> <?php get_header(); ?> <?php $args = array( 'post_type' => 'post', 'category_name' => 'about', ); ?> <?php // important bit set_query_var( 'query_category', $args ); get_template_part('template-parts/posts', 'loop'); ?> <?php get_footer(); ?> ``` and in template file `posts-loops.php` I now have ``` <!-- posts-loop.php --> <?php // important bit $args = get_query_var('query_category'); $cat_name = $args['category_name']; $query = new WP_Query( $args ); if($query->have_posts()) : ?> <section id="<?php echo $cat_name ?>-section"> <h1 class="<?php echo $cat_name ?>-section-title"> <strong><?php echo ucfirst($cat_name) ?> Section</strong> </h1><?php while($query->have_posts()) : $query->the_post(); ?> <strong><?php the_title(); ?></strong> <div <?php post_class() ?> > <?php the_content(); ?> </div> <?php endwhile; ?> </section> <?php endif; wp_reset_query(); ``` and it works. Reference: <http://keithdevon.com/passing-variables-to-get_template_part-in-wordpress/#comment-110459> <https://wordpress.stackexchange.com/a/176807/77054>
270,167
<p>I am trying to show a weblink to my WordPress users only if they are logged in. If they are logged out they will see text that says they need to "Login to View"</p> <p>My Original Code</p> <pre><code>&lt;a href="&lt;?php echo get_post_meta($post_id, 'external_link', true); ?&gt;"&gt;View Website&lt;/a&gt; </code></pre> <p>My Altered Code</p> <pre><code> &lt;a href="&lt;?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?&gt;"&gt;View Website&lt;/a&gt; </code></pre> <p>When a user is logged in, it's doing what it's supposed to but when they are logged out the url is broken. Can someone post an example of the format that it should be done?</p>
[ { "answer_id": 270169, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here's what you need:</p>\n\n<pre><code>&lt;?php\nif ( is_user_logged_in() ) {\n echo '&lt;a href...
2017/06/14
[ "https://wordpress.stackexchange.com/questions/270167", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121812/" ]
I am trying to show a weblink to my WordPress users only if they are logged in. If they are logged out they will see text that says they need to "Login to View" My Original Code ``` <a href="<?php echo get_post_meta($post_id, 'external_link', true); ?>">View Website</a> ``` My Altered Code ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?>">View Website</a> ``` When a user is logged in, it's doing what it's supposed to but when they are logged out the url is broken. Can someone post an example of the format that it should be done?
The code you posted: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?> ">View Website</a> ``` Is going to echo "Login to View" as the `href` attribute. You need something more like: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo wp_login_url( get_permalink() ); } ?>">View Website</a> ``` That of course won't be changing the text, just the `href`. So maybe do the conditional a step earlier (I added an arbitrary `<span>` for context): ``` <span> <?php if ( is_user_logged_in() ) { $href = esc_url( get_post_meta($post_id, 'external_link', true ) ); $text = 'View Website'; } else { $href = wp_login_url( get_permalink() ); $text = 'Login to View'; } ?> <a href="<?php echo $href; ?>" ><?php echo $text; ?></a> </span> ``` Since you're pulling the url from the db, I wrapped it in [esc\_url() for sanitization](https://codex.wordpress.org/Data_Validation#URLs).
270,176
<p>Basically as the title says I want to get list of categories and subcategories and then posts(with links to them) for those categories/subcategories.</p> <p>This is the structure I'm trying to achieve:</p> <ul> <li>Category 1</li> <ul> <li>Subcategory 1 within category 1</li> <ul> <li>Post 1 within subcategory 1</li> <li>Post 2 within subcategory 1</li> <li>Post 3 within subcategory 1</li> </ul> <li>Subcategory 2 within category 1</li> <ul> <li>Post 1 within subcategory 2</li> <li>Post 2 within subcategory 2</li> <li>Post 3 within subcategory 2</li> </ul> <li>Subcategory 3 within category 1</li> <ul> <li>Post 1 within subcategory 3</li> <li>Post 2 within subcategory 3</li> <li>Post 3 within subcategory 3</li> </ul> <li>Posts that have no subcategory</li> <ul> <li>Post 1 with no subcategory</li> <li>Post 1 with no subcategory</li> </ul> </ul> <li>Category 2</li> <ul> <li>Subcategory 1 within category 2</li> <ul> <li>Post 1 within subcategory 1</li> <li>Post 2 within subcategory 1</li> <li>Post 3 within subcategory 1</li> </ul> <li>Subcategory 2 within category 2</li> <ul> <li>Post 1 within subcategory 2</li> <li>Post 2 within subcategory 2</li> <li>Post 3 within subcategory 2</li> </ul> <li>Subcategory 3 within category 2</li> <ul> <li>Post 1 within subcategory 2</li> <li>Post 2 within subcategory 2</li> <li>Post 3 within subcategory 2</li> </ul> <li>Posts that have no subcategory</li> <ul> <li>Post 1 with no subcategory</li> <li>Post 1 with no subcategory</li> </ul> </ul> </ul> <p>Now so far after after reading everything I could found on the subject I have the following code:</p> <pre><code>&lt;ul&gt; &lt;?php $get_parent_cats = array( 'parent' =&gt; '0' //get top level categories only ); $all_categories = get_categories( $get_parent_cats );//get parent categories foreach( $all_categories as $single_category ){ //for each category, get the ID $catID = $single_category-&gt;cat_ID; echo '&lt;li&gt;&lt;a href=" ' . get_category_link( $catID ) . ' "&gt;' . $single_category-&gt;name . '&lt;/a&gt;'; //category name &amp; link $get_children_cats = array( 'child_of' =&gt; $catID //get children of this parent using the catID variable from earlier ); $child_cats = get_categories( $get_children_cats );//get children of parent category echo '&lt;ul class="children"&gt;'; foreach( $child_cats as $child_cat ){ //for each child category, get the ID $childID = $child_cat-&gt;cat_ID; //for each child category, give us the link and name echo '&lt;a href=" ' . get_category_link( $childID ) . ' "&gt;' . $child_cat-&gt;name . '&lt;/a&gt;'; } echo '&lt;/ul&gt;&lt;/li&gt;'; } //end of categories logic ?&gt; &lt;/ul&gt; </code></pre> <p>Now this code shows categories and subcategories well but I need to somehow loop through my posts and show them withing categories/subcategories. I have also tried to use fallowing code: </p> <pre><code> &lt;?php // get all the categories from the database $cats = get_categories(); // loop through the categries foreach ($cats as $cat) { // setup the cateogory ID $cat_id= $cat-&gt;term_id; // Make a header for the cateogry echo "&lt;h2&gt;".$cat-&gt;name."&lt;/h2&gt;"; // create a custom wordpress query query_posts("cat=$cat_id&amp;posts_per_page=100"); // start the wordpress loop! if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;?php // create our link now that the post is setup ?&gt; &lt;a href="&lt;?php the_permalink();?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php echo '&lt;hr/&gt;'; ?&gt; &lt;?php endwhile; endif; // done our wordpress loop. Will start again for each category ?&gt; &lt;?php } // done the foreach statement ?&gt; &lt;/div&gt;&lt;!-- #content --&gt; &lt;/div&gt;&lt;!-- #container --&gt; </code></pre> <p>This code shows all categories and posts within particular category, but the structure is not the one I want. I have been trying to combine these two snippets of code for two days, but nothing I try gives me the result I want. I am inexperienced with Wordpress and I could really use help with this.</p>
[ { "answer_id": 270169, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here's what you need:</p>\n\n<pre><code>&lt;?php\nif ( is_user_logged_in() ) {\n echo '&lt;a href...
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119868/" ]
Basically as the title says I want to get list of categories and subcategories and then posts(with links to them) for those categories/subcategories. This is the structure I'm trying to achieve: * Category 1 + Subcategory 1 within category 1 - Post 1 within subcategory 1 - Post 2 within subcategory 1 - Post 3 within subcategory 1 + Subcategory 2 within category 1 - Post 1 within subcategory 2 - Post 2 within subcategory 2 - Post 3 within subcategory 2 + Subcategory 3 within category 1 - Post 1 within subcategory 3 - Post 2 within subcategory 3 - Post 3 within subcategory 3 + Posts that have no subcategory - Post 1 with no subcategory - Post 1 with no subcategory * Category 2 + Subcategory 1 within category 2 - Post 1 within subcategory 1 - Post 2 within subcategory 1 - Post 3 within subcategory 1 + Subcategory 2 within category 2 - Post 1 within subcategory 2 - Post 2 within subcategory 2 - Post 3 within subcategory 2 + Subcategory 3 within category 2 - Post 1 within subcategory 2 - Post 2 within subcategory 2 - Post 3 within subcategory 2 + Posts that have no subcategory - Post 1 with no subcategory - Post 1 with no subcategory Now so far after after reading everything I could found on the subject I have the following code: ``` <ul> <?php $get_parent_cats = array( 'parent' => '0' //get top level categories only ); $all_categories = get_categories( $get_parent_cats );//get parent categories foreach( $all_categories as $single_category ){ //for each category, get the ID $catID = $single_category->cat_ID; echo '<li><a href=" ' . get_category_link( $catID ) . ' ">' . $single_category->name . '</a>'; //category name & link $get_children_cats = array( 'child_of' => $catID //get children of this parent using the catID variable from earlier ); $child_cats = get_categories( $get_children_cats );//get children of parent category echo '<ul class="children">'; foreach( $child_cats as $child_cat ){ //for each child category, get the ID $childID = $child_cat->cat_ID; //for each child category, give us the link and name echo '<a href=" ' . get_category_link( $childID ) . ' ">' . $child_cat->name . '</a>'; } echo '</ul></li>'; } //end of categories logic ?> </ul> ``` Now this code shows categories and subcategories well but I need to somehow loop through my posts and show them withing categories/subcategories. I have also tried to use fallowing code: ``` <?php // get all the categories from the database $cats = get_categories(); // loop through the categries foreach ($cats as $cat) { // setup the cateogory ID $cat_id= $cat->term_id; // Make a header for the cateogry echo "<h2>".$cat->name."</h2>"; // create a custom wordpress query query_posts("cat=$cat_id&posts_per_page=100"); // start the wordpress loop! if (have_posts()) : while (have_posts()) : the_post(); ?> <?php // create our link now that the post is setup ?> <a href="<?php the_permalink();?>"><?php the_title(); ?></a> <?php echo '<hr/>'; ?> <?php endwhile; endif; // done our wordpress loop. Will start again for each category ?> <?php } // done the foreach statement ?> </div><!-- #content --> </div><!-- #container --> ``` This code shows all categories and posts within particular category, but the structure is not the one I want. I have been trying to combine these two snippets of code for two days, but nothing I try gives me the result I want. I am inexperienced with Wordpress and I could really use help with this.
The code you posted: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?> ">View Website</a> ``` Is going to echo "Login to View" as the `href` attribute. You need something more like: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo wp_login_url( get_permalink() ); } ?>">View Website</a> ``` That of course won't be changing the text, just the `href`. So maybe do the conditional a step earlier (I added an arbitrary `<span>` for context): ``` <span> <?php if ( is_user_logged_in() ) { $href = esc_url( get_post_meta($post_id, 'external_link', true ) ); $text = 'View Website'; } else { $href = wp_login_url( get_permalink() ); $text = 'Login to View'; } ?> <a href="<?php echo $href; ?>" ><?php echo $text; ?></a> </span> ``` Since you're pulling the url from the db, I wrapped it in [esc\_url() for sanitization](https://codex.wordpress.org/Data_Validation#URLs).
270,187
<p>I've created a shortcode that should be showing an image depending on the day of the week.</p> <pre><code> function custom_shortcode() { return '&lt;img src="/wp-content/themes/coworker/images/daily-social-image-' . the_weekday() . '.gif" width="100%" /&gt;'; } add_shortcode( 'weekday', 'custom_shortcode' ); </code></pre> <p>The issue being that the function <code>the_weekday()</code> is not working - the rest of the code appears to be working correctly.</p>
[ { "answer_id": 270169, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>Here's what you need:</p>\n\n<pre><code>&lt;?php\nif ( is_user_logged_in() ) {\n echo '&lt;a href...
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270187", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100731/" ]
I've created a shortcode that should be showing an image depending on the day of the week. ``` function custom_shortcode() { return '<img src="/wp-content/themes/coworker/images/daily-social-image-' . the_weekday() . '.gif" width="100%" />'; } add_shortcode( 'weekday', 'custom_shortcode' ); ``` The issue being that the function `the_weekday()` is not working - the rest of the code appears to be working correctly.
The code you posted: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo 'Login to View'; } ?> ">View Website</a> ``` Is going to echo "Login to View" as the `href` attribute. You need something more like: ``` <a href="<?php if ( is_user_logged_in() ) { echo get_post_meta($post_id, 'external_link', true); } else { echo wp_login_url( get_permalink() ); } ?>">View Website</a> ``` That of course won't be changing the text, just the `href`. So maybe do the conditional a step earlier (I added an arbitrary `<span>` for context): ``` <span> <?php if ( is_user_logged_in() ) { $href = esc_url( get_post_meta($post_id, 'external_link', true ) ); $text = 'View Website'; } else { $href = wp_login_url( get_permalink() ); $text = 'Login to View'; } ?> <a href="<?php echo $href; ?>" ><?php echo $text; ?></a> </span> ``` Since you're pulling the url from the db, I wrapped it in [esc\_url() for sanitization](https://codex.wordpress.org/Data_Validation#URLs).
270,209
<p>There is a plugin that uses a class; and create an object like this:</p> <pre><code>class WC_Disability_VAT_Exemption { public function __construct() { add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } public function exemption_field() { //some code here } } /** * Return instance of WC_Disability_VAT_Exemption. * * @since 1.3.3 * * @return WC_Disability_VAT_Exemption */ function wc_dve() { static $instance; if ( ! isset( $instance ) ) { $instance = new WC_Disability_VAT_Exemption(); } return $instance; } wc_dve(); </code></pre> <p>I want to extend the class because I want to use this method to remove an action:</p> <pre><code>class WC_Disability_VAT_Exemption_Extend extends WC_Disability_VAT_Exemption { function __construct() { $this-&gt;unregister_parent_hook(); add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } function unregister_parent_hook() { global $instance; remove_action( 'woocommerce_after_order_notes', array( $instance, 'exemption_field' ) ); } function exemption_field() { //---some code here } } </code></pre> <p>But <code>global $instance</code> doesn't get the class object. It returns <em>null</em>. So how can I get <code>$instance</code> object in the extended class?</p>
[ { "answer_id": 270212, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>Well, you used <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer...
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57671/" ]
There is a plugin that uses a class; and create an object like this: ``` class WC_Disability_VAT_Exemption { public function __construct() { add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } public function exemption_field() { //some code here } } /** * Return instance of WC_Disability_VAT_Exemption. * * @since 1.3.3 * * @return WC_Disability_VAT_Exemption */ function wc_dve() { static $instance; if ( ! isset( $instance ) ) { $instance = new WC_Disability_VAT_Exemption(); } return $instance; } wc_dve(); ``` I want to extend the class because I want to use this method to remove an action: ``` class WC_Disability_VAT_Exemption_Extend extends WC_Disability_VAT_Exemption { function __construct() { $this->unregister_parent_hook(); add_action( 'woocommerce_after_order_notes', array( $this, 'exemption_field' ) ); } function unregister_parent_hook() { global $instance; remove_action( 'woocommerce_after_order_notes', array( $instance, 'exemption_field' ) ); } function exemption_field() { //---some code here } } ``` But `global $instance` doesn't get the class object. It returns *null*. So how can I get `$instance` object in the extended class?
Woocommerce support sent me the solution of my problem: ``` function unregister_parent_hook() { if ( function_exists( 'wc_dve' ) ) { $instance = wc_dve(); remove_action( 'woocommerce_after_order_notes', array( $instance, 'exemption_field' ) ); } } ```
270,218
<p>I am stuck in a situation where the requirement is to create a custom email template for a particular product category, so that when any user buy product from that category he/she get that customised order email. Please help if anyone have any idea about how this can be achieved. Thanks in advance.</p>
[ { "answer_id": 270256, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Whatever plugin you're using for ecommerce, there should be an email hook available to customize the emai...
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121842/" ]
I am stuck in a situation where the requirement is to create a custom email template for a particular product category, so that when any user buy product from that category he/she get that customised order email. Please help if anyone have any idea about how this can be achieved. Thanks in advance.
Firstly extend WC\_Email class to define the email header, subject, email template for content secondly, add custom email class to the default WooCommerce email classes using woocommerce\_email\_classes filter, with trigger that calls terms ``` if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) ) ``` lastly, Create an email template to be used to generate email content for your custom email. this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. <https://cloudredux.com/adding-sending-custom-woocommerce-email/>
270,229
<p>I am working with underscores me trying to build a template by my own.</p> <p>I have build a homepage template and also a single-post file for the custom post types.</p> <p>What I am trying to get its to display in the homepage a kind of gallery with the featured images from each custom post type with title and tags.</p> <p>Have tried different ways, i guessed it would be something with <code>wp_get_archives</code> but still didn't get it. </p> <p>If you have some suggestions would be awesome.</p> <p>Thanks!</p>
[ { "answer_id": 270256, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Whatever plugin you're using for ecommerce, there should be an email hook available to customize the emai...
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270229", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120964/" ]
I am working with underscores me trying to build a template by my own. I have build a homepage template and also a single-post file for the custom post types. What I am trying to get its to display in the homepage a kind of gallery with the featured images from each custom post type with title and tags. Have tried different ways, i guessed it would be something with `wp_get_archives` but still didn't get it. If you have some suggestions would be awesome. Thanks!
Firstly extend WC\_Email class to define the email header, subject, email template for content secondly, add custom email class to the default WooCommerce email classes using woocommerce\_email\_classes filter, with trigger that calls terms ``` if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) ) ``` lastly, Create an email template to be used to generate email content for your custom email. this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. <https://cloudredux.com/adding-sending-custom-woocommerce-email/>
270,235
<p>I'm trying to make booking - plugin with form on WordPress-admin site, where I can add new event in calendar (made with JavaScript). I have to submit form with all data and insert data to MySQL Database.</p> <p>My <strong>ajax.js</strong> file:</p> <pre><code>function ajaxSubmit(e){ var nazwa_szkolenia = document.getElementById(&quot;nazwa_szkolenia&quot;).value; var Data_szkolenia = document.getElementById(&quot;Data_szkolenia&quot;).value; var Godzina = document.getElementById(&quot;Godzina&quot;).value; var Max_pacjent = document.getElementById(&quot;Max_pacjent&quot;).value; // Returns successful data submission message when the entered information is stored in database. var dataString = 'nazwa_szkolenia1=' + nazwa_szkolenia + '&amp;Data_szkolenia1=' + Data_szkolenia + '&amp;Godzina1=' + Godzina + '&amp;Max_pacjent1=' + Max_pacjent; if (nazwa_szkolenia == '' || Data_szkolenia == '' || Max_pacjent == '') { alert(&quot;fill all fields&quot;); } else { // prevent the default action. e.preventDefault(); var myform= jQuery(this).serialize(); jQuery.ajax({ type:&quot;POST&quot;, // Get the admin ajax url which we have passed through wp_localize_script(). url: ajax_object.ajax_url, action: &quot;submitAjaxForm&quot;, data: dataString, error: function(jqXHR, textStatus, errorThrown){ console.error(&quot;The following error occurred: &quot; + textStatus, errorThrown); }, success:function(data){ alert(&quot;process OK&quot;); } }); } return false; } </code></pre> <p><strong>arcode-functions.php</strong>:</p> <pre><code>&lt;?php add_action('init', 'registerFormAction'); function registerFormAction(){ add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback'); add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback'); } function submitAjaxForm_callback(){ global $wpdb; $nazwa_szkolenia2 = $_POST['nazwa_szkolenia1']; $Data_szkolenia2 = $_POST['Data_szkolenia1']; $Godzina2 = $_POST['Godzina1']; $Max_pacjent2 = $_POST['Max_pacjent1']; $wpdb-&gt;insert( $wpdb-&gt;modul_terminarz, array( 'proba' =&gt; $nazwa_szkolenia2, 'id' =&gt; '10', 'data_szkolenia' =&gt; $Data_szkolenia2, 'typ_szkolenia' =&gt; '1', 'ile_miejsc' =&gt; $Max_pacjent2, 'pelne' =&gt; '1', 'Ile_miejsc_akt' =&gt; '4' ) ); wp_die(); } ?&gt; </code></pre> <p>I've added <code>admin-ajax.php</code> with <code>wp_localize_script</code> function. The form button is made with JavaScript:</p> <pre><code>var Input_Form_Send = document.createElement('input'); Input_Form_Send.value = 'Utwórz'; Input_Form_Send.type = 'submit'; Input_Form_Send.className = 'input-form-send'; Input_Form_Send.onclick = ajaxSubmit; </code></pre> <p>When I fill all fields from form, click on the button, then comes alert &quot;process ok&quot;, but on the Database comes nothing new... <em>nazwa_szkolenia</em>, <em>Data_szkolenia</em>, <em>Godzina</em>, <em>Max_pacjent</em> -those are the names of the form fields.</p> <p>Maybe you know what I've made wrong?</p>
[ { "answer_id": 270256, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Whatever plugin you're using for ecommerce, there should be an email hook available to customize the emai...
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270235", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121854/" ]
I'm trying to make booking - plugin with form on WordPress-admin site, where I can add new event in calendar (made with JavaScript). I have to submit form with all data and insert data to MySQL Database. My **ajax.js** file: ``` function ajaxSubmit(e){ var nazwa_szkolenia = document.getElementById("nazwa_szkolenia").value; var Data_szkolenia = document.getElementById("Data_szkolenia").value; var Godzina = document.getElementById("Godzina").value; var Max_pacjent = document.getElementById("Max_pacjent").value; // Returns successful data submission message when the entered information is stored in database. var dataString = 'nazwa_szkolenia1=' + nazwa_szkolenia + '&Data_szkolenia1=' + Data_szkolenia + '&Godzina1=' + Godzina + '&Max_pacjent1=' + Max_pacjent; if (nazwa_szkolenia == '' || Data_szkolenia == '' || Max_pacjent == '') { alert("fill all fields"); } else { // prevent the default action. e.preventDefault(); var myform= jQuery(this).serialize(); jQuery.ajax({ type:"POST", // Get the admin ajax url which we have passed through wp_localize_script(). url: ajax_object.ajax_url, action: "submitAjaxForm", data: dataString, error: function(jqXHR, textStatus, errorThrown){ console.error("The following error occurred: " + textStatus, errorThrown); }, success:function(data){ alert("process OK"); } }); } return false; } ``` **arcode-functions.php**: ``` <?php add_action('init', 'registerFormAction'); function registerFormAction(){ add_action('wp_ajax_nopriv_submitAjaxForm','submitAjaxForm_callback'); add_action('wp_ajax_submitAjaxForm','submitAjaxForm_callback'); } function submitAjaxForm_callback(){ global $wpdb; $nazwa_szkolenia2 = $_POST['nazwa_szkolenia1']; $Data_szkolenia2 = $_POST['Data_szkolenia1']; $Godzina2 = $_POST['Godzina1']; $Max_pacjent2 = $_POST['Max_pacjent1']; $wpdb->insert( $wpdb->modul_terminarz, array( 'proba' => $nazwa_szkolenia2, 'id' => '10', 'data_szkolenia' => $Data_szkolenia2, 'typ_szkolenia' => '1', 'ile_miejsc' => $Max_pacjent2, 'pelne' => '1', 'Ile_miejsc_akt' => '4' ) ); wp_die(); } ?> ``` I've added `admin-ajax.php` with `wp_localize_script` function. The form button is made with JavaScript: ``` var Input_Form_Send = document.createElement('input'); Input_Form_Send.value = 'Utwórz'; Input_Form_Send.type = 'submit'; Input_Form_Send.className = 'input-form-send'; Input_Form_Send.onclick = ajaxSubmit; ``` When I fill all fields from form, click on the button, then comes alert "process ok", but on the Database comes nothing new... *nazwa\_szkolenia*, *Data\_szkolenia*, *Godzina*, *Max\_pacjent* -those are the names of the form fields. Maybe you know what I've made wrong?
Firstly extend WC\_Email class to define the email header, subject, email template for content secondly, add custom email class to the default WooCommerce email classes using woocommerce\_email\_classes filter, with trigger that calls terms ``` if ( has_term( 'Your Cat', 'product_cat', $item['product_id'] ) ) ``` lastly, Create an email template to be used to generate email content for your custom email. this answer to this question involves a lot of code, far too much for SO so you may want to do some reading like. <https://cloudredux.com/adding-sending-custom-woocommerce-email/>
270,253
<p>I display a wp_editor on the front-end and everything was going fine until a recent WP update.</p> <p>Now, the "insert/edit link" is not working due to a Javascript error:</p> <pre><code>Uncaught TypeError: Cannot set property 'tempHide' of undefined </code></pre> <p>This error only appears on front-end. The back-end is going fine.</p> <p>I've looked for it on StackExchange and Google. Maybe I'm not using the right keywords, but I don't find anyone with the same problem...</p> <p>Has anyone an idea?</p>
[ { "answer_id": 270269, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I suspect a theme error. Try a different theme (like the standard ones - Twenty-whatevers).</p>\n" }...
2017/06/15
[ "https://wordpress.stackexchange.com/questions/270253", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121184/" ]
I display a wp\_editor on the front-end and everything was going fine until a recent WP update. Now, the "insert/edit link" is not working due to a Javascript error: ``` Uncaught TypeError: Cannot set property 'tempHide' of undefined ``` This error only appears on front-end. The back-end is going fine. I've looked for it on StackExchange and Google. Maybe I'm not using the right keywords, but I don't find anyone with the same problem... Has anyone an idea?
I found it at last! Using the browser debugger, I found that there was a "editor.wp" which was undefined (in the complete version of the js file). Then I understood that the "wordpress" plugin was not used in the editor. When calling the function wp\_editor, I was setting a list of plugin : paste, wplink, textcolor. It was working until a specific WordPress update. I just had to add the "wordpress" plugin in the list, and now it's working.