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
258,053
<p>I am using Remove product-category slug plugin works with 1 subcategroy not with 2. Like:</p> <pre><code>www.domain.com/europe/netherlands/amsterdam (doesn't work) www.domain.com/product-categorie/europe/netherlands/amsterdam (work) www.domain.com/europe/netherlands (work) www.domain.com/product-categorie/europe/netherlands (work) </code></pre> <p>Plugincode:</p> <pre><code>/* Plugin Name: Remove product-category slug Plugin URI: https://timersys.com/ Description: Check if url slug matches a woocommerce product category and use it instead Version: 0.1 Author: Timersys License: GPLv2 or later */ add_filter('request', function( $vars ) { global $wpdb; if( ! empty( $vars['pagename'] ) || ! empty( $vars['category_name'] ) || ! empty( $vars['name'] ) || ! empty( $vars['attachment'] ) ) { $slug = ! empty( $vars['pagename'] ) ? $vars['pagename'] : ( ! empty( $vars['name'] ) ? $vars['name'] : ( !empty( $vars['category_name'] ) ? $vars['category_name'] : $vars['attachment'] ) ); $exists = $wpdb-&gt;get_var( $wpdb-&gt;prepare( "SELECT t.term_id FROM $wpdb-&gt;terms t LEFT JOIN $wpdb-&gt;term_taxonomy tt ON tt.term_id = t.term_id WHERE tt.taxonomy = 'product_cat' AND t.slug = %s" ,array( $slug ))); if( $exists ){ $old_vars = $vars; $vars = array('product_cat' =&gt; $slug ); if ( !empty( $old_vars['paged'] ) || !empty( $old_vars['page'] ) ) $vars['paged'] = ! empty( $old_vars['paged'] ) ? $old_vars['paged'] : $old_vars['page']; if ( !empty( $old_vars['orderby'] ) ) $vars['orderby'] = $old_vars['orderby']; if ( !empty( $old_vars['order'] ) ) $vars['order'] = $old_vars['order']; } } return $vars; }); </code></pre> <p>How can i achieve this?</p>
[ { "answer_id": 258032, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<h1>WordPress way (recommended):</h1>\n\n<p>In your plugin, use the WordPress <code>theme_file_path</code> filter hook to change the file from the plugin. Use the following CODE in your plugin:</p>\n\n<pre><code>add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 );\nfunction wpse_258026_modify_theme_include_file( $path, $file = '' ) {\n if( 'includes/example-file.php' === $file ) {\n // change path here as required\n return plugin_dir_path( __FILE__ ) . 'includes/example-file.php';\n }\n return $path;\n}\n</code></pre>\n\n<p>Then you may include the file in your theme using the <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_theme_file_path</code></a> function, like this:</p>\n\n<pre><code>include get_theme_file_path( 'includes/example-file.php' );\n</code></pre>\n\n<p>Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included.</p>\n\n<p>Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification. </p>\n\n<h1>Controlling Page Template from Plugin:</h1>\n\n<p>If you are looking for controlling page templates from your plugin, then you may <a href=\"https://wordpress.stackexchange.com/a/257674/110572\">check out this answer</a> to see how to do it.</p>\n\n<h1>PHP way:</h1>\n\n<p>If you are including the <code>wp-content/theme/&lt;your-theme&gt;/includes/example-file.php</code> file using simple <code>include</code> call with <strong>relative path</strong> inside header, footer templates like the following:</p>\n\n<pre><code>include 'includes/example-file.php';\n</code></pre>\n\n<p>then it's also possible to replace it with the plugin's version of <code>includes/example-file.php</code> file using PHP <code>set_include_path()</code> function.</p>\n\n<p>Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path: </p>\n\n<pre><code>set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() );\n</code></pre>\n\n<p>After that, for any <code>include</code> with relative path in <code>header.php</code>, <code>footer.php</code> etc. PHP will look for the file in your plugin's directory first.</p>\n\n<blockquote>\n <p>However, this method <strong><em>will not work</em></strong> if you include the file using absolute path in your header, footer etc.</p>\n</blockquote>\n" }, { "answer_id": 258114, "author": "Sonali", "author_id": 84167, "author_profile": "https://wordpress.stackexchange.com/users/84167", "pm_score": 0, "selected": false, "text": "<p>Try this one.This works if you are using page templates.</p>\n\n<pre><code>add_filter(\"page_template\", \"plugin_function_name\");\nfunction plugin_function_name($page_template)\n{\n $id = substr($page_template, strrpos($page_template, '/') + 1);\n if ($id == 'includes/example-file.php') {\n $page_template = plugin_dir_path(__FILE__) . 'includes/example-file.php';\n }\n return $page_template;\n}\n</code></pre>\n" } ]
2017/02/26
[ "https://wordpress.stackexchange.com/questions/258053", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35917/" ]
I am using Remove product-category slug plugin works with 1 subcategroy not with 2. Like: ``` www.domain.com/europe/netherlands/amsterdam (doesn't work) www.domain.com/product-categorie/europe/netherlands/amsterdam (work) www.domain.com/europe/netherlands (work) www.domain.com/product-categorie/europe/netherlands (work) ``` Plugincode: ``` /* Plugin Name: Remove product-category slug Plugin URI: https://timersys.com/ Description: Check if url slug matches a woocommerce product category and use it instead Version: 0.1 Author: Timersys License: GPLv2 or later */ add_filter('request', function( $vars ) { global $wpdb; if( ! empty( $vars['pagename'] ) || ! empty( $vars['category_name'] ) || ! empty( $vars['name'] ) || ! empty( $vars['attachment'] ) ) { $slug = ! empty( $vars['pagename'] ) ? $vars['pagename'] : ( ! empty( $vars['name'] ) ? $vars['name'] : ( !empty( $vars['category_name'] ) ? $vars['category_name'] : $vars['attachment'] ) ); $exists = $wpdb->get_var( $wpdb->prepare( "SELECT t.term_id FROM $wpdb->terms t LEFT JOIN $wpdb->term_taxonomy tt ON tt.term_id = t.term_id WHERE tt.taxonomy = 'product_cat' AND t.slug = %s" ,array( $slug ))); if( $exists ){ $old_vars = $vars; $vars = array('product_cat' => $slug ); if ( !empty( $old_vars['paged'] ) || !empty( $old_vars['page'] ) ) $vars['paged'] = ! empty( $old_vars['paged'] ) ? $old_vars['paged'] : $old_vars['page']; if ( !empty( $old_vars['orderby'] ) ) $vars['orderby'] = $old_vars['orderby']; if ( !empty( $old_vars['order'] ) ) $vars['order'] = $old_vars['order']; } } return $vars; }); ``` How can i achieve this?
WordPress way (recommended): ============================ In your plugin, use the WordPress `theme_file_path` filter hook to change the file from the plugin. Use the following CODE in your plugin: ``` add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 ); function wpse_258026_modify_theme_include_file( $path, $file = '' ) { if( 'includes/example-file.php' === $file ) { // change path here as required return plugin_dir_path( __FILE__ ) . 'includes/example-file.php'; } return $path; } ``` Then you may include the file in your theme using the [`get_theme_file_path`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) function, like this: ``` include get_theme_file_path( 'includes/example-file.php' ); ``` Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included. Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification. Controlling Page Template from Plugin: ====================================== If you are looking for controlling page templates from your plugin, then you may [check out this answer](https://wordpress.stackexchange.com/a/257674/110572) to see how to do it. PHP way: ======== If you are including the `wp-content/theme/<your-theme>/includes/example-file.php` file using simple `include` call with **relative path** inside header, footer templates like the following: ``` include 'includes/example-file.php'; ``` then it's also possible to replace it with the plugin's version of `includes/example-file.php` file using PHP `set_include_path()` function. Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path: ``` set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() ); ``` After that, for any `include` with relative path in `header.php`, `footer.php` etc. PHP will look for the file in your plugin's directory first. > > However, this method ***will not work*** if you include the file using absolute path in your header, footer etc. > > >
258,055
<p>Lets say I have custom field on post editor, and I change value from <strong>AAA</strong> to <strong>ZZZ</strong>.. :</p> <pre><code>add_action('save_post', function($post){ $value = get_post_meta($post-&gt;ID, 'mykey'); } , 1); </code></pre> <p>How to get the old value (<strong>AAA</strong>) of that meta-key? during save_post (even earlier 1st priority), I get <strong>ZZZ</strong></p>
[ { "answer_id": 258065, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p><code>save_post</code> Runs whenever a post or page is created or updated, which\n could be from an import, post/page edit form, xmlrpc, or post by\n email. Action function arguments: post ID and post object. Runs after\n the data is saved to the database.</p>\n</blockquote>\n\n<p>above paragraph is quoted from WP Codex. </p>\n\n<p>so you cannot use this hook to get older value because it fires after saving new values to DB. WP has another action hook named <code>wp_insert_post</code>but sadly this hook does same thing as <code>save_post</code> </p>\n\n<p>alternatively you can use Filters to get the job done. WP provides few filter to edit the post while saving or before saving to DB. like <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data\" rel=\"nofollow noreferrer\"><code>wp_insert_post_data</code></a> &amp; <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/content_save_pre\" rel=\"nofollow noreferrer\"><code>content_save_pre</code></a> might work for you, i think.</p>\n\n<p><strong>Update</strong></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/35931/how-can-i-edit-post-data-before-it-is-saved\">here</a> is another discussionon this topic which might be helpful for you. </p>\n" }, { "answer_id": 258072, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 2, "selected": false, "text": "<p>The trick I did was:</p>\n\n<p>1) Created a hidden meta box, where I inserted input, with value of <code>current_meta_value</code><br/>\n2) during <code>save_post</code> i checked it against to <code>new_meta_value</code>.</p>\n\n<p>that was all.</p>\n" }, { "answer_id": 386799, "author": "Zeth", "author_id": 128304, "author_profile": "https://wordpress.stackexchange.com/users/128304", "pm_score": 0, "selected": false, "text": "<p>This might be against the WordPress-rules or something. But I got this working:</p>\n<pre><code>add_action( 'save_post', 'wp258055_save_post_callback' );\n\nfunction wp258055_save_post_callback( $post_id ){\n $value_in_db = get_post_meta( $post_id, 'mykey', true );\n $value_about_to_be_saved = $_POST['mykey'];\n}\n</code></pre>\n" } ]
2017/02/26
[ "https://wordpress.stackexchange.com/questions/258055", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33667/" ]
Lets say I have custom field on post editor, and I change value from **AAA** to **ZZZ**.. : ``` add_action('save_post', function($post){ $value = get_post_meta($post->ID, 'mykey'); } , 1); ``` How to get the old value (**AAA**) of that meta-key? during save\_post (even earlier 1st priority), I get **ZZZ**
> > `save_post` Runs whenever a post or page is created or updated, which > could be from an import, post/page edit form, xmlrpc, or post by > email. Action function arguments: post ID and post object. Runs after > the data is saved to the database. > > > above paragraph is quoted from WP Codex. so you cannot use this hook to get older value because it fires after saving new values to DB. WP has another action hook named `wp_insert_post`but sadly this hook does same thing as `save_post` alternatively you can use Filters to get the job done. WP provides few filter to edit the post while saving or before saving to DB. like [`wp_insert_post_data`](https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data) & [`content_save_pre`](https://codex.wordpress.org/Plugin_API/Filter_Reference/content_save_pre) might work for you, i think. **Update** [here](https://wordpress.stackexchange.com/questions/35931/how-can-i-edit-post-data-before-it-is-saved) is another discussionon this topic which might be helpful for you.
258,094
<p>I have 10 big dropdown select combo boxes of hundreds of font-faces, including System Fonts and Google Fonts. All combo boxes carry the same values.</p> <p>There are two more combo boxes for each of the boxes above, for loading the language and the font-weight sets. These should only be visible/active if the selected font is a Google font.</p> <p>I'm getting all the font-faces in the select lists through a JSON file via <code>json_decode</code>. Before, I was using separate combo boxes for System Fonts and Google Fonts, and the task was little simpler than what I have now.</p> <p>JSON file is like below (just an example): </p> <pre><code>{ "fonts":[ "Arial", "Helvetica", "Georgia", "Aclonica", "Acme", "Actor", "Adamina", "Advent Pro", "Aguafina Script" ] } </code></pre> <p>Then I'm using a function (call it JSON_fonts) to get all these values from the JSON file as an array.</p> <pre><code>$wp_customize-&gt;add_control( 'font_1', array( 'label' =&gt; esc_html( 'Body Font', 'my_theme' ), 'section' =&gt; 'typography', 'type' =&gt; 'select', 'choices' =&gt; JSON_fonts() ) ); </code></pre> <p>(I think I should use separate JSON files for System fonts and Google Fonts).</p> <p>What I want to do is, to assign keys to the fonts in the select boxes to detect their type (is it a system font or Google).</p> <p>If the selected value is a Google font, then:</p> <ol> <li>Collect it in an variable to use it further for en-queuing.</li> <li>Enable the language and font-weight select boxes for the respective font-face.</li> </ol> <p>En-queuing is not a problem, but getting the type of the font and the unique values is very problematic to me.</p> <ul> <li>Complexity 1: Getting the font-type</li> <li>Complexity 2: If the fonts match, merge their respective language and font-weight lists (one-to-one matching will be too much code).</li> <li>Complexity 3: Asking <code>wp-ajax</code> to reload the font without refreshing the customizer.</li> </ul> <p>Any help would be greatly appreciated. Also, feel free to share your ideas to bring down the complexity-level.</p>
[ { "answer_id": 260629, "author": "ricotheque", "author_id": 34238, "author_profile": "https://wordpress.stackexchange.com/users/34238", "pm_score": 0, "selected": false, "text": "<p>What you can do is add a prefix to each choice <code>key</code> for each Google font, so that your choices would look something like this:</p>\n\n<pre><code>$choices = array(\n '_google_open_sans' =&gt; 'Open Sans',\n '_google_titillium' =&gt; 'Titillium Web',\n 'arial' =&gt; 'Arial',\n);\n</code></pre>\n\n<p>Then, when you go through your list of selected fonts, you can just check for the <code>_google_</code> prefix in the key. You can use the <a href=\"https://github.com/typekit/webfontloader\" rel=\"nofollow noreferrer\">Web Font Loader</a> to update the Customizer without refreshing. Just plug into a <a href=\"https://make.wordpress.org/core/2016/02/16/selective-refresh-in-the-customizer/\" rel=\"nofollow noreferrer\">selective refresh</a>.</p>\n\n<p><strong>A bit too complicated?</strong></p>\n\n<p>I actually tried above approach for a theme I made for a client. I used the Google Fonts API to pull in the list of fonts, cache it, then mix it up with a pre-generated list of system fonts, all for the font selector dropdowns.</p>\n\n<p>However, the final system was a bit unwieldy. I replaced each dropdown with two text boxes. The first specified what Google Font import statement to execute (like <code>Titillium+Web:400,400i,600,600i</code>), while the second specified the font-family (like <code>\"Titillium Web\", Arial, sans-serif</code>).</p>\n\n<p>This was actually easier for my client. Instead of scanning through a loooong dropdown, he just had to copy-paste what he needed. This also eliminated the need to cache the font list.</p>\n" }, { "answer_id": 261075, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>This question is way too broad for a complete answer in a Q&amp;A format, but here is roughly what I would do:</p>\n\n<ol>\n<li>Collect all system fonts in an array <code>$sys_fonts</code></li>\n<li>Collect all Google fonts in an array <code>$ggl_fonts</code></li>\n<li>Collect the <a href=\"https://developers.google.com/fonts/docs/developer_api\" rel=\"nofollow noreferrer\">complete info about Google fonts</a> in a multidimensional array <code>$ggl_fontinfo</code></li>\n<li>Merge <code>$sys_fonts</code> and <code>$ggl_fonts</code> in an array <code>$total_fonts</code></li>\n<li>Use <code>$total_fonts</code> for your dropdown</li>\n<li>Using jquery, detect which item is selected from the dropdown</li>\n<li>If the item is in <code>sys_fonts</code> <a href=\"https://codex.wordpress.org/Theme_Customization_API#Step_2:_Create_a_JavaScript_File\" rel=\"nofollow noreferrer\">use the normal procedure</a> to change the css without reloading the page.</li>\n<li>If the item is in <code>ggl_fonts</code> use it as a key to look up variants (bold, italics, etc) and subsets (languages) in <code>ggl_fontinfo</code>. Then, <a href=\"http://api.jquery.com/append/\" rel=\"nofollow noreferrer\">dynamically add fields</a> to the form. Once all is set, look up which font files you need in <code>ggl_fontinfo</code> and <a href=\"https://stackoverflow.com/questions/16553326/dynamically-load-google-fonts-after-page-has-loaded\">load them dynamically</a> into the page.</li>\n</ol>\n\n<p>Beware that depending on your skills this may take several days to implement (which is why you are unlikely to get a cut-and-paste-ready answer here for free)</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258094", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74107/" ]
I have 10 big dropdown select combo boxes of hundreds of font-faces, including System Fonts and Google Fonts. All combo boxes carry the same values. There are two more combo boxes for each of the boxes above, for loading the language and the font-weight sets. These should only be visible/active if the selected font is a Google font. I'm getting all the font-faces in the select lists through a JSON file via `json_decode`. Before, I was using separate combo boxes for System Fonts and Google Fonts, and the task was little simpler than what I have now. JSON file is like below (just an example): ``` { "fonts":[ "Arial", "Helvetica", "Georgia", "Aclonica", "Acme", "Actor", "Adamina", "Advent Pro", "Aguafina Script" ] } ``` Then I'm using a function (call it JSON\_fonts) to get all these values from the JSON file as an array. ``` $wp_customize->add_control( 'font_1', array( 'label' => esc_html( 'Body Font', 'my_theme' ), 'section' => 'typography', 'type' => 'select', 'choices' => JSON_fonts() ) ); ``` (I think I should use separate JSON files for System fonts and Google Fonts). What I want to do is, to assign keys to the fonts in the select boxes to detect their type (is it a system font or Google). If the selected value is a Google font, then: 1. Collect it in an variable to use it further for en-queuing. 2. Enable the language and font-weight select boxes for the respective font-face. En-queuing is not a problem, but getting the type of the font and the unique values is very problematic to me. * Complexity 1: Getting the font-type * Complexity 2: If the fonts match, merge their respective language and font-weight lists (one-to-one matching will be too much code). * Complexity 3: Asking `wp-ajax` to reload the font without refreshing the customizer. Any help would be greatly appreciated. Also, feel free to share your ideas to bring down the complexity-level.
This question is way too broad for a complete answer in a Q&A format, but here is roughly what I would do: 1. Collect all system fonts in an array `$sys_fonts` 2. Collect all Google fonts in an array `$ggl_fonts` 3. Collect the [complete info about Google fonts](https://developers.google.com/fonts/docs/developer_api) in a multidimensional array `$ggl_fontinfo` 4. Merge `$sys_fonts` and `$ggl_fonts` in an array `$total_fonts` 5. Use `$total_fonts` for your dropdown 6. Using jquery, detect which item is selected from the dropdown 7. If the item is in `sys_fonts` [use the normal procedure](https://codex.wordpress.org/Theme_Customization_API#Step_2:_Create_a_JavaScript_File) to change the css without reloading the page. 8. If the item is in `ggl_fonts` use it as a key to look up variants (bold, italics, etc) and subsets (languages) in `ggl_fontinfo`. Then, [dynamically add fields](http://api.jquery.com/append/) to the form. Once all is set, look up which font files you need in `ggl_fontinfo` and [load them dynamically](https://stackoverflow.com/questions/16553326/dynamically-load-google-fonts-after-page-has-loaded) into the page. Beware that depending on your skills this may take several days to implement (which is why you are unlikely to get a cut-and-paste-ready answer here for free)
258,109
<p>I need the user to be able to sort and filter the posts when viewing a category. The correct way to make a category page would be to use category(-{id}/{slug}).php, but using that automatically creates a loop, so no matter what method I use to sort and filter the posts it will make another loop.</p> <p>In that case should I make a file that's not called category(-{id}/{slug}).php and somehow link it to the categories, or would it be better to simply ignore that two loops are being made no matter what and one of them will not be used?</p> <p>Also in that case is using the Loop again, but with the modified query, more efficient than get_posts()?</p>
[ { "answer_id": 258121, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 2, "selected": false, "text": "<p>First of all: Great you're thinking about a wasted query! :)</p>\n\n<p>Second: WP always runs a main query no matter what you do. But what you can do is alter this query instead of ignoring it and creating a secondary loop. This can be done using the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre get posts</code></a> hook.</p>\n" }, { "answer_id": 258138, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>Yes, the loop and a specific category template should be used even if you want to customize the query. Why?:</p>\n\n<ol>\n<li><p>Even with a custom page, the main query will run. So with a custom page, you are not actually avoiding the main query, you are only replacing it with a different query.</p></li>\n<li><p>The main query itself is customizable.</p></li>\n<li><p>If you deviate from the default WordPress behaviour, it'll be difficult for you to maintain in the future, especially it'll be difficult for other developers in case someone else takes over your work in the future.</p></li>\n</ol>\n\n<h1>How to modify the main query:</h1>\n\n<p>Fortunately, WordPress is extremely customizable, that means the main query (the loop) is also customizable. You may use the <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> action hook or <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\"><code>query_posts()</code></a> function to alter the main query. However, it's recommended to use the <code>pre_get_posts</code> hook.</p>\n\n<p>For example, say you want to change the order of posts in a category based on ascending order of date. For that you may use the following CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse258109_customize_category_query' );\nfunction wpse258109_customize_category_query( $query ) {\n if( ! is_admin() &amp;&amp; $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_category( 'your-category-slug' ) ) {\n // get the orderby value from where ever you want and set in the main query\n $query-&gt;set( 'orderby', array( 'date' =&gt; 'ASC' ) );\n }\n}\n</code></pre>\n\n<p>This CODE will change the default behaviour of the main query and your category posts for <code>your-category-slug</code> archive page will load in ascending order. Of course you can make any change to this main query as you can with any custom query using the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query</a> class. </p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71594/" ]
I need the user to be able to sort and filter the posts when viewing a category. The correct way to make a category page would be to use category(-{id}/{slug}).php, but using that automatically creates a loop, so no matter what method I use to sort and filter the posts it will make another loop. In that case should I make a file that's not called category(-{id}/{slug}).php and somehow link it to the categories, or would it be better to simply ignore that two loops are being made no matter what and one of them will not be used? Also in that case is using the Loop again, but with the modified query, more efficient than get\_posts()?
Yes, the loop and a specific category template should be used even if you want to customize the query. Why?: 1. Even with a custom page, the main query will run. So with a custom page, you are not actually avoiding the main query, you are only replacing it with a different query. 2. The main query itself is customizable. 3. If you deviate from the default WordPress behaviour, it'll be difficult for you to maintain in the future, especially it'll be difficult for other developers in case someone else takes over your work in the future. How to modify the main query: ============================= Fortunately, WordPress is extremely customizable, that means the main query (the loop) is also customizable. You may use the [`pre_get_posts`](https://developer.wordpress.org/reference/hooks/pre_get_posts/) action hook or [`query_posts()`](https://developer.wordpress.org/reference/functions/query_posts/) function to alter the main query. However, it's recommended to use the `pre_get_posts` hook. For example, say you want to change the order of posts in a category based on ascending order of date. For that you may use the following CODE in your theme's `functions.php` file: ``` add_action( 'pre_get_posts', 'wpse258109_customize_category_query' ); function wpse258109_customize_category_query( $query ) { if( ! is_admin() && $query->is_main_query() && $query->is_category( 'your-category-slug' ) ) { // get the orderby value from where ever you want and set in the main query $query->set( 'orderby', array( 'date' => 'ASC' ) ); } } ``` This CODE will change the default behaviour of the main query and your category posts for `your-category-slug` archive page will load in ascending order. Of course you can make any change to this main query as you can with any custom query using the [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/) class.
258,124
<p>I am trying to create a custom WordPress plugin and I created a new folder inside the "plugins" folder. It's called "wp-services-table". Inside this folder I created two files: wp-services-table.php and wp-services-table-shortcode.php</p> <p>For now the wp-services-table-shortcode.php file is blank. I only wrote this in the wp-services-table.php file:</p> <pre><code>&lt;?php /** * Plugin Name: Table and Modal Window for Displaying Services * Description: Displays Services in a table, by Categories and opens a Modal Window when the user clicks for more information. * Version: 0.1.0 * Author: Ami */ //Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } require_once ( plugin_dir_path(__FILE__) . 'wp-services-table-shortcode.php' ); </code></pre> <p>But I get this error: </p> <p>Fatal error: Call to undefined function plugin_dir_path() in /home/mysitedomain/public_html/wpfoldername/contentfolder/plugins/wp-services-table/wp-services-table.php on line 14</p> <p>Could this be because I have a custom name instead of "wp-content"? Or because I installed WordPress in a subfolder ("wpfoldername") and not directly in the "public_html" folder?</p> <p>Because oterwise I think that the what I wrote in the plugin's file is correct for creating a new plugin.</p> <p>I also tried to add this:</p> <pre><code>$dir = plugin_dir_path(__FILE__); var_dump($dir); die(); </code></pre> <p>To see what path it would show for the plugin, but of course I still got the same error regarding the undefined function plugin_dir_path()</p> <p>I hope someone knows why this is happening because I'm very puzzled here. Thank you!</p> <p><strong>I edited the question to add the contents of wp-config:</strong> it might be useful because I have changed the name of the wp-content folder and also WordPress is installed in a subfolder. I think this is the part that is relevant:</p> <pre><code>/* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Renaming the wp-content folder. */ define ('WP_CONTENT_FOLDERNAME', 'contentfolder'); define ('WP_CONTENT_DIR', ABSPATH . WP_CONTENT_FOLDERNAME) ; define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpfoldername/'); define('WP_CONTENT_URL', WP_SITEURL . WP_CONTENT_FOLDERNAME); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); </code></pre> <p>Also the index.php file is in the "wpfoldername" folder and it contains the following code:</p> <pre><code>&lt;?php /** * Front to the WordPress application. This file doesn't do anything, but loads * wp-blog-header.php which does and tells WordPress to load the theme. * * @package WordPress */ /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ define('WP_USE_THEMES', true); /** Loads the WordPress Environment and Template */ require( dirname( __FILE__ ) . '/wp-blog-header.php' ); </code></pre>
[ { "answer_id": 258126, "author": "codiiv", "author_id": 91561, "author_profile": "https://wordpress.stackexchange.com/users/91561", "pm_score": 2, "selected": false, "text": "<p>Could it be that you forgot to comment the <code>Exit if accessed directly</code> part? </p>\n\n<pre><code>//Exit if accessed directly\n\nif ( ! defined( 'ABSPATH' ) ) {\nexit; \n}\n</code></pre>\n" }, { "answer_id": 258250, "author": "Sjoerd van Hout", "author_id": 52181, "author_profile": "https://wordpress.stackexchange.com/users/52181", "pm_score": 2, "selected": false, "text": "<p>How do you access the page? Are you trying to access the pluginfile directly without using the frontend of the site? If that's the case Wordpress probably hasn't been loaded.</p>\n\n<p>What happens if you add the following code at the top of your page?</p>\n\n<pre><code>if ( !defined('ABSPATH') ) {\n //If wordpress isn't loaded load it up.\n $path = $_SERVER['DOCUMENT_ROOT'];\n include_once $path . '/wp-load.php';\n}\n</code></pre>\n\n<p>The code above makes sure Wordpress is loaded before your code runs.</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258124", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113047/" ]
I am trying to create a custom WordPress plugin and I created a new folder inside the "plugins" folder. It's called "wp-services-table". Inside this folder I created two files: wp-services-table.php and wp-services-table-shortcode.php For now the wp-services-table-shortcode.php file is blank. I only wrote this in the wp-services-table.php file: ``` <?php /** * Plugin Name: Table and Modal Window for Displaying Services * Description: Displays Services in a table, by Categories and opens a Modal Window when the user clicks for more information. * Version: 0.1.0 * Author: Ami */ //Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } require_once ( plugin_dir_path(__FILE__) . 'wp-services-table-shortcode.php' ); ``` But I get this error: Fatal error: Call to undefined function plugin\_dir\_path() in /home/mysitedomain/public\_html/wpfoldername/contentfolder/plugins/wp-services-table/wp-services-table.php on line 14 Could this be because I have a custom name instead of "wp-content"? Or because I installed WordPress in a subfolder ("wpfoldername") and not directly in the "public\_html" folder? Because oterwise I think that the what I wrote in the plugin's file is correct for creating a new plugin. I also tried to add this: ``` $dir = plugin_dir_path(__FILE__); var_dump($dir); die(); ``` To see what path it would show for the plugin, but of course I still got the same error regarding the undefined function plugin\_dir\_path() I hope someone knows why this is happening because I'm very puzzled here. Thank you! **I edited the question to add the contents of wp-config:** it might be useful because I have changed the name of the wp-content folder and also WordPress is installed in a subfolder. I think this is the part that is relevant: ``` /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Renaming the wp-content folder. */ define ('WP_CONTENT_FOLDERNAME', 'contentfolder'); define ('WP_CONTENT_DIR', ABSPATH . WP_CONTENT_FOLDERNAME) ; define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpfoldername/'); define('WP_CONTENT_URL', WP_SITEURL . WP_CONTENT_FOLDERNAME); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php'); ``` Also the index.php file is in the "wpfoldername" folder and it contains the following code: ``` <?php /** * Front to the WordPress application. This file doesn't do anything, but loads * wp-blog-header.php which does and tells WordPress to load the theme. * * @package WordPress */ /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ define('WP_USE_THEMES', true); /** Loads the WordPress Environment and Template */ require( dirname( __FILE__ ) . '/wp-blog-header.php' ); ```
Could it be that you forgot to comment the `Exit if accessed directly` part? ``` //Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } ```
258,156
<p>I'd like to show 4 related posts (without a plugin) at the bottom of my blog. However, I want to exclude a certain category. </p> <p>For example, if my blog post is in category <code>2</code> and <code>3</code>, I want to ignore category <code>2</code> and only look for blog posts of category <code>3</code>. Here is the relevant part of <code>single.php</code>:</p> <p><strong><em>Note:</strong> my code below is currently not working.</em></p> <pre><code>$related = get_posts( array( 'category__in' =&gt; wp_get_post_categories( $post-&gt;ID ), 'numberposts' =&gt; 4, 'orderby' =&gt; 'date', 'post__not_in' =&gt; array( $post-&gt;ID ), 'cat' =&gt; '-2' ) ); if( $related ) { foreach( $related as $post ) { setup_postdata($post); /** .. **/ } } </code></pre> <p><strong><em>Update:</em></strong> Category <code>2</code> is so prevalent that I want to ignore it in the search, but not hide those results. </p> <p>For example, this post is in category <code>2</code> and <code>3</code>. I want to find other posts with category <code>3</code>, and maybe they have category <code>2</code>, but I only want to search by category <code>3</code>.</p> <p><strong><em>Update 2:</em></strong> I have this code below and I believe it is now working correctly:</p> <pre><code>$cat_ids = get_the_category(); if( ! empty( $cat_ids ) ) { $post_cat_ids = array(); foreach( $cat_ids as $cat_id ) { if( $cat_id-&gt;cat_ID != 2 ) { $post_cat_ids[] = $cat_id-&gt;cat_ID; } } } $related = get_posts( array( 'category__in' =&gt; wp_get_post_categories( $post-&gt;ID ), 'numberposts' =&gt; 4, 'orderby' =&gt; 'date', 'exclude' =&gt; array( $post-&gt;ID ), 'category' =&gt; $post_cat_ids ) ); </code></pre>
[ { "answer_id": 258159, "author": "Rahul", "author_id": 74107, "author_profile": "https://wordpress.stackexchange.com/users/74107", "pm_score": 1, "selected": false, "text": "<p>Give it a go to <code>category__not_in</code> parameter:</p>\n\n<pre><code>$related = get_posts( array(\n 'numberposts' =&gt; 4,\n 'orderby' =&gt; 'date',\n 'category__in' =&gt; wp_get_post_categories( $post-&gt;ID ),\n 'category__not_in' =&gt; array(2);\n) );\n</code></pre>\n\n<p>It should work.</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters</a></p>\n" }, { "answer_id": 258168, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": true, "text": "<p>What I could gather from your question is:</p>\n\n<ol>\n<li><p>You want to ignore one category (may be more) in the related post query.</p></li>\n<li><p>However, you don't want to actually exclude the posts from that category (in case any post belongs to that category, but also belongs to another category you want to look for).</p></li>\n</ol>\n\n<p>Based on the assumption above, you may use the following CODE (some explanation is given within the CODE in comments):</p>\n\n<pre><code> // set the category ID (or multiple category IDs)\n // you want to ignore in the following array\n $cats_to_ignore = array( 2 );\n $categories = wp_get_post_categories( get_the_ID() );\n $category_in = array_diff( $categories, $cats_to_ignore );\n // ignore only if we have any category left after ignoring\n if( count( $category_in ) == 0 ) {\n $category_in = $categories;\n }\n $cat_args = array(\n 'category__in' =&gt; $category_in,\n 'posts_per_page' =&gt; 4,\n 'orderby' =&gt; 'date',\n 'post__not_in' =&gt; array( get_the_ID() )\n );\n $cat_query = new WP_Query( $cat_args );\n while ( $cat_query-&gt;have_posts() ) : $cat_query-&gt;the_post();\n /* just example markup for related posts */\n echo '&lt;h2&gt;&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . '&lt;/a&gt;&lt;/h2&gt;';\n endwhile;\n // reset $post after custom loop ends (if you need the main loop after this point)\n wp_reset_postdata();\n</code></pre>\n\n<p>You cannot use <code>'cat' =&gt; '-2'</code> or <code>'category__not_in' =&gt; array(2)</code> because that will exclude all posts having category <code>2</code>, even if those posts have other categories as well. So, instead of excluding, I've ignored the category <code>2</code> in the query with this CODE: <code>array_diff( $categories, $cats_to_ignore );</code>.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> I've used <code>WP_Query</code> instead of <code>get_posts()</code> because iteration with <code>WP_Query</code> looks more like the original loop. But of course you can use the <code>get_posts()</code> function as well, as it calls <code>WP_Query</code> internally anyway.</p>\n</blockquote>\n" }, { "answer_id": 258172, "author": "Austin", "author_id": 94192, "author_profile": "https://wordpress.stackexchange.com/users/94192", "pm_score": -1, "selected": false, "text": "<pre><code>$cat_ids = get_the_category();\n\nif( ! empty( $cat_ids ) ) {\n $post_cat_ids = array();\n\n foreach( $cat_ids as $cat_id ) {\n if( 2 != $cat_id-&gt;cat_ID ) {\n $post_cat_ids[] = $cat_id-&gt;cat_ID;\n }\n }\n}\n\n$related = get_posts( array(\n 'category__in' =&gt; wp_get_post_categories( $post-&gt;ID ),\n 'numberposts' =&gt; 4,\n 'orderby' =&gt; 'date',\n 'exclude' =&gt; array( $post-&gt;ID ),\n 'category' =&gt; $post_cat_ids\n) );\n</code></pre>\n" }, { "answer_id": 343047, "author": "Abdus Salam", "author_id": 113729, "author_profile": "https://wordpress.stackexchange.com/users/113729", "pm_score": 0, "selected": false, "text": "<pre><code>function custom_related_post()\n{\n global $post;\n $related = get_posts(array('category__in' =&gt; wp_get_post_categories($post-&gt;ID), 'numberposts' =&gt; 2, 'post__not_in' =&gt; array($post-&gt;ID)));\n ?&gt;\n &lt;div class=\"related-post-content wow fadeInUp\"&gt;\n &lt;h5&gt;&lt;?php esc_html_e('Related Posts', 'text-domain'); ?&gt;&lt;/h5&gt;\n &lt;div class=\"related-post d-flex\"&gt;\n &lt;?php\n if ($related) foreach ($related as $post) {\n setup_postdata($post);\n /* translators: used between list items, there is a space after the comma */\n\n ?&gt;\n &lt;div class=\"single-relatd-post\"&gt;\n &lt;div class=\"img-overflow\"&gt;\n &lt;a href=\"&lt;?php the_title(); ?&gt;\"&gt;&lt;?php the_post_thumbnail(); ?&gt;&lt;/a&gt;\n &lt;/div&gt;\n &lt;h6&gt;&lt;?php the_title(); ?&gt;&lt;/h6&gt;\n &lt;p&gt;&lt;?php the_author(); ?&gt; &lt;span&gt;-&lt;/span&gt; &lt;?php echo get_the_date(); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php wp_reset_postdata();\n }\n ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n&lt;?php }\n</code></pre>\n" }, { "answer_id": 346739, "author": "Shubham Ingale", "author_id": 174711, "author_profile": "https://wordpress.stackexchange.com/users/174711", "pm_score": 0, "selected": false, "text": "<p>Simply use</p>\n\n<p><code>'category__not_in' =&gt; array( category id )</code></p>\n\n<p>to exclude the posts from the specific category.</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258156", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94192/" ]
I'd like to show 4 related posts (without a plugin) at the bottom of my blog. However, I want to exclude a certain category. For example, if my blog post is in category `2` and `3`, I want to ignore category `2` and only look for blog posts of category `3`. Here is the relevant part of `single.php`: ***Note:*** my code below is currently not working. ``` $related = get_posts( array( 'category__in' => wp_get_post_categories( $post->ID ), 'numberposts' => 4, 'orderby' => 'date', 'post__not_in' => array( $post->ID ), 'cat' => '-2' ) ); if( $related ) { foreach( $related as $post ) { setup_postdata($post); /** .. **/ } } ``` ***Update:*** Category `2` is so prevalent that I want to ignore it in the search, but not hide those results. For example, this post is in category `2` and `3`. I want to find other posts with category `3`, and maybe they have category `2`, but I only want to search by category `3`. ***Update 2:*** I have this code below and I believe it is now working correctly: ``` $cat_ids = get_the_category(); if( ! empty( $cat_ids ) ) { $post_cat_ids = array(); foreach( $cat_ids as $cat_id ) { if( $cat_id->cat_ID != 2 ) { $post_cat_ids[] = $cat_id->cat_ID; } } } $related = get_posts( array( 'category__in' => wp_get_post_categories( $post->ID ), 'numberposts' => 4, 'orderby' => 'date', 'exclude' => array( $post->ID ), 'category' => $post_cat_ids ) ); ```
What I could gather from your question is: 1. You want to ignore one category (may be more) in the related post query. 2. However, you don't want to actually exclude the posts from that category (in case any post belongs to that category, but also belongs to another category you want to look for). Based on the assumption above, you may use the following CODE (some explanation is given within the CODE in comments): ``` // set the category ID (or multiple category IDs) // you want to ignore in the following array $cats_to_ignore = array( 2 ); $categories = wp_get_post_categories( get_the_ID() ); $category_in = array_diff( $categories, $cats_to_ignore ); // ignore only if we have any category left after ignoring if( count( $category_in ) == 0 ) { $category_in = $categories; } $cat_args = array( 'category__in' => $category_in, 'posts_per_page' => 4, 'orderby' => 'date', 'post__not_in' => array( get_the_ID() ) ); $cat_query = new WP_Query( $cat_args ); while ( $cat_query->have_posts() ) : $cat_query->the_post(); /* just example markup for related posts */ echo '<h2><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h2>'; endwhile; // reset $post after custom loop ends (if you need the main loop after this point) wp_reset_postdata(); ``` You cannot use `'cat' => '-2'` or `'category__not_in' => array(2)` because that will exclude all posts having category `2`, even if those posts have other categories as well. So, instead of excluding, I've ignored the category `2` in the query with this CODE: `array_diff( $categories, $cats_to_ignore );`. > > ***Note:*** I've used `WP_Query` instead of `get_posts()` because iteration with `WP_Query` looks more like the original loop. But of course you can use the `get_posts()` function as well, as it calls `WP_Query` internally anyway. > > >
258,157
<p>I have a custom search query which I have put in a plugin. The homepage has a custom search form and when the user searches for something, it goes to the search page and displays the result.</p> <p>My issue is that the custom query runs on every page of the website, even in the admin panel. It keeps throwing the error <code>latitude and longitude not defined</code> on every page.</p> <p>I have used <code>is_search()</code> function to make sure the function runs only on search pages but it doesn't work. It still runs the query!</p> <p>This is the code:</p> <pre><code> /** * Custom Search on Homepage * * */ add_filter('posts_fields', 'distance_query'); add_filter('posts_where', 'lat_lng_define'); add_filter('posts_join', 'lat_lng_join'); add_filter('posts_groupby', 'having_distance'); add_filter('posts_orderby', 'sort_distance'); /** * The Fields * * */ function distance_query( $fields ) { global $wpdb; //if(isset($_GET['latitude'] )|| isset($_GET['longitude'] )) { $lat = sanitize_text_field( $_GET['latitude'] ); $lng = sanitize_text_field( $_GET['longitude'] ); //} else { // return; //} if (is_search()) $fields .= ", SOME QUERY" return $fields; } /** * The Join * * */ function lat_lng_join( $join) { global $wpdb; if (is_search()) $join = " QUERY"; return $join; } //Likewise the rest of the query </code></pre> <p>If I isset the $GET values, the homepage shows 404:</p> <pre><code> if(isset($_GET['latitude'] )|| isset($_GET['longitude'] )) { $lat = sanitize_text_field( $_GET['latitude'] ); $lng = sanitize_text_field( $_GET['longitude'] ); } else { return; } </code></pre> <p>The search query running on every page is making my website too slow. Any assistance would be appreciated.</p>
[ { "answer_id": 258161, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 0, "selected": false, "text": "<p>try adding more conditional checks as required.</p>\n\n<pre><code>if ( is_search() &amp;&amp; ! is_admin &amp;&amp; ! is_front_page() &amp;&amp; ! is_page() ) {\n\n $fields .= \"SOME QUERY\";\n\n return $fields;\n}\n</code></pre>\n" }, { "answer_id": 258636, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>You are missing the curly brackets <code>{}</code> around your query statements so the query is modified regardless of the <code>if</code> statement. </p>\n\n<p>So try modifying your code to have something like</p>\n\n<pre><code>if( is_search() ) { \n $fields = '...'; \n return $fields \n} \n</code></pre>\n\n<p>same thing with your <code>$join</code> variable</p>\n\n<p>Remember that while using <code>if</code> without brackets is acceptable for single statements, it is better to always use the curly brackets. Even if it's only to make the code more consistent and easy to read for another coder (or even you in 6 months from now).</p>\n\n<p>You'll save an awful lot of time debugging errors that aren't actually ones. A little bit like you just experienced with your issue here :) </p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258157", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/447/" ]
I have a custom search query which I have put in a plugin. The homepage has a custom search form and when the user searches for something, it goes to the search page and displays the result. My issue is that the custom query runs on every page of the website, even in the admin panel. It keeps throwing the error `latitude and longitude not defined` on every page. I have used `is_search()` function to make sure the function runs only on search pages but it doesn't work. It still runs the query! This is the code: ``` /** * Custom Search on Homepage * * */ add_filter('posts_fields', 'distance_query'); add_filter('posts_where', 'lat_lng_define'); add_filter('posts_join', 'lat_lng_join'); add_filter('posts_groupby', 'having_distance'); add_filter('posts_orderby', 'sort_distance'); /** * The Fields * * */ function distance_query( $fields ) { global $wpdb; //if(isset($_GET['latitude'] )|| isset($_GET['longitude'] )) { $lat = sanitize_text_field( $_GET['latitude'] ); $lng = sanitize_text_field( $_GET['longitude'] ); //} else { // return; //} if (is_search()) $fields .= ", SOME QUERY" return $fields; } /** * The Join * * */ function lat_lng_join( $join) { global $wpdb; if (is_search()) $join = " QUERY"; return $join; } //Likewise the rest of the query ``` If I isset the $GET values, the homepage shows 404: ``` if(isset($_GET['latitude'] )|| isset($_GET['longitude'] )) { $lat = sanitize_text_field( $_GET['latitude'] ); $lng = sanitize_text_field( $_GET['longitude'] ); } else { return; } ``` The search query running on every page is making my website too slow. Any assistance would be appreciated.
You are missing the curly brackets `{}` around your query statements so the query is modified regardless of the `if` statement. So try modifying your code to have something like ``` if( is_search() ) { $fields = '...'; return $fields } ``` same thing with your `$join` variable Remember that while using `if` without brackets is acceptable for single statements, it is better to always use the curly brackets. Even if it's only to make the code more consistent and easy to read for another coder (or even you in 6 months from now). You'll save an awful lot of time debugging errors that aren't actually ones. A little bit like you just experienced with your issue here :)
258,165
<p>In my situation, WordPress was using the wrong url in sortable column headers, filters and pagination in the admin dashboard. The only solution that worked involved modifying core files, specifically lines 767 and 1053, where I had to change</p> <pre><code>$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); </code></pre> <p>to</p> <pre><code>$current_url = set_url_scheme( 'http://www.siteurl.com' . $_SERVER['REQUEST_URI'] ); </code></pre> <p>I've tried inserting</p> <pre><code>if ( ! empty( $_SERVER['HTTP_X_FORWARDED_HOST'] ) ) { $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST']; } </code></pre> <p>into wp-config.php but that didn't work.</p> <p>I was wondering what filters or hooks I could use to change WP's core, or do I have to reconfigure my proxy to set the correct host values before things even get to PHP/WP?</p>
[ { "answer_id": 258161, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 0, "selected": false, "text": "<p>try adding more conditional checks as required.</p>\n\n<pre><code>if ( is_search() &amp;&amp; ! is_admin &amp;&amp; ! is_front_page() &amp;&amp; ! is_page() ) {\n\n $fields .= \"SOME QUERY\";\n\n return $fields;\n}\n</code></pre>\n" }, { "answer_id": 258636, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 3, "selected": true, "text": "<p>You are missing the curly brackets <code>{}</code> around your query statements so the query is modified regardless of the <code>if</code> statement. </p>\n\n<p>So try modifying your code to have something like</p>\n\n<pre><code>if( is_search() ) { \n $fields = '...'; \n return $fields \n} \n</code></pre>\n\n<p>same thing with your <code>$join</code> variable</p>\n\n<p>Remember that while using <code>if</code> without brackets is acceptable for single statements, it is better to always use the curly brackets. Even if it's only to make the code more consistent and easy to read for another coder (or even you in 6 months from now).</p>\n\n<p>You'll save an awful lot of time debugging errors that aren't actually ones. A little bit like you just experienced with your issue here :) </p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258165", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108817/" ]
In my situation, WordPress was using the wrong url in sortable column headers, filters and pagination in the admin dashboard. The only solution that worked involved modifying core files, specifically lines 767 and 1053, where I had to change ``` $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ``` to ``` $current_url = set_url_scheme( 'http://www.siteurl.com' . $_SERVER['REQUEST_URI'] ); ``` I've tried inserting ``` if ( ! empty( $_SERVER['HTTP_X_FORWARDED_HOST'] ) ) { $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST']; } ``` into wp-config.php but that didn't work. I was wondering what filters or hooks I could use to change WP's core, or do I have to reconfigure my proxy to set the correct host values before things even get to PHP/WP?
You are missing the curly brackets `{}` around your query statements so the query is modified regardless of the `if` statement. So try modifying your code to have something like ``` if( is_search() ) { $fields = '...'; return $fields } ``` same thing with your `$join` variable Remember that while using `if` without brackets is acceptable for single statements, it is better to always use the curly brackets. Even if it's only to make the code more consistent and easy to read for another coder (or even you in 6 months from now). You'll save an awful lot of time debugging errors that aren't actually ones. A little bit like you just experienced with your issue here :)
258,183
<p>I am using Twitter Intents as part of my theme and I can successfully share posts’ URLs on Twitter. However, I would like to be able to show the images of the shared posts. Is that even possible? I was thinking to make use of Twitter cards: <a href="https://dev.twitter.com/cards/overview" rel="nofollow noreferrer">https://dev.twitter.com/cards/overview</a> Is that a viable solution? I guess I am trying to understand if what I am trying to do is even possible. </p> <p>This is an excerpt from the code:</p> <pre><code>&lt;div class="myclass&gt; &lt;a href="https://twitter.com/intent/tweet?text=&lt;?php echo urlencode( the_permalink() ) ?&gt;" target="_blank"&gt;&lt;i class="icon-twitter"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Thanks for your help. </p>
[ { "answer_id": 258344, "author": "brianjohnhanna", "author_id": 65403, "author_profile": "https://wordpress.stackexchange.com/users/65403", "pm_score": 1, "selected": false, "text": "<p>Yes, what you want to implement is cards. This is basically the concept of injecting metadata into your site that tells Twitter how you want it to be presented. If you wanted to do it using code, you could implement it doing something like this (barebones version):</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_add_twitter_metadata' );\nfunction wpse_add_twitter_metadata() {\n global $post;\n printf(\n '&lt;meta name=\"twitter:card\" content=\"summary\" /&gt;\n &lt;meta name=\"twitter:title\" content=\"%s\" /&gt;\n &lt;meta name=\"twitter:description\" content=\"%s\" /&gt;\n &lt;meta name=\"twitter:image\" content=\"%s\" /&gt;',\n get_the_title( $post ),\n get_the_excerpt( $post ),\n get_the_post_thumbnail_url($post)\n );\n}\n</code></pre>\n\n<p>With that configured, when someone goes to share your page with web intent or by copying and pasting the URL, Twitter should have the information it needs to generate the proper preview. With that said, I'd rely on a plugin to do something like this, personally. Social media API's and integrations like this are always changing and a free plugin like <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">Yoast SEO</a> will handle this for multiple social networks without having to implement it yourself.</p>\n" }, { "answer_id": 258609, "author": "panza", "author_id": 29402, "author_profile": "https://wordpress.stackexchange.com/users/29402", "pm_score": 1, "selected": true, "text": "<p>I have ended up with the following:</p>\n\n<pre><code>function my_twitter_cards() {\n if (is_singular()) {\n global $post;\n $twitter_user = str_replace('@', '', get_the_author_meta('twitter'));\n $twitter_url = get_permalink();\n $twitter_title = get_the_title();\n $twitter_excerpt = get_the_excerpt();\n $twittercard_image = wp_get_attachment_image_src(get_post_thumbnail_id($post-&gt;ID), 'full');\n $twittercard_thumb = $twittercard_image[0];\n if ($twitter_user) {\n echo '&lt;meta name=\"twitter:creator\" content=\"@' . esc_attr($twitter_user) . '\" /&gt;' . \"\\n\";\n }\n echo '&lt;meta name=\"twitter:card\" content=\"summary\" /&gt;' . \"\\n\";\n echo '&lt;meta name=\"twitter:url\" content=\"' . esc_url($twitter_url) . '\" /&gt;' . \"\\n\";\n echo '&lt;meta name=\"twitter:title\" content=\"' . esc_attr($twitter_title) . '\" /&gt;' . \"\\n\";\n echo '&lt;meta name=\"twitter:description\" content=\"' . esc_attr($twitter_excerpt) . '\" /&gt;' . \"\\n\";\n echo '&lt;meta name=\"twitter:image\" content=\"' . esc_url($twittercard_thumb) . '\" /&gt;' . \"\\n\";\n }\n}\nadd_action('wp_head', 'my_twitter_cards');\n</code></pre>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258183", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29402/" ]
I am using Twitter Intents as part of my theme and I can successfully share posts’ URLs on Twitter. However, I would like to be able to show the images of the shared posts. Is that even possible? I was thinking to make use of Twitter cards: <https://dev.twitter.com/cards/overview> Is that a viable solution? I guess I am trying to understand if what I am trying to do is even possible. This is an excerpt from the code: ``` <div class="myclass> <a href="https://twitter.com/intent/tweet?text=<?php echo urlencode( the_permalink() ) ?>" target="_blank"><i class="icon-twitter"></i></a> </div> ``` Thanks for your help.
I have ended up with the following: ``` function my_twitter_cards() { if (is_singular()) { global $post; $twitter_user = str_replace('@', '', get_the_author_meta('twitter')); $twitter_url = get_permalink(); $twitter_title = get_the_title(); $twitter_excerpt = get_the_excerpt(); $twittercard_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full'); $twittercard_thumb = $twittercard_image[0]; if ($twitter_user) { echo '<meta name="twitter:creator" content="@' . esc_attr($twitter_user) . '" />' . "\n"; } echo '<meta name="twitter:card" content="summary" />' . "\n"; echo '<meta name="twitter:url" content="' . esc_url($twitter_url) . '" />' . "\n"; echo '<meta name="twitter:title" content="' . esc_attr($twitter_title) . '" />' . "\n"; echo '<meta name="twitter:description" content="' . esc_attr($twitter_excerpt) . '" />' . "\n"; echo '<meta name="twitter:image" content="' . esc_url($twittercard_thumb) . '" />' . "\n"; } } add_action('wp_head', 'my_twitter_cards'); ```
258,188
<p>I'm using the code below to upload a post thumbnail image through the front end. However, it only seems to upload the original size and not all the various thumbnail sizes e.g. 'medium', 'large' etc. I am getting <code>_wp_attached_file</code> and <code>_thumbnail_id</code> entered into the db no problem, but no other size meta data. The image is added to the correct uploads folder, but only the original size not the additional standard sizes. </p> <p>Thanks in advance.</p> <pre><code>$uploaddir = wp_upload_dir(); $file = $_FILES['featured' ]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' =&gt; $wp_filetype['type'], 'post_title' =&gt; preg_replace('/\.[^.]+$/', '', $filename), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit', 'menu_order' =&gt; $_i + 1000 ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); wp_update_attachment_metadata( $attach_id, $attach_data ); $post = array( 'ID' =&gt; esc_sql($current_post) ); wp_update_post($post); update_post_meta($current_post,'_thumbnail_id',$attach_id); set_post_thumbnail( $current_post, $attach_id ); </code></pre>
[ { "answer_id": 258197, "author": "The Sumo", "author_id": 76021, "author_profile": "https://wordpress.stackexchange.com/users/76021", "pm_score": 0, "selected": false, "text": "<p>It seems that the only way to do this is to use <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">media_handle_upload</a> </p>\n" }, { "answer_id": 258227, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 1, "selected": false, "text": "<p>wp_generate_attachment_metadata generates metadata for an image attachment. It also creates a thumbnail and other intermediate sizes of the image attachment based on the sizes defined on the Settings_Media_Screen.</p>\n\n<p>wp_generate_attachment_metadata() is located in wp-admin/includes/image.php.</p>\n\n<p>/* just require image.php before wp_generate_attachment_metadata */</p>\n\n<p>require_once(ABSPATH . 'wp-admin/includes/image.php');</p>\n\n<p>$attach_data = wp_generate_attachment_metadata( $attach_id, $file );</p>\n\n<p>hope that helps!</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258188", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76021/" ]
I'm using the code below to upload a post thumbnail image through the front end. However, it only seems to upload the original size and not all the various thumbnail sizes e.g. 'medium', 'large' etc. I am getting `_wp_attached_file` and `_thumbnail_id` entered into the db no problem, but no other size meta data. The image is added to the correct uploads folder, but only the original size not the additional standard sizes. Thanks in advance. ``` $uploaddir = wp_upload_dir(); $file = $_FILES['featured' ]; $uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] ); move_uploaded_file( $file['tmp_name'] , $uploadfile ); $filename = basename( $uploadfile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), 'post_content' => '', 'post_status' => 'inherit', 'menu_order' => $_i + 1000 ); $attach_id = wp_insert_attachment( $attachment, $uploadfile ); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); wp_update_attachment_metadata( $attach_id, $attach_data ); $post = array( 'ID' => esc_sql($current_post) ); wp_update_post($post); update_post_meta($current_post,'_thumbnail_id',$attach_id); set_post_thumbnail( $current_post, $attach_id ); ```
wp\_generate\_attachment\_metadata generates metadata for an image attachment. It also creates a thumbnail and other intermediate sizes of the image attachment based on the sizes defined on the Settings\_Media\_Screen. wp\_generate\_attachment\_metadata() is located in wp-admin/includes/image.php. /\* just require image.php before wp\_generate\_attachment\_metadata \*/ require\_once(ABSPATH . 'wp-admin/includes/image.php'); $attach\_data = wp\_generate\_attachment\_metadata( $attach\_id, $file ); hope that helps!
258,190
<p>I have the following function written, the issue is when I set the category in my shortcode it ignores it and shows all posts from the custom post type. So it only sort of works.</p> <pre><code>/*-------------------------------------------------------------- ## Resources Shortcode --------------------------------------------------------------*/ function resources_query( $atts ) { extract(shortcode_atts(array( 'category' =&gt; '', 'per_page' =&gt; -1, 'orderby' =&gt; 'date', 'order' =&gt; 'ASC' ), $atts)); $tax_query = array( 'taxonomy' =&gt; 'resources_categories', 'field' =&gt; 'slug', 'terms' =&gt; array( esc_attr($category) ), 'operator' =&gt; 'IN', ); $args = array( 'post_type' =&gt; 'resources', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; $per_page, 'orderby' =&gt; $orderby, 'order' =&gt; $order, 'tax_query' =&gt; $tax_query ); $resources_query = new WP_Query( $args ); if ( $resources_query-&gt;have_posts() ) : $html_out = '&lt;div class="fg-row row flex-row"&gt;'; while ( $resources_query-&gt;have_posts() ) : $resources_query-&gt;the_post(); $title = get_the_title(); $content = get_the_excerpt(); $pdf = get_field( "download_pdf" ); // Do stuff with each post here $html_out .= '&lt;div class="fg-col col-xs-12 col-md-4 fg-text-dark"&gt;&lt;section class="icon-box-v3 light-box text-left fg-text-dark"&gt;&lt;i class="icon-box-v3-icons ff-font-et-line icon-document fg-text-dark ffb-icon-1"&gt;&lt;/i&gt;'; $html_out .= '&lt;h3 class="icon-box-v3-title fg-text-dark ffb-title-2"&gt;' . $title . '&lt;/h3&gt;&lt;p class="icon-box-v3-title-paragraph fg-text-dark ffb-description-3"&gt;' . $content . '&lt;/p&gt;'; if( $pdf ): $html_out .= '&lt;a href="' . $pdf . '" class="ffb-block-button-1-0 ffb-btn ffb-btn-v1 ffb-btn-link btn-base-brd-slide btn-slide btn-base-md btn-w-auto fg-text-dark ffb-button1-1 btn-light-box" target="_blank"&gt;&lt;span class="btn-text"&gt;Download PDF&lt;/span&gt;&lt;/a&gt;'; endif; $html_out .= '&lt;/section&gt;&lt;/div&gt;'; endwhile; $html_out .= '&lt;/div&gt;'; else : // No results $html_out = "No Resources Found."; endif; wp_reset_query(); return $html_out; } add_shortcode( 'show_resources', 'resources_query' ); </code></pre> <p>Here's what my shortcode actually looks like <code>[show_resources category="post-surgery-information" per_page="-1"]</code>. I am not sure why it would ignore it and show all posts. I looked at other Stack articles to help me with setting this up.</p>
[ { "answer_id": 258197, "author": "The Sumo", "author_id": 76021, "author_profile": "https://wordpress.stackexchange.com/users/76021", "pm_score": 0, "selected": false, "text": "<p>It seems that the only way to do this is to use <a href=\"https://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow noreferrer\">media_handle_upload</a> </p>\n" }, { "answer_id": 258227, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 1, "selected": false, "text": "<p>wp_generate_attachment_metadata generates metadata for an image attachment. It also creates a thumbnail and other intermediate sizes of the image attachment based on the sizes defined on the Settings_Media_Screen.</p>\n\n<p>wp_generate_attachment_metadata() is located in wp-admin/includes/image.php.</p>\n\n<p>/* just require image.php before wp_generate_attachment_metadata */</p>\n\n<p>require_once(ABSPATH . 'wp-admin/includes/image.php');</p>\n\n<p>$attach_data = wp_generate_attachment_metadata( $attach_id, $file );</p>\n\n<p>hope that helps!</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258190", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96257/" ]
I have the following function written, the issue is when I set the category in my shortcode it ignores it and shows all posts from the custom post type. So it only sort of works. ``` /*-------------------------------------------------------------- ## Resources Shortcode --------------------------------------------------------------*/ function resources_query( $atts ) { extract(shortcode_atts(array( 'category' => '', 'per_page' => -1, 'orderby' => 'date', 'order' => 'ASC' ), $atts)); $tax_query = array( 'taxonomy' => 'resources_categories', 'field' => 'slug', 'terms' => array( esc_attr($category) ), 'operator' => 'IN', ); $args = array( 'post_type' => 'resources', 'post_status' => 'publish', 'posts_per_page' => $per_page, 'orderby' => $orderby, 'order' => $order, 'tax_query' => $tax_query ); $resources_query = new WP_Query( $args ); if ( $resources_query->have_posts() ) : $html_out = '<div class="fg-row row flex-row">'; while ( $resources_query->have_posts() ) : $resources_query->the_post(); $title = get_the_title(); $content = get_the_excerpt(); $pdf = get_field( "download_pdf" ); // Do stuff with each post here $html_out .= '<div class="fg-col col-xs-12 col-md-4 fg-text-dark"><section class="icon-box-v3 light-box text-left fg-text-dark"><i class="icon-box-v3-icons ff-font-et-line icon-document fg-text-dark ffb-icon-1"></i>'; $html_out .= '<h3 class="icon-box-v3-title fg-text-dark ffb-title-2">' . $title . '</h3><p class="icon-box-v3-title-paragraph fg-text-dark ffb-description-3">' . $content . '</p>'; if( $pdf ): $html_out .= '<a href="' . $pdf . '" class="ffb-block-button-1-0 ffb-btn ffb-btn-v1 ffb-btn-link btn-base-brd-slide btn-slide btn-base-md btn-w-auto fg-text-dark ffb-button1-1 btn-light-box" target="_blank"><span class="btn-text">Download PDF</span></a>'; endif; $html_out .= '</section></div>'; endwhile; $html_out .= '</div>'; else : // No results $html_out = "No Resources Found."; endif; wp_reset_query(); return $html_out; } add_shortcode( 'show_resources', 'resources_query' ); ``` Here's what my shortcode actually looks like `[show_resources category="post-surgery-information" per_page="-1"]`. I am not sure why it would ignore it and show all posts. I looked at other Stack articles to help me with setting this up.
wp\_generate\_attachment\_metadata generates metadata for an image attachment. It also creates a thumbnail and other intermediate sizes of the image attachment based on the sizes defined on the Settings\_Media\_Screen. wp\_generate\_attachment\_metadata() is located in wp-admin/includes/image.php. /\* just require image.php before wp\_generate\_attachment\_metadata \*/ require\_once(ABSPATH . 'wp-admin/includes/image.php'); $attach\_data = wp\_generate\_attachment\_metadata( $attach\_id, $file ); hope that helps!
258,192
<p>I am trying to allow CSV files in a dashboard menu page like this..</p> <pre><code>&lt;form method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="csv_file" id="csv_file" multiple="false" accept=".csv" /&gt; &lt;input type="submit" value="Upload" /&gt; &lt;/form&gt; require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attachment_id = media_handle_upload ( 'csv_file', 0, array(), array( 'test_form' =&gt; false, 'mimes' =&gt; array( 'csv' =&gt; 'text/csv', ), ) ); </code></pre> <p>When I upload a CSV file to the form I get the following error message...</p> <pre><code>Sorry, this file type is not permitted for security reasons. </code></pre> <p>Can anyone spot what I am doing wrong? I had assumed I had allowed the CSV mime type in the above code.</p>
[ { "answer_id": 258198, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>By default, WordPress blocks <code>.csv</code> file uploads. The <code>mime_types</code> filter will allow you to add <code>.csv</code> files or any other file to be uploaded:</p>\n\n<pre><code>add_filter( 'mime_types', 'wpse_mime_types' );\nfunction wpse_mime_types( $existing_mimes ) {\n // Add csv to the list of allowed mime types\n $existing_mimes['csv'] = 'text/csv';\n\n return $existing_mimes;\n}\n</code></pre>\n" }, { "answer_id": 258208, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 4, "selected": true, "text": "<p>There's a <a href=\"https://wordpress.org/support/topic/read-this-first-wordpress-4-7-master-list/?view=all#post-8521428\" rel=\"nofollow noreferrer\">bug</a> in WordPress 4.7-4.7.3 related to validating MIME types, so the code provided by Dave Romsey won't work.</p>\n\n<p>There's a <a href=\"https://wordpress.org/plugins/disable-real-mime-check/\" rel=\"nofollow noreferrer\">plugin in the repo</a> that will bypass MIME checks, but it disables the checks for all users and all extensions. I think a better way would be to add a new capability for administrators that will allow them to upload .csv extensions.</p>\n\n<pre><code>//* Register activation and deactivation hooks\nregister_activation_hook( __FILE__ , 'wpse_258192_activation' );\nregister_deactivation_hook( __FILE__ , 'wpse_258192_deactivation' );\n\n//* Add upload_csv capability to administrator role\nfunction wpse_258192_activation() {\n $admin = get_role( 'administrator' );\n $admin-&gt;add_cap( 'upload_csv' );\n}\n\n//* Remove upload_csv capability from administrator role\nfunction wpse_258192_deactivation() {\n $admin = get_role( 'administrator' );\n $admin-&gt;remove_cap( 'upload_csv' );\n}\n\n//* Add filter to check filetype and extension\nadd_filter( 'wp_check_filetype_and_ext', 'wpse_258192_check_filetype_and_ext', 10, 4 );\n\n//* If the current user can upload_csv and the file extension is csv, override arguments - edit - \"$pathinfo\" changed to \"pathinfo\"\nfunction wpse_258192_check_filetype_and_ext( $args, $file, $filename, $mimes ) {\n if( current_user_can( 'upload_csv' ) &amp;&amp; 'csv' === pathinfo( $filename )[ 'extension' ] ){\n $args = array(\n 'ext' =&gt; 'csv',\n 'type' =&gt; 'text/csv',\n 'proper_filename' =&gt; $filename,\n );\n }\n return $args;\n}\n</code></pre>\n" }, { "answer_id": 359447, "author": "dee_ell", "author_id": 182168, "author_profile": "https://wordpress.stackexchange.com/users/182168", "pm_score": 3, "selected": false, "text": "<p>If you want a temporary quick and easy solution you can allow unfiltered uploads in your wp-config.php .</p>\n\n<pre><code>define('ALLOW_UNFILTERED_UPLOADS', true);\n</code></pre>\n\n<p>This line should probably not stay in your config.php, but if you want to do something like a woocommerce products import via CSV only once, it can be an easy fix.</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258192", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10247/" ]
I am trying to allow CSV files in a dashboard menu page like this.. ``` <form method="post" enctype="multipart/form-data"> <input type="file" name="csv_file" id="csv_file" multiple="false" accept=".csv" /> <input type="submit" value="Upload" /> </form> require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $attachment_id = media_handle_upload ( 'csv_file', 0, array(), array( 'test_form' => false, 'mimes' => array( 'csv' => 'text/csv', ), ) ); ``` When I upload a CSV file to the form I get the following error message... ``` Sorry, this file type is not permitted for security reasons. ``` Can anyone spot what I am doing wrong? I had assumed I had allowed the CSV mime type in the above code.
There's a [bug](https://wordpress.org/support/topic/read-this-first-wordpress-4-7-master-list/?view=all#post-8521428) in WordPress 4.7-4.7.3 related to validating MIME types, so the code provided by Dave Romsey won't work. There's a [plugin in the repo](https://wordpress.org/plugins/disable-real-mime-check/) that will bypass MIME checks, but it disables the checks for all users and all extensions. I think a better way would be to add a new capability for administrators that will allow them to upload .csv extensions. ``` //* Register activation and deactivation hooks register_activation_hook( __FILE__ , 'wpse_258192_activation' ); register_deactivation_hook( __FILE__ , 'wpse_258192_deactivation' ); //* Add upload_csv capability to administrator role function wpse_258192_activation() { $admin = get_role( 'administrator' ); $admin->add_cap( 'upload_csv' ); } //* Remove upload_csv capability from administrator role function wpse_258192_deactivation() { $admin = get_role( 'administrator' ); $admin->remove_cap( 'upload_csv' ); } //* Add filter to check filetype and extension add_filter( 'wp_check_filetype_and_ext', 'wpse_258192_check_filetype_and_ext', 10, 4 ); //* If the current user can upload_csv and the file extension is csv, override arguments - edit - "$pathinfo" changed to "pathinfo" function wpse_258192_check_filetype_and_ext( $args, $file, $filename, $mimes ) { if( current_user_can( 'upload_csv' ) && 'csv' === pathinfo( $filename )[ 'extension' ] ){ $args = array( 'ext' => 'csv', 'type' => 'text/csv', 'proper_filename' => $filename, ); } return $args; } ```
258,199
<p>I added HTML banners to the top of certain pages on a client's site. He wants to make edits to the text phrases on these banners without having to edit any HTML. How do I open this up for him? <hr> In the past, I have simply made a collection of pages that I insert into my HTML banners using the following code:</p> <pre><code>&lt;div class="banner-top"&gt; &lt;h1&gt;&lt;?php echo $about_us_phrase-&gt;post_title; ?&gt;&lt;/h1&gt; &lt;p&gt;&lt;?php echo apply_filters( 'the_content', $about_us_phrase-&gt;post_content ); ?&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>But this feels hackish, especially because it forces the client to swim through a potentially large number of pages to find the one that corresponds to the text they'd like to edit.</p> <p>What is the most Wordpress-y way to do this?</p>
[ { "answer_id": 258204, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 3, "selected": true, "text": "<p>Are the banners related to each page? If so, I would use a custom field or just a metabox that the user could edit or enter information into on the page that you want the banner to show up. The field would show up below the content in the page editor. You would then in your single.php add the code you noted above to encase whatever is typed in the custom field. </p>\n\n<p>If the banners are NOT related to individual pages. I would make a custom post type \"banners\" and then have them randomly show up on pages by inserting a call for the CPT within the single.php.</p>\n\n<p>You can either use a plugin to create the fields or these reference links will help you get started on creating your own:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes</a>\n(explanation etc)</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_meta_box/</a> (code examples and usage)</p>\n" }, { "answer_id": 258221, "author": "The J", "author_id": 98010, "author_profile": "https://wordpress.stackexchange.com/users/98010", "pm_score": 0, "selected": false, "text": "<p>Make a custom sidebar for the banner, then add from the theme any code you don't want them to edit or touch, finally have them use a simple Text Widget to add/change/remove text.</p>\n\n<p>That way, if there is no text widget (eg banner not in use), the banner won't display at all.</p>\n\n<p>For more complex content, I'd also say use a custom post type and custom fields.</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258199", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27503/" ]
I added HTML banners to the top of certain pages on a client's site. He wants to make edits to the text phrases on these banners without having to edit any HTML. How do I open this up for him? --- In the past, I have simply made a collection of pages that I insert into my HTML banners using the following code: ``` <div class="banner-top"> <h1><?php echo $about_us_phrase->post_title; ?></h1> <p><?php echo apply_filters( 'the_content', $about_us_phrase->post_content ); ?></p> </div> ``` But this feels hackish, especially because it forces the client to swim through a potentially large number of pages to find the one that corresponds to the text they'd like to edit. What is the most Wordpress-y way to do this?
Are the banners related to each page? If so, I would use a custom field or just a metabox that the user could edit or enter information into on the page that you want the banner to show up. The field would show up below the content in the page editor. You would then in your single.php add the code you noted above to encase whatever is typed in the custom field. If the banners are NOT related to individual pages. I would make a custom post type "banners" and then have them randomly show up on pages by inserting a call for the CPT within the single.php. You can either use a plugin to create the fields or these reference links will help you get started on creating your own: <https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes> (explanation etc) <https://developer.wordpress.org/reference/functions/add_meta_box/> (code examples and usage)
258,207
<p>I want to hide a widget completely when a visitor is using an ipad on <code>portrait orientation</code> (768x1024).</p> <p>I know that the media query will be this:</p> <pre><code>@media (width: 768px) and (height: 1024px) { .nameofthewidgetclass { display: none; } } </code></pre> <p>But I have two issues.</p> <p>1) I am not 100% sure how to target the specific widget. Obviously I cannot hide <code>footer-widget</code>, as that removes all of them. I know I could install a plugin that lets me have custom CSS per widget, but I try keep plugins to a minimum so if someone could assist, I would appreciate it.</p> <p>2) When I just used chrome to inspect the widget, then assigned the <code>"display: none;"</code> to it, it did hide it but the white space was not reclaimed. The solution must be able to hide this white space.</p> <p>Thanks in advance!</p>
[ { "answer_id": 258204, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 3, "selected": true, "text": "<p>Are the banners related to each page? If so, I would use a custom field or just a metabox that the user could edit or enter information into on the page that you want the banner to show up. The field would show up below the content in the page editor. You would then in your single.php add the code you noted above to encase whatever is typed in the custom field. </p>\n\n<p>If the banners are NOT related to individual pages. I would make a custom post type \"banners\" and then have them randomly show up on pages by inserting a call for the CPT within the single.php.</p>\n\n<p>You can either use a plugin to create the fields or these reference links will help you get started on creating your own:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes</a>\n(explanation etc)</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_meta_box/</a> (code examples and usage)</p>\n" }, { "answer_id": 258221, "author": "The J", "author_id": 98010, "author_profile": "https://wordpress.stackexchange.com/users/98010", "pm_score": 0, "selected": false, "text": "<p>Make a custom sidebar for the banner, then add from the theme any code you don't want them to edit or touch, finally have them use a simple Text Widget to add/change/remove text.</p>\n\n<p>That way, if there is no text widget (eg banner not in use), the banner won't display at all.</p>\n\n<p>For more complex content, I'd also say use a custom post type and custom fields.</p>\n" } ]
2017/02/27
[ "https://wordpress.stackexchange.com/questions/258207", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114346/" ]
I want to hide a widget completely when a visitor is using an ipad on `portrait orientation` (768x1024). I know that the media query will be this: ``` @media (width: 768px) and (height: 1024px) { .nameofthewidgetclass { display: none; } } ``` But I have two issues. 1) I am not 100% sure how to target the specific widget. Obviously I cannot hide `footer-widget`, as that removes all of them. I know I could install a plugin that lets me have custom CSS per widget, but I try keep plugins to a minimum so if someone could assist, I would appreciate it. 2) When I just used chrome to inspect the widget, then assigned the `"display: none;"` to it, it did hide it but the white space was not reclaimed. The solution must be able to hide this white space. Thanks in advance!
Are the banners related to each page? If so, I would use a custom field or just a metabox that the user could edit or enter information into on the page that you want the banner to show up. The field would show up below the content in the page editor. You would then in your single.php add the code you noted above to encase whatever is typed in the custom field. If the banners are NOT related to individual pages. I would make a custom post type "banners" and then have them randomly show up on pages by inserting a call for the CPT within the single.php. You can either use a plugin to create the fields or these reference links will help you get started on creating your own: <https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes> (explanation etc) <https://developer.wordpress.org/reference/functions/add_meta_box/> (code examples and usage)
258,210
<p>I create shortcode like this</p> <pre><code>function test_func( $atts ) { return $_GET['myvar']; } add_shortcode( 'test', 'test_func' ); </code></pre> <p>and one page with this name myparameters</p> <p>so this is the final url </p> <pre><code>http://website.com/myparameters </code></pre> <p>if I try this works perfect </p> <pre><code>http://website.com/myparameters/?myvar=theparameter </code></pre> <p>But i like have pretty url or friendly url like this</p> <pre><code>http://website.com/myparameters/theparameter/ </code></pre> <p>But show page not found.</p> <p>I try some tutorial like this <a href="https://wordpress.stackexchange.com/questions/89164/passing-parameters-to-a-custom-page-template-using-clean-urls">LINK</a> but nothing happen</p>
[ { "answer_id": 258204, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 3, "selected": true, "text": "<p>Are the banners related to each page? If so, I would use a custom field or just a metabox that the user could edit or enter information into on the page that you want the banner to show up. The field would show up below the content in the page editor. You would then in your single.php add the code you noted above to encase whatever is typed in the custom field. </p>\n\n<p>If the banners are NOT related to individual pages. I would make a custom post type \"banners\" and then have them randomly show up on pages by inserting a call for the CPT within the single.php.</p>\n\n<p>You can either use a plugin to create the fields or these reference links will help you get started on creating your own:</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes</a>\n(explanation etc)</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_meta_box/</a> (code examples and usage)</p>\n" }, { "answer_id": 258221, "author": "The J", "author_id": 98010, "author_profile": "https://wordpress.stackexchange.com/users/98010", "pm_score": 0, "selected": false, "text": "<p>Make a custom sidebar for the banner, then add from the theme any code you don't want them to edit or touch, finally have them use a simple Text Widget to add/change/remove text.</p>\n\n<p>That way, if there is no text widget (eg banner not in use), the banner won't display at all.</p>\n\n<p>For more complex content, I'd also say use a custom post type and custom fields.</p>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258210", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68371/" ]
I create shortcode like this ``` function test_func( $atts ) { return $_GET['myvar']; } add_shortcode( 'test', 'test_func' ); ``` and one page with this name myparameters so this is the final url ``` http://website.com/myparameters ``` if I try this works perfect ``` http://website.com/myparameters/?myvar=theparameter ``` But i like have pretty url or friendly url like this ``` http://website.com/myparameters/theparameter/ ``` But show page not found. I try some tutorial like this [LINK](https://wordpress.stackexchange.com/questions/89164/passing-parameters-to-a-custom-page-template-using-clean-urls) but nothing happen
Are the banners related to each page? If so, I would use a custom field or just a metabox that the user could edit or enter information into on the page that you want the banner to show up. The field would show up below the content in the page editor. You would then in your single.php add the code you noted above to encase whatever is typed in the custom field. If the banners are NOT related to individual pages. I would make a custom post type "banners" and then have them randomly show up on pages by inserting a call for the CPT within the single.php. You can either use a plugin to create the fields or these reference links will help you get started on creating your own: <https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes> (explanation etc) <https://developer.wordpress.org/reference/functions/add_meta_box/> (code examples and usage)
258,223
<p>I wrote a repeater script that clones the last field group before it. My issue is that cloned WP Color Picker fields don't open the new color spectrum when clicked on but instead opens the color picker in the group it was cloned from.</p> <p>Of course, it works fine once you save the field and reload the page, but not on the fly as you clone the prior group.</p> <p>Here's the field HTML:</p> <pre><code>&lt;div class="md-repeat"&gt; &lt;a href="#" class="md-repeat-add"&gt;Add Another Color Picker&lt;/a&gt; &lt;div class="md-repeat-field"&gt; &lt;label for="my_field"&gt;My Color Picker Field&lt;/label&gt; &lt;input name="my_field" id="my_field" type="text" class="my-colorpicker" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and the repeater scripts:</p> <pre><code>... add: function() { $( ".md-repeat-add" ).click( function( e ) { e.preventDefault(); var lastRepeatingGroup = $( this ).closest( '.md-repeat' ).find( '.md-repeat-field' ).last(), clone = lastRepeatingGroup.clone( true ); clone.find( 'input.regular-text, textarea, select' ).val( '' ); clone.find( 'input.regular-text' ).prop( 'readonly', false ); clone.find( 'input[type=checkbox]' ).attr( 'checked', false ); clone.insertAfter( lastRepeatingGroup ); MD_Repeatable_Fields.resetAtts( clone ); }); }, resetAtts: function( section ) { var attrs = [ 'for', 'id', 'name' ], tags = section.find( 'input, label, textarea, select' ), count = section.index(); tags.each( function() { var $this = $( this ); $.each( attrs, function( i, attr ) { var attr_val = $this.attr( attr ); if ( attr_val ) $this.attr( attr, attr_val.replace( /(\d+)(?=\D+$)/, count ) ); }); }); }, ... </code></pre> <p>How can I "reset" the color picker script to detect when new color pickers are made on the fly and execute the proper JS to open the new color picker when clicked?</p>
[ { "answer_id": 258274, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 1, "selected": false, "text": "<p>It's hard to know for sure, since you don't include the markup you're output for the metabox nor the JS you're using to clone. But, the following simplified setup seems to work for me:</p>\n\n<p><strong>metabox markup</strong></p>\n\n<pre><code>&lt;label for='my_field'&gt;\n My Color Picker Field\n&lt;/label&gt;\n&lt;input name='my_field' id='my_field' type='text' class='my-colorpicker' /&gt;\n&lt;a href='#' class='clone-it'&gt;Add Another Color Picker&lt;/a&gt;\n</code></pre>\n\n<p><strong>JS</strong></p>\n\n<pre><code>(function ($) {\n // turn the field into a colorpicker\n $('.my-colorpicker').wpColorPicker () ;\n\n $('.clone-it').click (function () {\n // clone the field in question\n var field = $(this).prev ('.wp-picker-container').find ('.my-colorpicker').clone () ;\n\n // set the cloned field's value to ''\n // so it starts off without a specific color\n $(field).val ('') ;\n\n // your code to mod the cloned field's name, etc goes here \n\n // add the cloned field to the metabox\n $(this).before (field) ;\n\n // turn the cloned field into a colorpicker\n $(field).wpColorPicker () ;\n }) ;\n\n})(jQuery)\n</code></pre>\n" }, { "answer_id": 361290, "author": "Na.Sh.", "author_id": 184710, "author_profile": "https://wordpress.stackexchange.com/users/184710", "pm_score": 0, "selected": false, "text": "<p>In case you deal with the Spectrum color picker, you need to destroy the color picker before cloning the field group by calling</p>\n\n<pre><code>$(\"#my_field\").spectrum(\"destroy\");\n</code></pre>\n\n<p>Then you need to bind new color pickers to the original and the cloned field group.</p>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258223", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14649/" ]
I wrote a repeater script that clones the last field group before it. My issue is that cloned WP Color Picker fields don't open the new color spectrum when clicked on but instead opens the color picker in the group it was cloned from. Of course, it works fine once you save the field and reload the page, but not on the fly as you clone the prior group. Here's the field HTML: ``` <div class="md-repeat"> <a href="#" class="md-repeat-add">Add Another Color Picker</a> <div class="md-repeat-field"> <label for="my_field">My Color Picker Field</label> <input name="my_field" id="my_field" type="text" class="my-colorpicker" /> </div> </div> ``` and the repeater scripts: ``` ... add: function() { $( ".md-repeat-add" ).click( function( e ) { e.preventDefault(); var lastRepeatingGroup = $( this ).closest( '.md-repeat' ).find( '.md-repeat-field' ).last(), clone = lastRepeatingGroup.clone( true ); clone.find( 'input.regular-text, textarea, select' ).val( '' ); clone.find( 'input.regular-text' ).prop( 'readonly', false ); clone.find( 'input[type=checkbox]' ).attr( 'checked', false ); clone.insertAfter( lastRepeatingGroup ); MD_Repeatable_Fields.resetAtts( clone ); }); }, resetAtts: function( section ) { var attrs = [ 'for', 'id', 'name' ], tags = section.find( 'input, label, textarea, select' ), count = section.index(); tags.each( function() { var $this = $( this ); $.each( attrs, function( i, attr ) { var attr_val = $this.attr( attr ); if ( attr_val ) $this.attr( attr, attr_val.replace( /(\d+)(?=\D+$)/, count ) ); }); }); }, ... ``` How can I "reset" the color picker script to detect when new color pickers are made on the fly and execute the proper JS to open the new color picker when clicked?
It's hard to know for sure, since you don't include the markup you're output for the metabox nor the JS you're using to clone. But, the following simplified setup seems to work for me: **metabox markup** ``` <label for='my_field'> My Color Picker Field </label> <input name='my_field' id='my_field' type='text' class='my-colorpicker' /> <a href='#' class='clone-it'>Add Another Color Picker</a> ``` **JS** ``` (function ($) { // turn the field into a colorpicker $('.my-colorpicker').wpColorPicker () ; $('.clone-it').click (function () { // clone the field in question var field = $(this).prev ('.wp-picker-container').find ('.my-colorpicker').clone () ; // set the cloned field's value to '' // so it starts off without a specific color $(field).val ('') ; // your code to mod the cloned field's name, etc goes here // add the cloned field to the metabox $(this).before (field) ; // turn the cloned field into a colorpicker $(field).wpColorPicker () ; }) ; })(jQuery) ```
258,269
<p>I'm looking for a way to remove the Section <code>font_selection</code> and move the Control <code>body_font_family</code> straight to the Panel <code>font_panel</code> using Child Theme <code>functions.php</code>. Below is the sample CODE from parent theme's <code>customizer.php</code>:</p> <pre><code>//PANEL $wp_customize-&gt;add_panel( 'font_panel', array( 'priority' =&gt; 17, 'capability' =&gt; 'edit_theme_options', 'theme_supports' =&gt; '', 'title' =&gt; __('Fonts', 'theme'), ) ); //SECTION $wp_customize-&gt;add_section( 'font_selection', array( 'title' =&gt; __('Font selection', 'theme'), 'priority' =&gt; 10, 'panel' =&gt; 'font_panel', ) ) ); //SETTING $wp_customize-&gt;add_setting( 'body_font_family', array( 'sanitize_callback' =&gt; 'theme_sanitize_text', 'default' =&gt; $defaults['body_font_family'], ) ); //CONTROL $wp_customize-&gt;add_control( 'body_font_family', array( 'label' =&gt; __( 'Body font', 'theme' ), 'section' =&gt; 'font_selection', 'type' =&gt; 'text', 'priority' =&gt; 12 ) ); </code></pre>
[ { "answer_id": 258477, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 1, "selected": false, "text": "<p>Assuming that the parent theme is running the above code at <code>customize_register</code> priority 10, you just have to add another <code>customize_register</code> action callback that runs afterward, like at 20. However, you cannot move a control to a <em>panel</em>. Controls can only reside inside of <em>sections</em>. To move a control to another section you can use:</p>\n\n<pre><code>add_action( 'customize_register', function ( WP_Customize_Manager $wp_customize ) {\n $wp_customize-&gt;remove_section( 'font_selection' );\n $wp_customize-&gt;add_section( 'some_other_section', array(\n 'title' =&gt; __( 'Some other section', 'theme' ),\n ) );\n\n $body_font_family_control = $wp_customize-&gt;get_control( 'body_font_family' );\n if ( $body_font_family_control ) {\n $body_font_family_control-&gt;section = 'some_other_section';\n }\n}, 20 );\n</code></pre>\n" }, { "answer_id": 259872, "author": "Imon Hasan Imon Theme", "author_id": 115313, "author_profile": "https://wordpress.stackexchange.com/users/115313", "pm_score": 0, "selected": false, "text": "<p>Possible to move widgets control to another section ?</p>\n\n<p>Like sidebar_widgets want to move my_section </p>\n\n<pre><code>$sidebars_widgets_control = $wp_customize-&gt;get_control( 'sidebars_widgets-foot_sidebar' );\n if ( $sidebars_widgets_control ) {\n $sidebars_widgets_control-&gt;section = 'my_settings';\n }\n}, 20 );\n</code></pre>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258269", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113957/" ]
I'm looking for a way to remove the Section `font_selection` and move the Control `body_font_family` straight to the Panel `font_panel` using Child Theme `functions.php`. Below is the sample CODE from parent theme's `customizer.php`: ``` //PANEL $wp_customize->add_panel( 'font_panel', array( 'priority' => 17, 'capability' => 'edit_theme_options', 'theme_supports' => '', 'title' => __('Fonts', 'theme'), ) ); //SECTION $wp_customize->add_section( 'font_selection', array( 'title' => __('Font selection', 'theme'), 'priority' => 10, 'panel' => 'font_panel', ) ) ); //SETTING $wp_customize->add_setting( 'body_font_family', array( 'sanitize_callback' => 'theme_sanitize_text', 'default' => $defaults['body_font_family'], ) ); //CONTROL $wp_customize->add_control( 'body_font_family', array( 'label' => __( 'Body font', 'theme' ), 'section' => 'font_selection', 'type' => 'text', 'priority' => 12 ) ); ```
Assuming that the parent theme is running the above code at `customize_register` priority 10, you just have to add another `customize_register` action callback that runs afterward, like at 20. However, you cannot move a control to a *panel*. Controls can only reside inside of *sections*. To move a control to another section you can use: ``` add_action( 'customize_register', function ( WP_Customize_Manager $wp_customize ) { $wp_customize->remove_section( 'font_selection' ); $wp_customize->add_section( 'some_other_section', array( 'title' => __( 'Some other section', 'theme' ), ) ); $body_font_family_control = $wp_customize->get_control( 'body_font_family' ); if ( $body_font_family_control ) { $body_font_family_control->section = 'some_other_section'; } }, 20 ); ```
258,277
<p>When doing a template such as single.php and you have php wrapped in html, is it best to :</p> <ol> <li><p>Start + Stop PHP? for example</p> <pre><code> &lt;h1 class="post-tilte"&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;p class="post-content"&gt;&lt;?php the_content();?&gt;&lt;/p&gt; </code></pre></li> </ol> <p>Or</p> <ol start="2"> <li><p>Echo HTML and Escape PHP? For example - </p> <pre><code>&lt;?php echo '&lt;h1 class="post-title"&gt;' . get_the_title() . '&lt;/h1&gt; &lt;p class="post-content"' . get_the_content() . '&lt;/p&gt; </code></pre></li> </ol> <p>I dont have a prefreed choice and find myself doing both, just curious to hear some thoughts</p>
[ { "answer_id": 258283, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 3, "selected": false, "text": "<p>That's question is only relevant, because WordPress use a mix from a coding language and layout language. If you would use a template language, syntax, than is this topic not relevant.\nBut to your question. If you use your example source for a Theme, much more layout language like html, then I prefer the first one - it is much more readable for designer and users, there must read the markup. It is easier to create an overview about the markup, have you the open and closing tags etc.</p>\n\n<p>For the include in plugins, code with more logic and flow is the second example easier to implement. The main topic is php, not markup and this should it visible in the source. That's also a point to think about to exclude this markup in template files and separate the markup from the logic.</p>\n" }, { "answer_id": 258289, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 3, "selected": false, "text": "<p>Just as additional information. WordPress has <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/\" rel=\"noreferrer\">handbooks for PHP &amp; HTML on best practice regarding coding standards</a>, also for CSS, JavaScript and Accessibility. You might find them helpful for getting deeper into the matter. </p>\n" }, { "answer_id": 258590, "author": "not2savvy", "author_id": 114567, "author_profile": "https://wordpress.stackexchange.com/users/114567", "pm_score": 0, "selected": false, "text": "<p>The first method is preferable because:</p>\n\n<ul>\n<li>It clearly separates the fixed HTML layout from the dynamic contents.</li>\n<li>It is easier to read.</li>\n<li>It is better supported by syntax highlighting in most editors, because the in-string html attributes are usually not recognized.</li>\n<li>It prevents you from intermingling HTML and PHP too easily.</li>\n</ul>\n\n<p>Because of the reasons stated above, the first method leads to code that is easier to understand and thus easier to maintain.</p>\n\n<p>In my experience, in some situations, it can appear to be more convenient to use the second method. However, that is usually due to weak (software) design and should be seen as warning sign. </p>\n" }, { "answer_id": 258613, "author": "Anwer AR", "author_id": 83820, "author_profile": "https://wordpress.stackexchange.com/users/83820", "pm_score": 3, "selected": false, "text": "<p>As explained in above answer, the first method is designer friendly &amp; second method maybe suitable in cases of plugins and complex php codes where the number of html tags are only few.</p>\n\n<p>But most of WordPress template tags has <code>before</code> and <code>after</code> parameters and its more appropriate to use your html codes inside of function call.</p>\n\n<p>for example in the case of <code>the_title</code> it has three parameters</p>\n\n<pre><code>the_title( $before, $after, $echo );\n</code></pre>\n\n<p>you can pass your html to before and after parameters like below</p>\n\n<pre><code>the_title( '&lt;h2 class=\"title\"&gt;', '&lt;/h2&gt;', true );\n</code></pre>\n\n<p>the advantages of this method is </p>\n\n<ul>\n<li>Designer Friendly </li>\n<li>will not print out html tags if title is empty</li>\n<li>can be used in complex php codes as well as in simple template files</li>\n</ul>\n" }, { "answer_id": 260100, "author": "Nadav", "author_id": 115422, "author_profile": "https://wordpress.stackexchange.com/users/115422", "pm_score": 0, "selected": false, "text": "<p>You're code example is marginal because it only shows two lines of code, but I believe the overall answer is quite situational. If you are using a PHP line within an HTML block use the first method. If you are using an HTML line within a PHP block go with the second one.</p>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102774/" ]
When doing a template such as single.php and you have php wrapped in html, is it best to : 1. Start + Stop PHP? for example ``` <h1 class="post-tilte"><?php the_title(); ?></h1> <p class="post-content"><?php the_content();?></p> ``` Or 2. Echo HTML and Escape PHP? For example - ``` <?php echo '<h1 class="post-title">' . get_the_title() . '</h1> <p class="post-content"' . get_the_content() . '</p> ``` I dont have a prefreed choice and find myself doing both, just curious to hear some thoughts
That's question is only relevant, because WordPress use a mix from a coding language and layout language. If you would use a template language, syntax, than is this topic not relevant. But to your question. If you use your example source for a Theme, much more layout language like html, then I prefer the first one - it is much more readable for designer and users, there must read the markup. It is easier to create an overview about the markup, have you the open and closing tags etc. For the include in plugins, code with more logic and flow is the second example easier to implement. The main topic is php, not markup and this should it visible in the source. That's also a point to think about to exclude this markup in template files and separate the markup from the logic.
258,279
<p>I want to add more classes in the <code>div</code> tag of my search widget. My search is located in the sidebar together with other widgets.</p> <p>My code:</p> <pre><code>function NT_widgets_init() { register_sidebar( array( 'name' =&gt; __( 'Sidebar', 'side' ), 'id' =&gt; 'sidebar', 'description' =&gt; __( 'Rechte Spalte', 'rechts' ), 'before_widget' =&gt; '&lt;div id="%1$s" class="widget %2$s"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;span class="none"&gt;', 'after_title' =&gt; '&lt;/span&gt;', ) ); } add_action( 'widgets_init', 'NT_widgets_init' ); </code></pre> <p>So each widget gets an <code>id</code> and a <code>class</code>. How can I add more classes to only ONE widget, not the rest.</p>
[ { "answer_id": 258292, "author": "Nabil Kadimi", "author_id": 17187, "author_profile": "https://wordpress.stackexchange.com/users/17187", "pm_score": 3, "selected": true, "text": "<p>You have two possible solutions.</p>\n\n<h2>1. The <code>widget_display_callback</code> filter hook</h2>\n\n<p><a href=\"http://hookr.io/filters/widget_display_callback/\" rel=\"nofollow noreferrer\">This filter hook</a> parameters allows you to target easily the widget instance and override it's arguments.</p>\n\n<p>A possible approach would be: Inside the filter callback, modify the arguments for that instance, display it and then <strong>return <code>false</code></strong> to prevent it from being displayed again the normal way by WordPress. See this code in <a href=\"https://github.com/WordPress/WordPress/blob/5f4497/wp-includes/class-wp-widget.php#L373-L399\" rel=\"nofollow noreferrer\">wp-includes/class-wp-widget.php</a>.</p>\n\n<h2>2. Register a new widget that extends the search widget</h2>\n\n<p>You can extend the search widget --defined in <a href=\"https://github.com/WordPress/WordPress/blob/dd6da7/wp-includes/widgets/class-wp-widget-search.php\" rel=\"nofollow noreferrer\">wp-includes/widgets/class-wp-widget-search.php</a> and override the <code>widget()</code> method to add the class you want, something like this <em>(code should be added in some place seen by WordPress, like a custom plugin or in your theme <code>functions.php</code> file)</em>:</p>\n\n<pre><code>/**\n * Custom widget search\n *\n * Extends the default search widget and adds a class to classes in `before_title`\n *\n * @author Nabil Kadimi\n * @link http://wordpress.stackexchange.com/a/258292/17187\n */\nclass WP_Widget_Search_Custom extends WP_Widget_Search {\n\n public function __construct() {\n $widget_ops = array(\n 'classname' =&gt; 'widget_search widget_search_custom',\n 'description' =&gt; __( 'A Custom search form for your site.' ),\n 'customize_selective_refresh' =&gt; true,\n );\n WP_Widget::__construct( 'search_custom', _x( 'Custom Search', 'Custom Search widget' ), $widget_ops );\n }\n\n public function widget( $args, $instance ) {\n\n $custom_class = 'wpse-258279';\n $args['before_widget'] = str_replace('class=\"', \"class=\\\"$custom_class\", $args['before_widget']);\n\n /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */\n $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this-&gt;id_base );\n echo $args['before_widget'];\n if ( $title ) {\n echo $args['before_title'] . $title . $args['after_title'];\n }\n // Use current theme search form if it exists\n get_search_form();\n echo $args['after_widget'];\n }\n}\n\n/**\n * Register the custom search widget\n */\nadd_action( 'widgets_init', function() {\n register_widget( 'WP_Widget_Search_Custom' );\n} );\n</code></pre>\n" }, { "answer_id": 258322, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": false, "text": "<h1>Option-1: Using CSS class already provided:</h1>\n\n<p>Every widget already provides unique <code>id</code> and <code>class</code> to use in CSS rules. So for most styling needs, it's better to use those to generate specific CSS rule that'll only work for that widget (e.g. Search). For example, the default Search widget will have the CSS class <code>widget_search</code>. You may use it to style the search widget differently from other widgets. Like:</p>\n\n<pre><code>.widget {\n background-color: wheat;\n}\n.widget.widget_search {\n background-color: gold;\n}\n</code></pre>\n\n<h1>Option-2: Using <code>dynamic_sidebar_params</code> filter:</h1>\n\n<p>Since you are registering the widgets with <code>register_sidebar()</code> function, most likely you've used it with <code>dynamic_sidebar()</code> function in the templates. In that case, you may use the <a href=\"https://developer.wordpress.org/reference/hooks/dynamic_sidebar_params/\" rel=\"nofollow noreferrer\"><code>dynamic_sidebar_params</code></a> filter hook to insert extra CSS classes only to a specific widget.</p>\n\n<p>Use the following CODE in your theme's <code>functions.php</code> file (additional instructions are there in the CODE):</p>\n\n<pre><code>add_filter( 'dynamic_sidebar_params', 'wpse258279_filter_widget' );\nfunction wpse258279_filter_widget( $params ) {\n // avoiding admin panel\n if( ! is_admin() ) {\n if ( is_array( $params ) &amp;&amp; is_array( $params[0] ) &amp;&amp; $params[0]['widget_name'] === 'Search' ) {\n // Insert your custom CSS class (one or more) in the following array\n $classes = array( 'custom-css-class-for-search' );\n\n // The following three lines will add $classes\n // (along with the existing CSS classes) using regular expression\n // don't touch it if you don't know RegEx\n $pattern = '/class\\s*=\\s*([\"\\'])(?:\\s*((?!\\1).*?)\\s*)?\\1/i';\n $replace = 'class=$1$2 ' . implode( ' ', $classes ) . '$1';\n $params[0]['before_widget'] = preg_replace( $pattern, $replace, $params[0]['before_widget'], 1 );\n }\n }\n return $params;\n}\n</code></pre>\n\n<p>With the above CODE, you may add one or more CSS classes in this line: <code>$classes = array( 'custom-css-class-for-search' );</code>. So if you want to add two CSS classes for the search widget, it'll be like:</p>\n\n<pre><code>$classes = array( 'custom-css-class-for-search', 'another-class' );\n</code></pre>\n\n<h1>Option-3: Custom Widget:</h1>\n\n<p>If you need more control than the above methods can handle, then you may implement custom Widget for Search <a href=\"https://wordpress.stackexchange.com/a/258292/110572\">like shown in this answer</a>. </p>\n\n<p>However, it may be difficult to maintain custom widgets if you want the same behaviour for multiple widgets. Because then you'll have to implement that widget too (only for extra CSS class)! If that's not an issue for you, then you may follow that path, as with a custom Widget, you'll have far better control over the markups and functionality.</p>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258279", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93472/" ]
I want to add more classes in the `div` tag of my search widget. My search is located in the sidebar together with other widgets. My code: ``` function NT_widgets_init() { register_sidebar( array( 'name' => __( 'Sidebar', 'side' ), 'id' => 'sidebar', 'description' => __( 'Rechte Spalte', 'rechts' ), 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<span class="none">', 'after_title' => '</span>', ) ); } add_action( 'widgets_init', 'NT_widgets_init' ); ``` So each widget gets an `id` and a `class`. How can I add more classes to only ONE widget, not the rest.
You have two possible solutions. 1. The `widget_display_callback` filter hook -------------------------------------------- [This filter hook](http://hookr.io/filters/widget_display_callback/) parameters allows you to target easily the widget instance and override it's arguments. A possible approach would be: Inside the filter callback, modify the arguments for that instance, display it and then **return `false`** to prevent it from being displayed again the normal way by WordPress. See this code in [wp-includes/class-wp-widget.php](https://github.com/WordPress/WordPress/blob/5f4497/wp-includes/class-wp-widget.php#L373-L399). 2. Register a new widget that extends the search widget ------------------------------------------------------- You can extend the search widget --defined in [wp-includes/widgets/class-wp-widget-search.php](https://github.com/WordPress/WordPress/blob/dd6da7/wp-includes/widgets/class-wp-widget-search.php) and override the `widget()` method to add the class you want, something like this *(code should be added in some place seen by WordPress, like a custom plugin or in your theme `functions.php` file)*: ``` /** * Custom widget search * * Extends the default search widget and adds a class to classes in `before_title` * * @author Nabil Kadimi * @link http://wordpress.stackexchange.com/a/258292/17187 */ class WP_Widget_Search_Custom extends WP_Widget_Search { public function __construct() { $widget_ops = array( 'classname' => 'widget_search widget_search_custom', 'description' => __( 'A Custom search form for your site.' ), 'customize_selective_refresh' => true, ); WP_Widget::__construct( 'search_custom', _x( 'Custom Search', 'Custom Search widget' ), $widget_ops ); } public function widget( $args, $instance ) { $custom_class = 'wpse-258279'; $args['before_widget'] = str_replace('class="', "class=\"$custom_class", $args['before_widget']); /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */ $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base ); echo $args['before_widget']; if ( $title ) { echo $args['before_title'] . $title . $args['after_title']; } // Use current theme search form if it exists get_search_form(); echo $args['after_widget']; } } /** * Register the custom search widget */ add_action( 'widgets_init', function() { register_widget( 'WP_Widget_Search_Custom' ); } ); ```
258,286
<p>I am developing a wp theme and I want to have a shortcode that can be used serveral times from within an article.</p> <p>in functions.php i have:</p> <pre><code>function twoColPostcardfn($atts, $content){ extract(shortcode_atts(array( 'image'=&gt;'', 'text'=&gt;'', 'title'=&gt;'', 'boxlink'=&gt;'', 'float'=&gt;'' ), $atts)); $bob='&lt;span class="twoColPostcard "&gt;'.$content.'&lt;/span&gt;'; return $bob; } add_shortcode( 'twoColPostcard', 'twoColPostcardfn' ); </code></pre> <p>in the article I have:</p> <pre><code>&lt;p&gt;[twoColPostcard]&lt;/p&gt; &lt;p&gt;hello from the first postcard&lt;/p&gt; &lt;p&gt;[/twoColPostcard]&lt;/p&gt; &lt;p&gt;[twoColPostcard]&lt;/p&gt; &lt;p&gt;hello from the second postcard&lt;/p&gt; &lt;p&gt;[/twoColPostcard]&lt;/p&gt; </code></pre> <p>And I want my output to be</p> <pre><code>&lt;span class="twoColPostcard"&gt;&lt;p&gt;Hello from ...&lt;/p&gt;&lt;/span&gt; &lt;span class="twoColPostcard"&gt;&lt;p&gt;Hello from ...&lt;/p&gt;&lt;/span&gt; </code></pre> <p>But instead I am getting:</p> <pre><code>&lt;span class="twoColPostcard"&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;hello from the first postcard&lt;/p&gt; &lt;p&gt;&lt;span class="twoColPostcard "&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;hello from the second postcard&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;/span&gt; </code></pre> <p>In other words the second shortcode is begun before the first one is finished so the are ending up nested (and the 2nd one is empty)</p> <p>I used the <a href="https://codex.wordpress.org/Shortcode_API#Enclosing_vs_self-closing_shortcodes" rel="nofollow noreferrer">codex</a> to help but its not working and I don't know why. I have tried inserting this into my functions <a href="https://wordpress.stackexchange.com/questions/175025/wraping-content-into-link-with-shortcodes">as per</a> to no avail</p> <pre><code>remove_filter( 'the_content', 'wpautop' ); add_filter( 'the_content', 'wpautop' , 12); </code></pre>
[ { "answer_id": 258291, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>It looks like you're adding unnecessary <code>&lt;p&gt;</code> tags around your shortcodes. Try this instead:</p>\n\n<pre><code>[twoColPostcard]&lt;p&gt;hello from the first postcard&lt;/p&gt;[/twoColPostcard]\n[twoColPostcard]&lt;p&gt;hello from the second postcard&lt;/p&gt;[/twoColPostcard]\n</code></pre>\n" }, { "answer_id": 258306, "author": "Samyer", "author_id": 112788, "author_profile": "https://wordpress.stackexchange.com/users/112788", "pm_score": 1, "selected": false, "text": "<p>Why use p tags at all? Don't enter any new lines and p tags won't be added. Just add it all on line: </p>\n\n<pre><code>[twoColPostcard]hello from the first postcard[/twoColPostcard[twoColPostcard]hello from the second postcard[/twoColPostcard]\n</code></pre>\n\n<p>And then change your shortcode to include the p tags:</p>\n\n<pre><code>function twoColPostcardfn($atts, $content){\nextract(shortcode_atts(array(\n 'image'=&gt;'',\n 'text'=&gt;'',\n 'title'=&gt;'',\n 'boxlink'=&gt;'',\n 'float'=&gt;''\n ), $atts));\n$bob='&lt;span class=\"twoColPostcard \"&gt;&lt;p&gt;'.$content.'&lt;/p&gt;&lt;/span&gt;';\nreturn $bob;\n}\nadd_shortcode( 'twoColPostcard', 'twoColPostcardfn' );\n</code></pre>\n" }, { "answer_id": 258312, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 3, "selected": true, "text": "<p>put the remove filter to be called first like this, change your <code>span</code> to <code>div</code> or you will have issues with some browsers:</p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nadd_filter( 'the_content', 'wpautop' , 12);\n\nfunction twoColPostcardfn($atts, $content){\n extract(shortcode_atts(array(\n 'image'=&gt;'',\n 'text'=&gt;'',\n 'title'=&gt;'',\n 'boxlink'=&gt;'',\n 'float'=&gt;''\n ), $atts));\n $bob='&lt;div class=\"twoColPostcard \"&gt;'.$content.'&lt;/div&gt;';\n return $bob;\n}\nadd_shortcode( 'twoColPostcard', 'twoColPostcardfn' );\n</code></pre>\n\n<p>or change the content to another <code>span</code>, the <code>p</code> tag is a block tag and the <code>span</code> tag is an inline tag, a block tag cant be inside an inline one.</p>\n\n<pre><code>[twoColPostcard]&lt;span&gt;hello from the first postcard&lt;/span&gt;[/twoColPostcard]\n[twoColPostcard]&lt;span&gt;hello from the second postcard&lt;/span&gt;[/twoColPostcard]\n</code></pre>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258286", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81925/" ]
I am developing a wp theme and I want to have a shortcode that can be used serveral times from within an article. in functions.php i have: ``` function twoColPostcardfn($atts, $content){ extract(shortcode_atts(array( 'image'=>'', 'text'=>'', 'title'=>'', 'boxlink'=>'', 'float'=>'' ), $atts)); $bob='<span class="twoColPostcard ">'.$content.'</span>'; return $bob; } add_shortcode( 'twoColPostcard', 'twoColPostcardfn' ); ``` in the article I have: ``` <p>[twoColPostcard]</p> <p>hello from the first postcard</p> <p>[/twoColPostcard]</p> <p>[twoColPostcard]</p> <p>hello from the second postcard</p> <p>[/twoColPostcard]</p> ``` And I want my output to be ``` <span class="twoColPostcard"><p>Hello from ...</p></span> <span class="twoColPostcard"><p>Hello from ...</p></span> ``` But instead I am getting: ``` <span class="twoColPostcard"> <p></p> <p>hello from the first postcard</p> <p><span class="twoColPostcard "></span></p> <p>hello from the second postcard</p> <p></p> </span> ``` In other words the second shortcode is begun before the first one is finished so the are ending up nested (and the 2nd one is empty) I used the [codex](https://codex.wordpress.org/Shortcode_API#Enclosing_vs_self-closing_shortcodes) to help but its not working and I don't know why. I have tried inserting this into my functions [as per](https://wordpress.stackexchange.com/questions/175025/wraping-content-into-link-with-shortcodes) to no avail ``` remove_filter( 'the_content', 'wpautop' ); add_filter( 'the_content', 'wpautop' , 12); ```
put the remove filter to be called first like this, change your `span` to `div` or you will have issues with some browsers: ``` remove_filter( 'the_content', 'wpautop' ); add_filter( 'the_content', 'wpautop' , 12); function twoColPostcardfn($atts, $content){ extract(shortcode_atts(array( 'image'=>'', 'text'=>'', 'title'=>'', 'boxlink'=>'', 'float'=>'' ), $atts)); $bob='<div class="twoColPostcard ">'.$content.'</div>'; return $bob; } add_shortcode( 'twoColPostcard', 'twoColPostcardfn' ); ``` or change the content to another `span`, the `p` tag is a block tag and the `span` tag is an inline tag, a block tag cant be inside an inline one. ``` [twoColPostcard]<span>hello from the first postcard</span>[/twoColPostcard] [twoColPostcard]<span>hello from the second postcard</span>[/twoColPostcard] ```
258,300
<p>I'm querying all child pages on my current page with a custom Query like this.</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'page', 'posts_per_page' =&gt; -1, 'post_parent' =&gt; $post-&gt;ID, 'order' =&gt; 'ASC', 'orderby' =&gt; 'menu_order' ); $subservice = new WP_Query( $args ); if ( $subservice-&gt;have_posts() ) : ?&gt; &lt;?php while ( $subservice-&gt;have_posts() ) : $subservice-&gt;the_post();?&gt; </code></pre> <p>How do I get all slugs from these child pages into a javascript function?</p> <p>I'm initialising my jQuery Plugin like this:</p> <pre><code>$('#pagepiling').pagepiling({ sectionSelector: '.box', anchors: ['intro', 'section2','section3'], menu: '#menu' )}; </code></pre> <p>That means, the <code>anchors</code> option should display my child-page slugs from my current page. </p> <p>Thanks for your help! Cara</p>
[ { "answer_id": 258291, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>It looks like you're adding unnecessary <code>&lt;p&gt;</code> tags around your shortcodes. Try this instead:</p>\n\n<pre><code>[twoColPostcard]&lt;p&gt;hello from the first postcard&lt;/p&gt;[/twoColPostcard]\n[twoColPostcard]&lt;p&gt;hello from the second postcard&lt;/p&gt;[/twoColPostcard]\n</code></pre>\n" }, { "answer_id": 258306, "author": "Samyer", "author_id": 112788, "author_profile": "https://wordpress.stackexchange.com/users/112788", "pm_score": 1, "selected": false, "text": "<p>Why use p tags at all? Don't enter any new lines and p tags won't be added. Just add it all on line: </p>\n\n<pre><code>[twoColPostcard]hello from the first postcard[/twoColPostcard[twoColPostcard]hello from the second postcard[/twoColPostcard]\n</code></pre>\n\n<p>And then change your shortcode to include the p tags:</p>\n\n<pre><code>function twoColPostcardfn($atts, $content){\nextract(shortcode_atts(array(\n 'image'=&gt;'',\n 'text'=&gt;'',\n 'title'=&gt;'',\n 'boxlink'=&gt;'',\n 'float'=&gt;''\n ), $atts));\n$bob='&lt;span class=\"twoColPostcard \"&gt;&lt;p&gt;'.$content.'&lt;/p&gt;&lt;/span&gt;';\nreturn $bob;\n}\nadd_shortcode( 'twoColPostcard', 'twoColPostcardfn' );\n</code></pre>\n" }, { "answer_id": 258312, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 3, "selected": true, "text": "<p>put the remove filter to be called first like this, change your <code>span</code> to <code>div</code> or you will have issues with some browsers:</p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nadd_filter( 'the_content', 'wpautop' , 12);\n\nfunction twoColPostcardfn($atts, $content){\n extract(shortcode_atts(array(\n 'image'=&gt;'',\n 'text'=&gt;'',\n 'title'=&gt;'',\n 'boxlink'=&gt;'',\n 'float'=&gt;''\n ), $atts));\n $bob='&lt;div class=\"twoColPostcard \"&gt;'.$content.'&lt;/div&gt;';\n return $bob;\n}\nadd_shortcode( 'twoColPostcard', 'twoColPostcardfn' );\n</code></pre>\n\n<p>or change the content to another <code>span</code>, the <code>p</code> tag is a block tag and the <code>span</code> tag is an inline tag, a block tag cant be inside an inline one.</p>\n\n<pre><code>[twoColPostcard]&lt;span&gt;hello from the first postcard&lt;/span&gt;[/twoColPostcard]\n[twoColPostcard]&lt;span&gt;hello from the second postcard&lt;/span&gt;[/twoColPostcard]\n</code></pre>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258300", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113943/" ]
I'm querying all child pages on my current page with a custom Query like this. ``` <?php $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => $post->ID, 'order' => 'ASC', 'orderby' => 'menu_order' ); $subservice = new WP_Query( $args ); if ( $subservice->have_posts() ) : ?> <?php while ( $subservice->have_posts() ) : $subservice->the_post();?> ``` How do I get all slugs from these child pages into a javascript function? I'm initialising my jQuery Plugin like this: ``` $('#pagepiling').pagepiling({ sectionSelector: '.box', anchors: ['intro', 'section2','section3'], menu: '#menu' )}; ``` That means, the `anchors` option should display my child-page slugs from my current page. Thanks for your help! Cara
put the remove filter to be called first like this, change your `span` to `div` or you will have issues with some browsers: ``` remove_filter( 'the_content', 'wpautop' ); add_filter( 'the_content', 'wpautop' , 12); function twoColPostcardfn($atts, $content){ extract(shortcode_atts(array( 'image'=>'', 'text'=>'', 'title'=>'', 'boxlink'=>'', 'float'=>'' ), $atts)); $bob='<div class="twoColPostcard ">'.$content.'</div>'; return $bob; } add_shortcode( 'twoColPostcard', 'twoColPostcardfn' ); ``` or change the content to another `span`, the `p` tag is a block tag and the `span` tag is an inline tag, a block tag cant be inside an inline one. ``` [twoColPostcard]<span>hello from the first postcard</span>[/twoColPostcard] [twoColPostcard]<span>hello from the second postcard</span>[/twoColPostcard] ```
258,323
<p>I am running on <code>WP 4.7.2</code> and <code>Yoast SEO 4.4</code>. I want to append a PHP variable to all titles. But it seems I am not able to do that. </p> <p>I have read that <code>wp_title</code> used to be the method before WP 4.4, then it was removed, and then it was returned because of some 'bug'?</p> <p>I have tried using the <code>wpseo</code>+<code>add_filter</code> method, but it does not set the site title. </p> <p>I have searched <code>/wp-content/plugins/wordpress-seo</code> via <code>grep -r '&lt;title&gt;' *</code> and am not seeing where the plugin sets the title tag. It did return few lines, but none of them seem to be related. </p> <p>I found the following code in <code>clss-frontend.php</code>:</p> <pre><code>// When using WP 4.4, just use the new hook. add_filter( 'pre_get_document_title', array( $this, 'title' ), 15 ); add_filter( 'wp_title', array( $this, 'title' ), 15, 3 ); </code></pre>
[ { "answer_id": 258329, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 4, "selected": true, "text": "<p>There's a <code>wpseo_title</code> filter you can hook into. Example:</p>\n\n<pre><code>add_filter('wpseo_title', 'add_to_page_titles');\nfunction add_to_page_titles($title) {\n $title .= $addToTitle;\n return $title;\n}\n</code></pre>\n" }, { "answer_id": 258333, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<h2>Where does Yoast SEO plugin sets the site/page title?</h2>\n\n<p>Yoast SEO plugin adds two hooks that filter the title.</p>\n\n<pre><code>add_filter( 'pre_get_document_title', array( $this, 'title' ), 15 );\nadd_filter( 'wp_title', array( $this, 'title' ), 15, 3 );\n</code></pre>\n\n<p>The <code>pre_get_document_title</code> hook was added in WordPress 4.4, so on older versions, that hook will never get fired. </p>\n\n<p>For versions older than 4.4, the <code>wp_title</code> hook will generate the SEO title.<br>\nFor versions newer than 4.4, the <code>pre_get_document_title</code> hook will generate the SEO title. </p>\n\n<p>The <code>wp_title</code> hook will still fire on versions newer than 4.4, but it won't do anything because if we look at the <a href=\"https://plugins.trac.wordpress.org/browser/wordpress-seo/trunk/frontend/class-frontend.php#L407\" rel=\"nofollow noreferrer\">WPSEO_Frontend::title()</a> method, notice that if the the $title property is already set, it will simply return that. If it's not set, it will generate the title using the <a href=\"https://plugins.trac.wordpress.org/browser/wordpress-seo/trunk/frontend/class-frontend.php#L423\" rel=\"nofollow noreferrer\">WPSEO_Frontend::generate_title()</a> method.</p>\n\n<h2>How to change the SEO title?</h2>\n\n<p>To modify the SEO title, you need to hook in after Yoast generates the title, but before it's output. The latest that Yoast SEO could generate the title is on the <code>wp_title</code> hook at a priority of 15. The title is output after all the <code>wp_title</code> hooks are processed. So we need to hook into <code>wp_title</code> <em>after</em> 15.</p>\n\n<p>If you want to change the title from within another plugin, just add the following code to your plugin:<br>\nIf you want to change the title from within your theme, add the following toyour functions.php file: </p>\n\n<pre><code>//* Hooking after priority 15 guarantees that Yoast SEO has generated the title\nadd_filter( 'wp_title', 'wpse_258323_title', 20, 2 );\nfunction wpse_258323_title( $title, $post_id ) {\n //* Do something with the $title\n return $title;\n}\n</code></pre>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50416/" ]
I am running on `WP 4.7.2` and `Yoast SEO 4.4`. I want to append a PHP variable to all titles. But it seems I am not able to do that. I have read that `wp_title` used to be the method before WP 4.4, then it was removed, and then it was returned because of some 'bug'? I have tried using the `wpseo`+`add_filter` method, but it does not set the site title. I have searched `/wp-content/plugins/wordpress-seo` via `grep -r '<title>' *` and am not seeing where the plugin sets the title tag. It did return few lines, but none of them seem to be related. I found the following code in `clss-frontend.php`: ``` // When using WP 4.4, just use the new hook. add_filter( 'pre_get_document_title', array( $this, 'title' ), 15 ); add_filter( 'wp_title', array( $this, 'title' ), 15, 3 ); ```
There's a `wpseo_title` filter you can hook into. Example: ``` add_filter('wpseo_title', 'add_to_page_titles'); function add_to_page_titles($title) { $title .= $addToTitle; return $title; } ```
258,345
<p>First of all thanks for reading, and my apologies for my lack of knowledge.</p> <p>I have a WP site running with a theme and a child theme. I run it in 3 languages Spanish, English and Portuguese; and for handling the translations I'm using WPML plugin.</p> <p>My problem is that in the translated Portfolios and Contact page the site is not looking quite as I want. After quite a lot of research on WPML support's end the conclusion was that my devs the child-theme including additional CSS sheets that are surprisingly set to post/page specific levels. So the styling goes like in the pictures:</p> <p><img src="https://d2salfytceyqoe.cloudfront.net/wp-content/uploads/2017/02/1216707-CSSSheetPageLevelStyling.png" alt="CSSSheetPageLevelStyling"></p> <p><img src="https://d2salfytceyqoe.cloudfront.net/wp-content/uploads/2017/02/1216707-MorePageSpecificStyling.png" alt="CMorePageSpecificStyling"></p> <p>And the same goes for the Contacts ID posts.</p> <p>So in this scenario WMPL support solution is to "copy" the script and just change in the copied lines the post id.</p> <p>I believe this is a short term solution as if in the future any of the following happen I will have to re do it again:</p> <p>-I want to create a second Portfolio Page -I want to add a new language -For whatever reason I delete the portfolio or contact page and re do it it will have a new post ID</p> <p>So the question is: Isn't another option to achieve this in a more "clean" fashion? I wouldn't know how but I imagine something like saying in the CSS, for Portfolios the styling should be these -no matter which language-; for Contact, the styling should be these, etc</p> <p>My dev is saying this approach is wrong, but for me their explanations make no sense.</p> <p>Any advise would be deeply appreciate</p> <p>Cheers</p>
[ { "answer_id": 258350, "author": "montrealist", "author_id": 8105, "author_profile": "https://wordpress.stackexchange.com/users/8105", "pm_score": 2, "selected": false, "text": "<p>You're absolutely right in your assumption. CSS should <strong>never</strong> be tied to post IDs, because they can always change (for example if you decide to migrate your posts to another install).</p>\n\n<p>You can always shift control towards the admin dashboard.</p>\n\n<p>Add a custom field in a post/page that you want styled in a special way (in your example you would have the same custom field in all language versions of the post/page). Let's say it will be <code>wpse_custom_class</code>. Add it to each post/page; the value will be <code>portfolio</code> for this example.</p>\n\n<p>Add this code to <code>functions.php</code> (copied from <a href=\"https://wordpress.stackexchange.com/a/64124/8105\">this answer</a>). When the page loads it will look for a custom field and insert its value as a CSS class on the HTML body element.</p>\n\n<pre><code>function wpse_filter_post_class( $classes ) {\n $my_post_class = get_post_meta($post-&gt;ID, \"wpse_custom_class\");\n\n if( $my_post_class != '' ) {\n $classes[] = $my_post_class;\n }\n return $classes;\n}\n\nadd_filter( 'post_class', 'wpse_filter_post_class' );\n</code></pre>\n\n<p>Your designer can now use it like so:</p>\n\n<pre><code>.portfolio #content .main {\n max-width: 100%;\n}\n</code></pre>\n\n<p>This is more work on the admin side (you or the designer will need to manually go in and specify those CSS classes for all the custom-styled pages), but ultimately it contributes to a very flexible and future-proof solution.</p>\n" }, { "answer_id": 258351, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 1, "selected": false, "text": "<h1>Why not to use ID specific CSS rules:</h1>\n\n<p>Post ID specific CSS can only be a quick fix and it's far from the best practice. Post ID is not reliable in many cases. For example:</p>\n\n<ul>\n<li><p>May be you'll delete a post and replace that with a new post.</p></li>\n<li><p>May be you'll need to migrate your site in the future to another server.</p></li>\n<li><p>May be you are creating a newer version of the post / page and want to review the new post / page before replacing the old one.</p></li>\n</ul>\n\n<p>In all these cases, post ID is likely to change and those ID specific CSS will not be even applicable any more. So you'll have to update your CSS again to match your design needs. WordPress is extremely customizable, so there is no scenario where you have to use post ID base CSS rules. For a more mature development and design practice, using ID specific CSS rules are highly discouraged. Instead, use one of the options below:</p>\n\n<h1>Use Page Templates:</h1>\n\n<p>WordPress supports <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=\"nofollow noreferrer\">page templates</a> for pages for a long time and from version <code>4.7</code> WordPress supports <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/#creating-page-templates-for-specific-post-types\" rel=\"nofollow noreferrer\">page templates for any post type</a>. So if you you have WordPress <code>4.7</code> or later, then you may create specific page template for any posts or pages in your child theme.</p>\n\n<p>This way you don't need any ID specific CSS at all, because once you have those specific templates, whenever you'll need the same design for any page or post, you'll simply have to choose the same template from the post or page editor. That's all. After that, design of that page template will apply to that <code>page</code>, <code>post</code> or <code>custom post type</code>.</p>\n\n<h1>Use <a href=\"https://developer.wordpress.org/reference/hooks/post_class/\" rel=\"nofollow noreferrer\"><code>post_class</code></a> filter hook:</h1>\n\n<p>If you don't want to go to different pages or posts in the admin panel to assign specific templates (may be you have a lot of pages / posts), then you may use the <code>post_class</code> filter hook. This way, you will be able to assign unique CSS classes to different posts and pages that needs them and style them based on those CSS classes. For example, say you have a custom post type <code>movie</code> &amp; you want different CSS class for <code>movie</code> entries. Then in your theme's <code>functions.php</code> file, you may add the following CODE:</p>\n\n<pre><code>add_filter( 'post_class', 'movie_post_class' );\nfunction movie_post_class( $class ) {\n if ( get_post_type() === 'movie' ) {\n\n // remove these CSS classes from movie entries\n $remove = array( 'css-class-to-remove', 'another-class-to-remove' );\n $class = array_diff( $class, $remove );\n\n // add these custom CSS classes to movie entries\n $add = array( 'custom-movie', 'my-movie-class' );\n $class = array_merge( $add, $class );\n }\n return $class;\n}\n</code></pre>\n\n<p>Now you can use the following CSS to target movie entires:</p>\n\n<pre><code>.custom-movie {\n background-color: gold;\n}\n</code></pre>\n\n<h1>Use <a href=\"https://developer.wordpress.org/reference/hooks/body_class/\" rel=\"nofollow noreferrer\"><code>body_class</code></a> filter hook:</h1>\n\n<p>In some situations, if you don't want to use page templates and you need more generic control over the entire page design (compared to what <code>post_class</code> will provide), then you may modify <code>&lt;body&gt;</code> class using the <code>body_class</code> filter hook (in the same way that you can do with the <code>post_class</code> filter hook). Like this:</p>\n\n<pre><code>add_filter( 'body_class', 'movie_body_class' );\nfunction movie_body_class( $class ) {\n if ( is_single() &amp;&amp; get_post_type() === 'movie' ) {\n\n // remove these CSS classes from body class\n $remove = array( 'css-class-to-remove', 'another-class-to-remove' );\n $class = array_diff( $class, $remove );\n\n // add these custom CSS classes to body class of a movie post\n $add = array( 'custom-movie', 'my-movie-class' );\n $class = array_merge( $add, $class );\n }\n return $class;\n}\n</code></pre>\n\n<p>Now you can use the following CSS to target movie custom post page:</p>\n\n<pre><code>body.custom-movie .any-inner-content-class {\n color: blue;\n}\n</code></pre>\n\n<p>Since this custom class is added in the <code>&lt;body&gt;</code>, you can target any element within the page this way.</p>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258345", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114431/" ]
First of all thanks for reading, and my apologies for my lack of knowledge. I have a WP site running with a theme and a child theme. I run it in 3 languages Spanish, English and Portuguese; and for handling the translations I'm using WPML plugin. My problem is that in the translated Portfolios and Contact page the site is not looking quite as I want. After quite a lot of research on WPML support's end the conclusion was that my devs the child-theme including additional CSS sheets that are surprisingly set to post/page specific levels. So the styling goes like in the pictures: ![CSSSheetPageLevelStyling](https://d2salfytceyqoe.cloudfront.net/wp-content/uploads/2017/02/1216707-CSSSheetPageLevelStyling.png) ![CMorePageSpecificStyling](https://d2salfytceyqoe.cloudfront.net/wp-content/uploads/2017/02/1216707-MorePageSpecificStyling.png) And the same goes for the Contacts ID posts. So in this scenario WMPL support solution is to "copy" the script and just change in the copied lines the post id. I believe this is a short term solution as if in the future any of the following happen I will have to re do it again: -I want to create a second Portfolio Page -I want to add a new language -For whatever reason I delete the portfolio or contact page and re do it it will have a new post ID So the question is: Isn't another option to achieve this in a more "clean" fashion? I wouldn't know how but I imagine something like saying in the CSS, for Portfolios the styling should be these -no matter which language-; for Contact, the styling should be these, etc My dev is saying this approach is wrong, but for me their explanations make no sense. Any advise would be deeply appreciate Cheers
You're absolutely right in your assumption. CSS should **never** be tied to post IDs, because they can always change (for example if you decide to migrate your posts to another install). You can always shift control towards the admin dashboard. Add a custom field in a post/page that you want styled in a special way (in your example you would have the same custom field in all language versions of the post/page). Let's say it will be `wpse_custom_class`. Add it to each post/page; the value will be `portfolio` for this example. Add this code to `functions.php` (copied from [this answer](https://wordpress.stackexchange.com/a/64124/8105)). When the page loads it will look for a custom field and insert its value as a CSS class on the HTML body element. ``` function wpse_filter_post_class( $classes ) { $my_post_class = get_post_meta($post->ID, "wpse_custom_class"); if( $my_post_class != '' ) { $classes[] = $my_post_class; } return $classes; } add_filter( 'post_class', 'wpse_filter_post_class' ); ``` Your designer can now use it like so: ``` .portfolio #content .main { max-width: 100%; } ``` This is more work on the admin side (you or the designer will need to manually go in and specify those CSS classes for all the custom-styled pages), but ultimately it contributes to a very flexible and future-proof solution.
258,358
<p>So i'm new at wordpress, I want to add some php code in my home page, but I don't understand why neither page.php or front-page.php seems to act as a template to my homepage</p> <p>I tried to copy front-page.php and I put</p> <pre><code>/** * Template Name: homepagetemplate **/ </code></pre> <p>edited the html and add some super-big Text to see if it works....<br> Then set the template in wordpress and no big text I see.</p> <p>Tried the same with page.php, but nothing seems to work, I even tried editing page.php and front-page.php directly and I see nothing</p> <p>If I do the same with a page that is not my homepage it works if i edit page.php, but not for my homepage </p>
[ { "answer_id": 258350, "author": "montrealist", "author_id": 8105, "author_profile": "https://wordpress.stackexchange.com/users/8105", "pm_score": 2, "selected": false, "text": "<p>You're absolutely right in your assumption. CSS should <strong>never</strong> be tied to post IDs, because they can always change (for example if you decide to migrate your posts to another install).</p>\n\n<p>You can always shift control towards the admin dashboard.</p>\n\n<p>Add a custom field in a post/page that you want styled in a special way (in your example you would have the same custom field in all language versions of the post/page). Let's say it will be <code>wpse_custom_class</code>. Add it to each post/page; the value will be <code>portfolio</code> for this example.</p>\n\n<p>Add this code to <code>functions.php</code> (copied from <a href=\"https://wordpress.stackexchange.com/a/64124/8105\">this answer</a>). When the page loads it will look for a custom field and insert its value as a CSS class on the HTML body element.</p>\n\n<pre><code>function wpse_filter_post_class( $classes ) {\n $my_post_class = get_post_meta($post-&gt;ID, \"wpse_custom_class\");\n\n if( $my_post_class != '' ) {\n $classes[] = $my_post_class;\n }\n return $classes;\n}\n\nadd_filter( 'post_class', 'wpse_filter_post_class' );\n</code></pre>\n\n<p>Your designer can now use it like so:</p>\n\n<pre><code>.portfolio #content .main {\n max-width: 100%;\n}\n</code></pre>\n\n<p>This is more work on the admin side (you or the designer will need to manually go in and specify those CSS classes for all the custom-styled pages), but ultimately it contributes to a very flexible and future-proof solution.</p>\n" }, { "answer_id": 258351, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 1, "selected": false, "text": "<h1>Why not to use ID specific CSS rules:</h1>\n\n<p>Post ID specific CSS can only be a quick fix and it's far from the best practice. Post ID is not reliable in many cases. For example:</p>\n\n<ul>\n<li><p>May be you'll delete a post and replace that with a new post.</p></li>\n<li><p>May be you'll need to migrate your site in the future to another server.</p></li>\n<li><p>May be you are creating a newer version of the post / page and want to review the new post / page before replacing the old one.</p></li>\n</ul>\n\n<p>In all these cases, post ID is likely to change and those ID specific CSS will not be even applicable any more. So you'll have to update your CSS again to match your design needs. WordPress is extremely customizable, so there is no scenario where you have to use post ID base CSS rules. For a more mature development and design practice, using ID specific CSS rules are highly discouraged. Instead, use one of the options below:</p>\n\n<h1>Use Page Templates:</h1>\n\n<p>WordPress supports <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=\"nofollow noreferrer\">page templates</a> for pages for a long time and from version <code>4.7</code> WordPress supports <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/#creating-page-templates-for-specific-post-types\" rel=\"nofollow noreferrer\">page templates for any post type</a>. So if you you have WordPress <code>4.7</code> or later, then you may create specific page template for any posts or pages in your child theme.</p>\n\n<p>This way you don't need any ID specific CSS at all, because once you have those specific templates, whenever you'll need the same design for any page or post, you'll simply have to choose the same template from the post or page editor. That's all. After that, design of that page template will apply to that <code>page</code>, <code>post</code> or <code>custom post type</code>.</p>\n\n<h1>Use <a href=\"https://developer.wordpress.org/reference/hooks/post_class/\" rel=\"nofollow noreferrer\"><code>post_class</code></a> filter hook:</h1>\n\n<p>If you don't want to go to different pages or posts in the admin panel to assign specific templates (may be you have a lot of pages / posts), then you may use the <code>post_class</code> filter hook. This way, you will be able to assign unique CSS classes to different posts and pages that needs them and style them based on those CSS classes. For example, say you have a custom post type <code>movie</code> &amp; you want different CSS class for <code>movie</code> entries. Then in your theme's <code>functions.php</code> file, you may add the following CODE:</p>\n\n<pre><code>add_filter( 'post_class', 'movie_post_class' );\nfunction movie_post_class( $class ) {\n if ( get_post_type() === 'movie' ) {\n\n // remove these CSS classes from movie entries\n $remove = array( 'css-class-to-remove', 'another-class-to-remove' );\n $class = array_diff( $class, $remove );\n\n // add these custom CSS classes to movie entries\n $add = array( 'custom-movie', 'my-movie-class' );\n $class = array_merge( $add, $class );\n }\n return $class;\n}\n</code></pre>\n\n<p>Now you can use the following CSS to target movie entires:</p>\n\n<pre><code>.custom-movie {\n background-color: gold;\n}\n</code></pre>\n\n<h1>Use <a href=\"https://developer.wordpress.org/reference/hooks/body_class/\" rel=\"nofollow noreferrer\"><code>body_class</code></a> filter hook:</h1>\n\n<p>In some situations, if you don't want to use page templates and you need more generic control over the entire page design (compared to what <code>post_class</code> will provide), then you may modify <code>&lt;body&gt;</code> class using the <code>body_class</code> filter hook (in the same way that you can do with the <code>post_class</code> filter hook). Like this:</p>\n\n<pre><code>add_filter( 'body_class', 'movie_body_class' );\nfunction movie_body_class( $class ) {\n if ( is_single() &amp;&amp; get_post_type() === 'movie' ) {\n\n // remove these CSS classes from body class\n $remove = array( 'css-class-to-remove', 'another-class-to-remove' );\n $class = array_diff( $class, $remove );\n\n // add these custom CSS classes to body class of a movie post\n $add = array( 'custom-movie', 'my-movie-class' );\n $class = array_merge( $add, $class );\n }\n return $class;\n}\n</code></pre>\n\n<p>Now you can use the following CSS to target movie custom post page:</p>\n\n<pre><code>body.custom-movie .any-inner-content-class {\n color: blue;\n}\n</code></pre>\n\n<p>Since this custom class is added in the <code>&lt;body&gt;</code>, you can target any element within the page this way.</p>\n" } ]
2017/02/28
[ "https://wordpress.stackexchange.com/questions/258358", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114425/" ]
So i'm new at wordpress, I want to add some php code in my home page, but I don't understand why neither page.php or front-page.php seems to act as a template to my homepage I tried to copy front-page.php and I put ``` /** * Template Name: homepagetemplate **/ ``` edited the html and add some super-big Text to see if it works.... Then set the template in wordpress and no big text I see. Tried the same with page.php, but nothing seems to work, I even tried editing page.php and front-page.php directly and I see nothing If I do the same with a page that is not my homepage it works if i edit page.php, but not for my homepage
You're absolutely right in your assumption. CSS should **never** be tied to post IDs, because they can always change (for example if you decide to migrate your posts to another install). You can always shift control towards the admin dashboard. Add a custom field in a post/page that you want styled in a special way (in your example you would have the same custom field in all language versions of the post/page). Let's say it will be `wpse_custom_class`. Add it to each post/page; the value will be `portfolio` for this example. Add this code to `functions.php` (copied from [this answer](https://wordpress.stackexchange.com/a/64124/8105)). When the page loads it will look for a custom field and insert its value as a CSS class on the HTML body element. ``` function wpse_filter_post_class( $classes ) { $my_post_class = get_post_meta($post->ID, "wpse_custom_class"); if( $my_post_class != '' ) { $classes[] = $my_post_class; } return $classes; } add_filter( 'post_class', 'wpse_filter_post_class' ); ``` Your designer can now use it like so: ``` .portfolio #content .main { max-width: 100%; } ``` This is more work on the admin side (you or the designer will need to manually go in and specify those CSS classes for all the custom-styled pages), but ultimately it contributes to a very flexible and future-proof solution.
258,362
<p>Variations of this question have been asked, however the scenarios do not match mine and despite my efforts I have not been able to adopt the previous answers to a working solution in my use case.</p> <p>I have a page template that has a javascript application built into it. This application uses the last parameter in a URL as a parameter for an ajax request, which it runs and then produces results for.</p> <p>Due to SEO concerns and client requirement, I cannot change or alter the way this request syntax functions, so I must make it work in Wordpress (page is being converted from a Ruby application)</p> <p>When the client makes a request to:</p> <pre><code>https://www.wordpresssite.com/service/testing-tool/domain.com </code></pre> <p>I need to respond with the page that is built using the template at:</p> <pre><code>https://www.wordpresssite.com/service/results </code></pre> <p>This part I have working with the following rewrite rule in <code>.htaccess</code> </p> <pre><code>RewriteRule ^service/testing-tool/([a-z0-9.]+)$ /index.php?pagename=service/results [NC,L] </code></pre> <p>The rewrite works, however WordPress changes the URL in the browser to</p> <pre><code>https://www.wordpresssite.com/service/results </code></pre> <p>This causes the JS to fail as the domain parameter is missing, and it also doesn't meet the requirements previously mentioned.</p> <p>I though after doing some research here that the issue is the redirect_canonical() action, so I tried removing it from within the template:</p> <pre><code>// Disable redirect_canonical() add_action( 'init', 'results_tweaks' ); function results_tweaks() { remove_action( 'template_redirect', 'redirect_canonical' ); } </code></pre> <p>However this doesn't seem to do it. Reading the WP documentation, I suspect this is because the action is already processed by the time the page loads.</p> <p>Is there another way I can override this action specifically for this template, and no others? Perhaps another way aside from removing the action?</p>
[ { "answer_id": 258369, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 0, "selected": false, "text": "<p>You might be able to solve your problem just by changing your rewrite rule to:</p>\n\n<p><code>RewriteRule ^service/testing-tool/([a-z0-9.]+)/?$ /index.php?pagename=service/results&amp;domain=$1 [NC,L]</code></p>\n\n<p>Now, from within <a href=\"https://www.wordpresssite.com/service/results\" rel=\"nofollow noreferrer\">https://www.wordpresssite.com/service/results</a> you can get the domain via PHP.</p>\n\n<p>Note that I added '/?' to your rule, otherwise it shouldn't work.</p>\n\n<p>Using php you'd get the domain (missing param) using <code>$_GET['domain']</code>.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 258379, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p>You can use an internal rewrite instead of .htaccess:</p>\n\n<pre><code>function wpd_service_rewrite() {\n add_rewrite_rule(\n '^service/testing-tool/([a-z0-9.]+)$',\n 'index.php?pagename=service/results',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_service_rewrite' );\n</code></pre>\n\n<p>Don't forget to <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow noreferrer\">flush rewrite rules</a> after adding / changing them.</p>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258362", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97943/" ]
Variations of this question have been asked, however the scenarios do not match mine and despite my efforts I have not been able to adopt the previous answers to a working solution in my use case. I have a page template that has a javascript application built into it. This application uses the last parameter in a URL as a parameter for an ajax request, which it runs and then produces results for. Due to SEO concerns and client requirement, I cannot change or alter the way this request syntax functions, so I must make it work in Wordpress (page is being converted from a Ruby application) When the client makes a request to: ``` https://www.wordpresssite.com/service/testing-tool/domain.com ``` I need to respond with the page that is built using the template at: ``` https://www.wordpresssite.com/service/results ``` This part I have working with the following rewrite rule in `.htaccess` ``` RewriteRule ^service/testing-tool/([a-z0-9.]+)$ /index.php?pagename=service/results [NC,L] ``` The rewrite works, however WordPress changes the URL in the browser to ``` https://www.wordpresssite.com/service/results ``` This causes the JS to fail as the domain parameter is missing, and it also doesn't meet the requirements previously mentioned. I though after doing some research here that the issue is the redirect\_canonical() action, so I tried removing it from within the template: ``` // Disable redirect_canonical() add_action( 'init', 'results_tweaks' ); function results_tweaks() { remove_action( 'template_redirect', 'redirect_canonical' ); } ``` However this doesn't seem to do it. Reading the WP documentation, I suspect this is because the action is already processed by the time the page loads. Is there another way I can override this action specifically for this template, and no others? Perhaps another way aside from removing the action?
You can use an internal rewrite instead of .htaccess: ``` function wpd_service_rewrite() { add_rewrite_rule( '^service/testing-tool/([a-z0-9.]+)$', 'index.php?pagename=service/results', 'top' ); } add_action( 'init', 'wpd_service_rewrite' ); ``` Don't forget to [flush rewrite rules](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules) after adding / changing them.
258,364
<p>I am in the process of putting together my own WordPress Theme. Up until now, I have been using the 'single.php' file to act as a Template for both my Blogs and Media Files. In reference to my Media files, I have been using the <code>&lt;?php the_content(); ?&gt;</code> tag to call such images. </p> <p>I have now reached the stage, where I have created an 'attachment.php' file for the various Media files. I have noticed that the <code>&lt;?php the_content(); ?&gt;</code> does not work in said file, unlike in the 'single.php' file. </p> <p>What is the relevant alternative to <code>&lt;?php the_content(); ?&gt;</code> when it comes to calling images in the 'attachment.php' file?</p>
[ { "answer_id": 258369, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 0, "selected": false, "text": "<p>You might be able to solve your problem just by changing your rewrite rule to:</p>\n\n<p><code>RewriteRule ^service/testing-tool/([a-z0-9.]+)/?$ /index.php?pagename=service/results&amp;domain=$1 [NC,L]</code></p>\n\n<p>Now, from within <a href=\"https://www.wordpresssite.com/service/results\" rel=\"nofollow noreferrer\">https://www.wordpresssite.com/service/results</a> you can get the domain via PHP.</p>\n\n<p>Note that I added '/?' to your rule, otherwise it shouldn't work.</p>\n\n<p>Using php you'd get the domain (missing param) using <code>$_GET['domain']</code>.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 258379, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p>You can use an internal rewrite instead of .htaccess:</p>\n\n<pre><code>function wpd_service_rewrite() {\n add_rewrite_rule(\n '^service/testing-tool/([a-z0-9.]+)$',\n 'index.php?pagename=service/results',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_service_rewrite' );\n</code></pre>\n\n<p>Don't forget to <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow noreferrer\">flush rewrite rules</a> after adding / changing them.</p>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258364", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112472/" ]
I am in the process of putting together my own WordPress Theme. Up until now, I have been using the 'single.php' file to act as a Template for both my Blogs and Media Files. In reference to my Media files, I have been using the `<?php the_content(); ?>` tag to call such images. I have now reached the stage, where I have created an 'attachment.php' file for the various Media files. I have noticed that the `<?php the_content(); ?>` does not work in said file, unlike in the 'single.php' file. What is the relevant alternative to `<?php the_content(); ?>` when it comes to calling images in the 'attachment.php' file?
You can use an internal rewrite instead of .htaccess: ``` function wpd_service_rewrite() { add_rewrite_rule( '^service/testing-tool/([a-z0-9.]+)$', 'index.php?pagename=service/results', 'top' ); } add_action( 'init', 'wpd_service_rewrite' ); ``` Don't forget to [flush rewrite rules](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules) after adding / changing them.
258,401
<p>I have registered a sidebar with the following code :</p> <pre><code>function reg_l_sid(){ $args = array( 'name' =&gt; __( 'left-sidebar', 'Tutorial-Blog' ), 'id' =&gt; 'left-sidebar', 'description' =&gt; '', 'class' =&gt; '', 'before_widget' =&gt; '&lt;li id="%1$s" class="widget %2$s"&gt;', 'after_widget' =&gt; '&lt;/li&gt;', 'before_title' =&gt; '&lt;h2 class="widgettitle"&gt;', 'after_title' =&gt; '&lt;/h2&gt;' ); register_sidebar( $args ); } add_action ('widgets_init','reg_l_sid'); </code></pre> <p>and the sidebar is registered, then i added some widgets. then i tried to use the conditional <code>is_active_sidebar</code> to display a message if there are no widgets like this :</p> <pre><code>if ( is_active_sidebar( 'left-sidebar' ) ) { dynamic_sidebar( 'left-sidebar' ); } else { echo 'Please add widgets'; } </code></pre> <p>but it keeps showing the message "Please add widgets", while as i mentioned that there are widgets have been added. So where is the problem? </p> <blockquote> <p>Update</p> </blockquote> <p>To be mentioned that it works fine without the conditional.</p>
[ { "answer_id": 258402, "author": "Sonali", "author_id": 84167, "author_profile": "https://wordpress.stackexchange.com/users/84167", "pm_score": 3, "selected": true, "text": "<p>Please try this one,because without id we i don't think that will work:</p>\n\n<pre><code> function reg_l_sid()\n {\n $args = array( 'id' =&gt; 'sidebar-footer-6','name'=&gt; 'Left-sidebar');\n register_sidebar($args);\n }\n add_action('widgets_init', 'reg_l_sid');\n</code></pre>\n\n<p>and inside template:</p>\n\n<pre><code> if (is_active_sidebar('sidebar-footer-6')) {\n dynamic_sidebar('sidebar-footer-6');\n } else {\n echo 'Please add widgets';\n }\n</code></pre>\n" }, { "answer_id": 258411, "author": "Mohamed Omar", "author_id": 102224, "author_profile": "https://wordpress.stackexchange.com/users/102224", "pm_score": 1, "selected": false, "text": "<p>Actually the problem has been solved but i don't know why this happened.. so after using the default WordPress function every thing worked fine, then i manged to delete the args i don't need ,returning back to using only the name argument ...and this was the starting point for me.. after checking every thing worked .. so my be it was a syntax problem but finally no problem with using the <code>name</code> argument only. Now i have this and it works just fine :</p>\n\n<pre><code>function reg_l_sid(){\n $args = array('name'=&gt; __( 'Left-sidebar', 'Tutorial-Blog' ));\n register_sidebar( $args );\n}\nadd_action ('widgets_init','reg_l_sid')\n</code></pre>\n\n<p>In sidebar :</p>\n\n<pre><code>if ( is_active_sidebar( 'Left-sidebar' ) ) {\n dynamic_sidebar( 'Left-sidebar' );\n} else {\n echo 'Please add widgets';\n}\n</code></pre>\n" }, { "answer_id": 258420, "author": "lalitpendhare", "author_id": 114472, "author_profile": "https://wordpress.stackexchange.com/users/114472", "pm_score": 0, "selected": false, "text": "<p>I have just put your code in my function file and also create a template to test your code. for me, it's working fine. Please re-evaluate your things, it might be working.</p>\n\n<pre><code>add_action( 'widgets_init', 'twentyseventeen_widgets_init' );\nfunction reg_l_sid(){\n $args = array(\n 'name' =&gt; __( 'left-sidebar', 'Tutorial-Blog' ),\n 'id' =&gt; 'left-sidebar',\n 'description' =&gt; '',\n 'class' =&gt; '',\n 'before_widget' =&gt; '&lt;li id=\"%1$s\" class=\"widget %2$s\"&gt;',\n 'after_widget' =&gt; '&lt;/li&gt;',\n 'before_title' =&gt; '&lt;h2 class=\"widgettitle\"&gt;',\n 'after_title' =&gt; '&lt;/h2&gt;' );\n\nregister_sidebar( $args );\n}\n\nadd_action ('widgets_init','reg_l_sid');\n\nif ( is_active_sidebar( 'left-sidebar' ) ) {\n dynamic_sidebar( 'left-sidebar' );\n} else {\n echo 'Please add widgets';\n}\n</code></pre>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258401", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102224/" ]
I have registered a sidebar with the following code : ``` function reg_l_sid(){ $args = array( 'name' => __( 'left-sidebar', 'Tutorial-Blog' ), 'id' => 'left-sidebar', 'description' => '', 'class' => '', 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>' ); register_sidebar( $args ); } add_action ('widgets_init','reg_l_sid'); ``` and the sidebar is registered, then i added some widgets. then i tried to use the conditional `is_active_sidebar` to display a message if there are no widgets like this : ``` if ( is_active_sidebar( 'left-sidebar' ) ) { dynamic_sidebar( 'left-sidebar' ); } else { echo 'Please add widgets'; } ``` but it keeps showing the message "Please add widgets", while as i mentioned that there are widgets have been added. So where is the problem? > > Update > > > To be mentioned that it works fine without the conditional.
Please try this one,because without id we i don't think that will work: ``` function reg_l_sid() { $args = array( 'id' => 'sidebar-footer-6','name'=> 'Left-sidebar'); register_sidebar($args); } add_action('widgets_init', 'reg_l_sid'); ``` and inside template: ``` if (is_active_sidebar('sidebar-footer-6')) { dynamic_sidebar('sidebar-footer-6'); } else { echo 'Please add widgets'; } ```
258,434
<p>Currently i am using this code to output menu display :</p> <pre><code>&lt;?php wp_nav_menu(array( 'theme_location' =&gt; 'songs-category', 'container' =&gt; false, 'menu_id' =&gt; 'nav', 'menu_class' =&gt; '', 'items_wrap' =&gt; '&lt;ul id="nav"&gt;&lt;li class="active"&gt;&lt;a href="#" data-slug="4,5,6,7,8,9" class="xyz"&gt;All&lt;/a&gt;&lt;/li&gt;%3$s&lt;/ul&gt;' )); </code></pre> <p>getting output:</p> <pre><code>&lt;ul id="nav"&gt; &lt;li class="active"&gt;&lt;a href="http://domain.com/" title="All"&gt;All&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category1/"&gt;category1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category2/"&gt;category2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category3/"&gt;category3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category4/"&gt;category4&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category5/"&gt;category5&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category6/"&gt;category6&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category7/"&gt;category7&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category8/"&gt;category8&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://domain.com/category/category9/"&gt;category9&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>but need output like this :</p> <pre><code>&lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="#" data-slug="4,5,6,7,8,9,10,11,12,13,14,15" class="xyz"&gt;All&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="10" class="xyz"&gt;category1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="12" class="xyz"&gt;category2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="15" class="xyz"&gt;category3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="9" class="xyz"&gt;category4&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="4" class="xyz"&gt;category5&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="11" class="xyz"&gt;category6&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="13" class="xyz"&gt;category7&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="8" class="xyz"&gt;category8&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-slug="7" class="xyz"&gt;category9&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I don't know how to achieve this.</p>
[ { "answer_id": 258440, "author": "ajie", "author_id": 114369, "author_profile": "https://wordpress.stackexchange.com/users/114369", "pm_score": 2, "selected": false, "text": "<p>You will have to use a custom Walker for your menu. Here is the page in the codex that explains it: </p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/Walker</a></p>\n\n<p>and here:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/walker_nav_menu/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/walker_nav_menu/</a></p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 376900, "author": "gtamborero", "author_id": 52236, "author_profile": "https://wordpress.stackexchange.com/users/52236", "pm_score": 1, "selected": false, "text": "<p>You can do a walker or you can do a custom output getting only what you need using the nav_menu_items function:</p>\n<pre><code>// Get wordpress menu and do a custom output\n$getMenu = wp_get_nav_menu_items( 'menu1'); // Where menu1 can be ID, slug or title\nforeach($getMenu as $item){\n echo '&lt;li&gt;&lt;a href=&quot;' . $item-&gt;url . '&quot;&gt;' . $item-&gt;title . '&lt;/a&gt;&lt;/li&gt;';\n}\n</code></pre>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258434", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114481/" ]
Currently i am using this code to output menu display : ``` <?php wp_nav_menu(array( 'theme_location' => 'songs-category', 'container' => false, 'menu_id' => 'nav', 'menu_class' => '', 'items_wrap' => '<ul id="nav"><li class="active"><a href="#" data-slug="4,5,6,7,8,9" class="xyz">All</a></li>%3$s</ul>' )); ``` getting output: ``` <ul id="nav"> <li class="active"><a href="http://domain.com/" title="All">All</a></li> <li><a href="http://domain.com/category/category1/">category1</a></li> <li><a href="http://domain.com/category/category2/">category2</a></li> <li><a href="http://domain.com/category/category3/">category3</a></li> <li><a href="http://domain.com/category/category4/">category4</a></li> <li><a href="http://domain.com/category/category5/">category5</a></li> <li><a href="http://domain.com/category/category6/">category6</a></li> <li><a href="http://domain.com/category/category7/">category7</a></li> <li><a href="http://domain.com/category/category8/">category8</a></li> <li><a href="http://domain.com/category/category9/">category9</a></li> </ul> ``` but need output like this : ``` <ul id="nav"> <li><a href="#" data-slug="4,5,6,7,8,9,10,11,12,13,14,15" class="xyz">All</a></li> <li><a href="#" data-slug="10" class="xyz">category1</a></li> <li><a href="#" data-slug="12" class="xyz">category2</a></li> <li><a href="#" data-slug="15" class="xyz">category3</a></li> <li><a href="#" data-slug="9" class="xyz">category4</a></li> <li><a href="#" data-slug="4" class="xyz">category5</a></li> <li><a href="#" data-slug="11" class="xyz">category6</a></li> <li><a href="#" data-slug="13" class="xyz">category7</a></li> <li><a href="#" data-slug="8" class="xyz">category8</a></li> <li><a href="#" data-slug="7" class="xyz">category9</a></li> </ul> ``` I don't know how to achieve this.
You will have to use a custom Walker for your menu. Here is the page in the codex that explains it: <https://codex.wordpress.org/Class_Reference/Walker> and here: <https://developer.wordpress.org/reference/classes/walker_nav_menu/> Hope that helps.
258,437
<p>I am trying to automate the change in order status from "on-hold" to "pending payment" once a product vendor has marked an order as fulfilled. Currently, the default status in "on-hold" when an order is created and only once the product is delivered must payment be required. Is it possible to update to the "pending" status after an action has been made? </p>
[ { "answer_id": 258443, "author": "Sonali", "author_id": 84167, "author_profile": "https://wordpress.stackexchange.com/users/84167", "pm_score": -1, "selected": false, "text": "<p>Yes you just add see when you want to change status and add inside this function.</p>\n\n<pre><code> add_action('woocommerce_order_status_changed','status_changed_processsing');\n function status_changed_processsing( $order_id, $checkout = null ) {\n global $woocommerce;\n $order = new WC_Order( $order_id );\n if(your condition goes here){\n\n //assign statu to that order\n $order-&gt;status = 'pending';\n }\n }\n</code></pre>\n" }, { "answer_id": 272115, "author": "BugDecode", "author_id": 121752, "author_profile": "https://wordpress.stackexchange.com/users/121752", "pm_score": 1, "selected": false, "text": "<p>If you ever need to change the order status from php here is how to do it.</p>\n\n<pre><code>$order = new WC_Order($order_id);\n\nif (!empty($order)) {\n $order-&gt;update_status( 'completed' );\n}\n</code></pre>\n\n<p>Possible values: processing, on-hold, cancelled, completed</p>\n\n<p>This is from woocommerce/includes/abstracts/abstract-wc-order.php</p>\n" }, { "answer_id": 304691, "author": "Ivan K. Serensen", "author_id": 144430, "author_profile": "https://wordpress.stackexchange.com/users/144430", "pm_score": 0, "selected": false, "text": "<p>a little late, but still hard to find...</p>\n\n<p><strong>Possible values</strong></p>\n\n<p>Based on <a href=\"https://www.bozzmedia.com/posts/get-know-woocommerce-status-definitions/\" rel=\"nofollow noreferrer\">https://www.bozzmedia.com/posts/get-know-woocommerce-status-definitions/</a></p>\n\n<p>\"<strong>processing, on-hold, cancelled, completed, pending, failed, refunded</strong>\"</p>\n\n<p>and that is supported in the WooCommerce Order class.. <br>\n/woocommerce/includes/class-wc-order.php <em>- Around lines 108 or so.</em></p>\n\n<p>Assuming that you do not use a plugin capable of adding more.</p>\n" }, { "answer_id": 396423, "author": "Bernard Van Isacker", "author_id": 213177, "author_profile": "https://wordpress.stackexchange.com/users/213177", "pm_score": 0, "selected": false, "text": "<p>This will work:</p>\n<pre><code>add_filter( 'woocommerce_bacs_process_payment_order_status', function( $status = 'on_hold', $order = null ) {\nreturn 'pending';\n}, 10, 2 );\n</code></pre>\n<p>BUT if you use it, the status change could cause emails not being sent after an order comes in since it goes too quickly from 'on hold' to pending, and woocommerce does not send mails in 'pending'. I tried this, and after a few days mails were no longer sent out although it initially worked.</p>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258437", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114482/" ]
I am trying to automate the change in order status from "on-hold" to "pending payment" once a product vendor has marked an order as fulfilled. Currently, the default status in "on-hold" when an order is created and only once the product is delivered must payment be required. Is it possible to update to the "pending" status after an action has been made?
If you ever need to change the order status from php here is how to do it. ``` $order = new WC_Order($order_id); if (!empty($order)) { $order->update_status( 'completed' ); } ``` Possible values: processing, on-hold, cancelled, completed This is from woocommerce/includes/abstracts/abstract-wc-order.php
258,457
<p>I have a custom post type and using this function to add for posts, previous and next buttons. </p> <p>The problem is that within the custom post type, I have subcategories defined by a custom field <code>category</code>. </p> <p>Is there a way to limit the previous and next post link for items only within the same category of the current post?</p> <pre><code> function crunchify_post_navigation(){ ?&gt; &lt;div class="arrowNav"&gt; &lt;div class="arrowLeft"&gt; &lt;?php previous_post_link('%link', '&amp;#8606;', FALSE); ?&gt; &lt;/div&gt; &lt;div class="arrowRight"&gt; &lt;?php next_post_link('%link', '&amp;#8608;', FALSE); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } add_action('wp_footer', 'crunchify_post_navigation'); </code></pre>
[ { "answer_id": 258468, "author": "TrubinE", "author_id": 111011, "author_profile": "https://wordpress.stackexchange.com/users/111011", "pm_score": 0, "selected": false, "text": "<p>This function must be used within the loop.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/next_post_link\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/next_post_link</a></p>\n" }, { "answer_id": 358774, "author": "TomC", "author_id": 36980, "author_profile": "https://wordpress.stackexchange.com/users/36980", "pm_score": 1, "selected": false, "text": "<p>You want to change the <code>in_same_term</code> value to TRUE as follows:</p>\n\n<pre><code> function crunchify_post_navigation(){\n ?&gt;\n &lt;div class=\"arrowNav\"&gt;\n &lt;div class=\"arrowLeft\"&gt;\n &lt;?php previous_post_link('%link', '&amp;#8606;', TRUE); ?&gt;\n &lt;/div&gt;\n &lt;div class=\"arrowRight\"&gt;\n &lt;?php next_post_link('%link', '&amp;#8608;', TRUE); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n }\n\n add_action('wp_footer', 'crunchify_post_navigation');\n</code></pre>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258457", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
I have a custom post type and using this function to add for posts, previous and next buttons. The problem is that within the custom post type, I have subcategories defined by a custom field `category`. Is there a way to limit the previous and next post link for items only within the same category of the current post? ``` function crunchify_post_navigation(){ ?> <div class="arrowNav"> <div class="arrowLeft"> <?php previous_post_link('%link', '&#8606;', FALSE); ?> </div> <div class="arrowRight"> <?php next_post_link('%link', '&#8608;', FALSE); ?> </div> </div> <?php } add_action('wp_footer', 'crunchify_post_navigation'); ```
You want to change the `in_same_term` value to TRUE as follows: ``` function crunchify_post_navigation(){ ?> <div class="arrowNav"> <div class="arrowLeft"> <?php previous_post_link('%link', '&#8606;', TRUE); ?> </div> <div class="arrowRight"> <?php next_post_link('%link', '&#8608;', TRUE); ?> </div> </div> <?php } add_action('wp_footer', 'crunchify_post_navigation'); ```
258,482
<p>I'm trying, without success, to disable pagination only in a specific category (where I'm showing all the posts of that category listed by years). Someone can help me? Thanks.</p>
[ { "answer_id": 258483, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 2, "selected": false, "text": "<p>You can try this, replacing <code>my_cat</code> with your category slug. This will modify the main query just before rendering the loop on the archive page of your category.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_disable_pagination' );\nfunction wpse_disable_pagination( $query ) {\n\n if( is_category( 'my_cat' ) {\n query-&gt;set( 'posts_per_page', '-1' );\n }\n\n}\n</code></pre>\n" }, { "answer_id": 258552, "author": "ArDiEm", "author_id": 113631, "author_profile": "https://wordpress.stackexchange.com/users/113631", "pm_score": 1, "selected": false, "text": "<p>@bynicolas thanks! One shot, one kill :)</p>\n\n<p>This is the modified sintax of your snippet that worked for me:</p>\n\n<pre>\nadd_action( 'pre_get_posts', 'wpse_disable_pagination' );\nfunction wpse_disable_pagination( $query )\n{\n if ( is_category( 'newsletter' ) )\n $query->set( 'posts_per_page', '-1' );\n}\n</pre>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258482", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113631/" ]
I'm trying, without success, to disable pagination only in a specific category (where I'm showing all the posts of that category listed by years). Someone can help me? Thanks.
You can try this, replacing `my_cat` with your category slug. This will modify the main query just before rendering the loop on the archive page of your category. ``` add_action( 'pre_get_posts', 'wpse_disable_pagination' ); function wpse_disable_pagination( $query ) { if( is_category( 'my_cat' ) { query->set( 'posts_per_page', '-1' ); } } ```
258,491
<p>I've created custom post types in a theme before (actually on the exact theme I'm having trouble with now), and everything has gone relatively seamlessly. However, now I've run into an issue where a post type that I'm trying to create, with archive and content php files, is not working. More specifically, the slug is not working.</p> <pre><code>function sop_posttype() { register_post_type( 'sop', array( 'labels' =&gt; array( 'name' =&gt; __( 'SOPs' ), 'singular_name' =&gt; __( 'SOP' ) ), 'slug' =&gt; 'sop', 'menu_icon' =&gt; 'dashicons-editor-help', 'public' =&gt; true, 'has_archive' =&gt; true, 'supports' =&gt; [ 'title', 'editor', 'thumbnail' ] ) ); } add_action( 'init', 'sop_posttype' ); </code></pre> <p>Above is my registration for the post type. It is almost exactly the same as my previous post type, only with a different name.</p> <p>My archive file is called archive-sop.php, and my content file is called content-sop.php.</p> <p>I can't seem to see anything missing in my registration code, and the other post types are working correctly, but for some reason I'm still getting a 404 when I try to visit the archive page (<a href="http://url.com/sop/" rel="nofollow noreferrer">http://url.com/sop/</a>), even though I've added a test post.</p>
[ { "answer_id": 258483, "author": "bynicolas", "author_id": 99217, "author_profile": "https://wordpress.stackexchange.com/users/99217", "pm_score": 2, "selected": false, "text": "<p>You can try this, replacing <code>my_cat</code> with your category slug. This will modify the main query just before rendering the loop on the archive page of your category.</p>\n\n<pre><code>add_action( 'pre_get_posts', 'wpse_disable_pagination' );\nfunction wpse_disable_pagination( $query ) {\n\n if( is_category( 'my_cat' ) {\n query-&gt;set( 'posts_per_page', '-1' );\n }\n\n}\n</code></pre>\n" }, { "answer_id": 258552, "author": "ArDiEm", "author_id": 113631, "author_profile": "https://wordpress.stackexchange.com/users/113631", "pm_score": 1, "selected": false, "text": "<p>@bynicolas thanks! One shot, one kill :)</p>\n\n<p>This is the modified sintax of your snippet that worked for me:</p>\n\n<pre>\nadd_action( 'pre_get_posts', 'wpse_disable_pagination' );\nfunction wpse_disable_pagination( $query )\n{\n if ( is_category( 'newsletter' ) )\n $query->set( 'posts_per_page', '-1' );\n}\n</pre>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100731/" ]
I've created custom post types in a theme before (actually on the exact theme I'm having trouble with now), and everything has gone relatively seamlessly. However, now I've run into an issue where a post type that I'm trying to create, with archive and content php files, is not working. More specifically, the slug is not working. ``` function sop_posttype() { register_post_type( 'sop', array( 'labels' => array( 'name' => __( 'SOPs' ), 'singular_name' => __( 'SOP' ) ), 'slug' => 'sop', 'menu_icon' => 'dashicons-editor-help', 'public' => true, 'has_archive' => true, 'supports' => [ 'title', 'editor', 'thumbnail' ] ) ); } add_action( 'init', 'sop_posttype' ); ``` Above is my registration for the post type. It is almost exactly the same as my previous post type, only with a different name. My archive file is called archive-sop.php, and my content file is called content-sop.php. I can't seem to see anything missing in my registration code, and the other post types are working correctly, but for some reason I'm still getting a 404 when I try to visit the archive page (<http://url.com/sop/>), even though I've added a test post.
You can try this, replacing `my_cat` with your category slug. This will modify the main query just before rendering the loop on the archive page of your category. ``` add_action( 'pre_get_posts', 'wpse_disable_pagination' ); function wpse_disable_pagination( $query ) { if( is_category( 'my_cat' ) { query->set( 'posts_per_page', '-1' ); } } ```
258,506
<p>I have set up the following:</p> <pre><code>add_image_size( 'featured-image', 1600, 450, true ); </code></pre> <p>which is used to serve a full width image on the website I'm building, but, as you can imagine, for mobile this is re-scaled to a ridiculously small height and looks really odd on mobile.</p> <p>I have created a new image size which I've named <code>'featured-image-mobile'</code> and has the dimensions <em>650px</em> by <em>448px</em>.</p> <p>On the actual page I am displaying the full width image like so:</p> <pre><code>&lt;img src="&lt;?php the_post_thumbnail_url( 'featured-image' )?&gt;" alt="&lt;?php echo $altTag; ?&gt;" title="&lt;?php echo $titleTag; ?&gt;"&gt; </code></pre> <p>Is there a way I can keep</p> <pre><code>the_post_thumbnail_url( 'featured-image' ); </code></pre> <p>for everything except a screen resolution of <em>650px</em>, and then change the image size to the following?</p> <pre><code>the_post_thumbnail_url( 'featured-image-mobile' ); </code></pre>
[ { "answer_id": 258530, "author": "Fernando Baltazar", "author_id": 10218, "author_profile": "https://wordpress.stackexchange.com/users/10218", "pm_score": -1, "selected": false, "text": "<p>You need to do a conditional (if) to change or select the part for big devices or mobile, if you want to set different images.</p>\n\n<pre><code>function isMobile() {\n return preg_match(\"/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\\.browser|up\\.link|webos|wos)/i\", $_SERVER[\"HTTP_USER_AGENT\"]);\n}\n\n// Use the function\n if(isMobile()){\n // Do something for only mobile users\n the_post_thumbnail_url( 'featured-image-mobile' );\n }\n else {\n // Do something for only desktop users\n the_post_thumbnail_url( 'featured-image' );\n }\n</code></pre>\n\n<p>There are more examples here <a href=\"https://stackoverflow.com/questions/4117555/simplest-way-to-detect-a-mobile-device\">https://stackoverflow.com/questions/4117555/simplest-way-to-detect-a-mobile-device</a></p>\n" }, { "answer_id": 258546, "author": "Svartbaard", "author_id": 112928, "author_profile": "https://wordpress.stackexchange.com/users/112928", "pm_score": 0, "selected": false, "text": "<p>You could output both images and just switch between the two using css (I am just using basic bootstrap classes here and omitting unnecessary markup for clarity sake):</p>\n\n<pre><code>&lt;div class=\"featured-image hidden-xs\"&gt;\n &lt;img src=\"&lt;?php the_post_thumbnail_url( 'featured-image' )?&gt;\"&gt;\n&lt;/div&gt;\n\n&lt;div class=\"featured-image-mobile visible-xs-block\"&gt;\n &lt;img src=\"&lt;?php the_post_thumbnail_url( 'featured-image-mobile' )?&gt;\"&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Alternatively, you could add the mobile version of the image as a custom attribute:</p>\n\n<pre><code>&lt;img src=\"&lt;?php the_post_thumbnail_url( 'featured-image' )?&gt;\" data-mob-src=\"&lt;?php the_post_thumbnail_url( 'featured-image-mobile' )?&gt;\"&gt;\n</code></pre>\n\n<p>And subsequently switch the source of the image with Javascript on mobile.</p>\n" }, { "answer_id": 258578, "author": "Elex", "author_id": 113687, "author_profile": "https://wordpress.stackexchange.com/users/113687", "pm_score": 2, "selected": false, "text": "<p>WordPress <code>wp_is_mobile()</code> can be the function that you're looking for.</p>\n\n<pre><code>// Use the build-in function if WP\nif(wp_is_mobile()) // On mobile\n{\n the_post_thumbnail_url('featured-image-mobile');\n}\nelse\n{\n the_post_thumbnail_url('featured-image');\n}\n</code></pre>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258506", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114518/" ]
I have set up the following: ``` add_image_size( 'featured-image', 1600, 450, true ); ``` which is used to serve a full width image on the website I'm building, but, as you can imagine, for mobile this is re-scaled to a ridiculously small height and looks really odd on mobile. I have created a new image size which I've named `'featured-image-mobile'` and has the dimensions *650px* by *448px*. On the actual page I am displaying the full width image like so: ``` <img src="<?php the_post_thumbnail_url( 'featured-image' )?>" alt="<?php echo $altTag; ?>" title="<?php echo $titleTag; ?>"> ``` Is there a way I can keep ``` the_post_thumbnail_url( 'featured-image' ); ``` for everything except a screen resolution of *650px*, and then change the image size to the following? ``` the_post_thumbnail_url( 'featured-image-mobile' ); ```
WordPress `wp_is_mobile()` can be the function that you're looking for. ``` // Use the build-in function if WP if(wp_is_mobile()) // On mobile { the_post_thumbnail_url('featured-image-mobile'); } else { the_post_thumbnail_url('featured-image'); } ```
258,510
<p>I spent a lot of time searching for a solution where I can pass the value of the JavaScript variable into PHP variable in the same file, same function (WordPress Widget, Form function). Is there a good way, as of 2017, to do so?</p> <p>I have tried this method below. Although the Ajax part bring out the successful message, the php part failed. </p> <p><strong>repeat.php</strong></p> <pre><code>&lt;?php echo $_POST['examplePHP']; //will cause undefined index here ?&gt; &lt;script&gt; jQuery(document).ready(function($){ var exampleJS = "hi!"; $.ajax({ url: ajaxurl, //I have tried 'repeat.php' instead of ajaxurl, but not working. type: 'POST', data: { examplePHP: exampleJS }, success: function( response){ console.log("Successful!"); }, error: function(error){ console.log("error"); } }); }); &lt;/script&gt; </code></pre>
[ { "answer_id": 258512, "author": "xvilo", "author_id": 104427, "author_profile": "https://wordpress.stackexchange.com/users/104427", "pm_score": 1, "selected": false, "text": "<p>Please remember that the code fires from top to bottom. </p>\n\n<p>This way you <strong>can not</strong> 'get' the POST variable before sending it over via ajax. </p>\n\n<p>Something that <em>would</em> work with your setup:</p>\n\n<pre><code>&lt;?php \n if(isset($_POST['examplePHP'])){ //check if $_POST['examplePHP'] exists\n echo $_POST['examplePHP']; // echo the data\n die(); // stop execution of the script.\n }\n?&gt;\n\n&lt;script&gt;\n jQuery(document).ready(function($){\n\n var exampleJS = \"hi!\";\n\n $.ajax({\n url: window.location, //window.location points to the current url. change is needed.\n type: 'POST',\n data: {\n examplePHP: exampleJS\n },\n success: function( response){\n console.log(\"Successful! My post data is: \"+response);\n },\n error: function(error){\n console.log(\"error\");\n }\n });\n\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>First we check if the POST variable exists with <code>isset()</code>. If this exists we echo the content of 'examplePHP' and then stop the execution of the script with <code>die();</code>.</p>\n\n<p>If there is not POST variable available, this means somebody just loads the page. Then we don't echo but just continue with the rest of the page. </p>\n\n<p>I've added <code>window.location</code> which is the current URL. And the <code>response</code> variable gives the echo. </p>\n\n<p>Since this is the WordPress Stack Exchange I would recommend you to use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">WordPress Ajax</a>. You can read more about on the Codex Page! </p>\n" }, { "answer_id": 258775, "author": "Sengngy Kouch", "author_id": 113869, "author_profile": "https://wordpress.stackexchange.com/users/113869", "pm_score": 3, "selected": true, "text": "<p>I found an easy way to pass a JavaScript variable to PHP variable. Please note that this method works in WordPress version 4.7.2, and only specifically on Widget. I wrote a lot of comments to try to explain what each line did. If you have a better solution, please share with us!</p>\n\n<p><strong>Solution:</strong> </p>\n\n<ul>\n<li>Create a hidden input field to store the value of the javascript you want to pass.</li>\n<li>Access that hidden input field and assign its value to a PHP variable.</li>\n</ul>\n\n<p><strong>Demo Widget:</strong></p>\n\n<ul>\n<li><p>I create a demo widget that add \"LOVE YOU\" word according to how many time you press the \"<em>Add LOVE YOU</em>\" button.</p></li>\n<li><p>Note that I left the hidden field shown for better understanding.</p></li>\n<li><p>You can change <code>type=\"text\"</code> to<code>type=\"hidden\"</code> to hide it. </p></li>\n<li><p>This demo only focuses on the <code>form</code> function of the widget.</p></li>\n<li><p>Make sure the click Save button, else the value of the hidden input is not saved by the widget. </p></li>\n</ul>\n\n<p><strong>Demo Widget ScreenShot:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/W5muv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W5muv.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Source code:</strong></p>\n\n<p><em>wp-text-repeater.php</em></p>\n\n<pre><code>&lt;?php\n/**\n*Plugin Name: WP Text Reapter\n**/\n\nclass wp_text_repeater extends WP_Widget {\n\n /**\n * Sets up the widgets name etc\n */\n public function __construct() {\n $widget_ops = array(\n 'classname' =&gt; 'wp_text_repeater',\n 'description' =&gt; 'Widget that prints LOVE YOU repeatedly according to button press',\n );\n parent::__construct( 'wp_text_repeater', 'WP Text Repeater Widget', $widget_ops );\n }\n\n /**\n * Outputs the content of the widget\n *\n * @param array $args\n * @param array $instance\n */\n public function widget( $args, $instance ) {\n // outputs the content of the widget\n $wp_text_repeater_button = ! empty( $instance['wp_text_repeater_button'] ) ? $instance['wp_text_repeater_button'] : '';\n $wp_text_repeater_appendee = ! empty( $instance['wp_text_repeater_appendee'] ) ? $instance['wp_text_repeater_appendee'] : '';\n $wp_text_repeater_hidden = ! empty( $instance['wp_text_repeater_hidden'] ) ? $instance['wp_text_repeater_hidden'] : '';\n }\n\n /**\n * Outputs the options form on admin\n *\n * @param array $instance The widget options\n */\n public function form( $instance ) {\n // outputs the options form on admin\n $instance = wp_parse_args( (array) $instance, array( 'wp_text_repeater_button' =&gt; '', 'wp_text_repeater_appendee' =&gt; '', 'wp_text_repeater_hidden' =&gt; ''));\n\n $wp_text_repeater_button = $instance['wp_text_repeater_button'];\n $wp_text_repeater_appendee = $instance['wp_text_repeater_appendee'];\n $wp_text_repeater_hidden = $instance['wp_text_repeater_hidden'];\n\n $tempHidden = 'wp_text_repeater_hidden';\n\n ?&gt;\n &lt;!-- Hidden field that store number of time user press the button --&gt;\n &lt;input\n class=\"widefat\"\n id=\"&lt;?php echo $this-&gt;get_field_id($tempHidden); ?&gt;\"\n name=\"&lt;?php echo $this-&gt;get_field_name($tempHidden); ?&gt;\"\n type=\"text\"\n value=\"&lt;?php echo esc_attr($$tempHidden);?&gt;\"/&gt;\n &lt;?php\n\n $max = 0; //Number of time user press the button\n\n //if JavaScript front-end hidden input has value, assign $max to it.\n //This If statement sync between the javascript and the php part.\n if(strlen($$tempHidden) &gt; 0){\n $max = intval($$tempHidden);\n }\n\n $counter = 0;\n while($counter &lt; $max){ //loop according to how many time user press the button\n ?&gt;\n &lt;p&gt;LOVE YOU!&lt;/p&gt;\n &lt;?php\n $counter++;\n }\n\n $id_prefix = $this-&gt;get_field_id(''); //get the widget prefix id.\n ?&gt;\n &lt;!-- You can append all your content herev--&gt;\n &lt;span id=\"&lt;?php echo $this-&gt;get_field_id('wp_text_repeater_appendee')?&gt;\"&gt;&lt;/span&gt;\n\n &lt;!-- Add button that call jQery function to add \"LOVE YOU\" word --&gt;\n &lt;input style=\"background-color: #08a538; color:white; height: 27px;\"\n class=\"button widefat\"\n type=\"button\"\n id=\"&lt;?php echo $this-&gt;get_field_id('wp_text_repeater_button'); ?&gt;\"\n value=\"Add LOVE YOU\"\n onclick=\"text_repeater.addLove('&lt;?php echo $this-&gt;id;?&gt;', '&lt;?php echo $id_prefix;?&gt;'); return false;\"\n /&gt;\n\n &lt;script&gt;\n\n jQuery(document).ready(function($){\n var preIndexID;\n var numberOfLove = &lt;?php echo $max; ?&gt;; //grab value from the php in order to sync between the front and back end.\n text_repeater = {\n addLove :function(widget_id, widget_id_string){\n preIndexID = widget_id_string; //get the correct pre-index of the widget.\n numberOfLove++;\n numberOfLove = numberOfLove.toString(); //convert int to string for the hidden input field.\n $(\"#\" + preIndexID + \"wp_text_repeater_hidden\").val(numberOfLove); //change the value of the hidden input field.\n $(\"#\" + preIndexID + \"wp_text_repeater_appendee\").append('&lt;p&gt;LOVE YOU!&lt;/p&gt;'); //live update the front-end with \"LOVE YOU\".\n }\n }\n });\n\n &lt;/script&gt;\n &lt;?php\n }\n\n /**\n * Processing widget options on save\n *\n * @param array $new_instance The new options\n * @param array $old_instance The previous options\n */\n public function update( $new_instance, $old_instance ) {\n // processes widget options to be saved\n $instance = $old_instance;\n\n $instance['wp_text_repeater_button'] = sanitize_text_field($new_instance['wp_text_repeater_button']);\n $instance['wp_text_repeater_appendee'] = sanitize_text_field ($new_instance['wp_text_repeater_appendee']);\n $instance['wp_text_repeater_hidden'] = sanitize_text_field( $new_instance['wp_text_repeater_hidden'] );\n\n return $instance;\n\n }\n}\n\n// register wp_text_repeater widget\nfunction register_wp_text_repeater_widget() {\n register_widget( 'wp_text_repeater' );\n}\nadd_action( 'widgets_init', 'register_wp_text_repeater_widget' );\n</code></pre>\n" } ]
2017/03/01
[ "https://wordpress.stackexchange.com/questions/258510", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113869/" ]
I spent a lot of time searching for a solution where I can pass the value of the JavaScript variable into PHP variable in the same file, same function (WordPress Widget, Form function). Is there a good way, as of 2017, to do so? I have tried this method below. Although the Ajax part bring out the successful message, the php part failed. **repeat.php** ``` <?php echo $_POST['examplePHP']; //will cause undefined index here ?> <script> jQuery(document).ready(function($){ var exampleJS = "hi!"; $.ajax({ url: ajaxurl, //I have tried 'repeat.php' instead of ajaxurl, but not working. type: 'POST', data: { examplePHP: exampleJS }, success: function( response){ console.log("Successful!"); }, error: function(error){ console.log("error"); } }); }); </script> ```
I found an easy way to pass a JavaScript variable to PHP variable. Please note that this method works in WordPress version 4.7.2, and only specifically on Widget. I wrote a lot of comments to try to explain what each line did. If you have a better solution, please share with us! **Solution:** * Create a hidden input field to store the value of the javascript you want to pass. * Access that hidden input field and assign its value to a PHP variable. **Demo Widget:** * I create a demo widget that add "LOVE YOU" word according to how many time you press the "*Add LOVE YOU*" button. * Note that I left the hidden field shown for better understanding. * You can change `type="text"` to`type="hidden"` to hide it. * This demo only focuses on the `form` function of the widget. * Make sure the click Save button, else the value of the hidden input is not saved by the widget. **Demo Widget ScreenShot:** [![enter image description here](https://i.stack.imgur.com/W5muv.png)](https://i.stack.imgur.com/W5muv.png) **Source code:** *wp-text-repeater.php* ``` <?php /** *Plugin Name: WP Text Reapter **/ class wp_text_repeater extends WP_Widget { /** * Sets up the widgets name etc */ public function __construct() { $widget_ops = array( 'classname' => 'wp_text_repeater', 'description' => 'Widget that prints LOVE YOU repeatedly according to button press', ); parent::__construct( 'wp_text_repeater', 'WP Text Repeater Widget', $widget_ops ); } /** * Outputs the content of the widget * * @param array $args * @param array $instance */ public function widget( $args, $instance ) { // outputs the content of the widget $wp_text_repeater_button = ! empty( $instance['wp_text_repeater_button'] ) ? $instance['wp_text_repeater_button'] : ''; $wp_text_repeater_appendee = ! empty( $instance['wp_text_repeater_appendee'] ) ? $instance['wp_text_repeater_appendee'] : ''; $wp_text_repeater_hidden = ! empty( $instance['wp_text_repeater_hidden'] ) ? $instance['wp_text_repeater_hidden'] : ''; } /** * Outputs the options form on admin * * @param array $instance The widget options */ public function form( $instance ) { // outputs the options form on admin $instance = wp_parse_args( (array) $instance, array( 'wp_text_repeater_button' => '', 'wp_text_repeater_appendee' => '', 'wp_text_repeater_hidden' => '')); $wp_text_repeater_button = $instance['wp_text_repeater_button']; $wp_text_repeater_appendee = $instance['wp_text_repeater_appendee']; $wp_text_repeater_hidden = $instance['wp_text_repeater_hidden']; $tempHidden = 'wp_text_repeater_hidden'; ?> <!-- Hidden field that store number of time user press the button --> <input class="widefat" id="<?php echo $this->get_field_id($tempHidden); ?>" name="<?php echo $this->get_field_name($tempHidden); ?>" type="text" value="<?php echo esc_attr($$tempHidden);?>"/> <?php $max = 0; //Number of time user press the button //if JavaScript front-end hidden input has value, assign $max to it. //This If statement sync between the javascript and the php part. if(strlen($$tempHidden) > 0){ $max = intval($$tempHidden); } $counter = 0; while($counter < $max){ //loop according to how many time user press the button ?> <p>LOVE YOU!</p> <?php $counter++; } $id_prefix = $this->get_field_id(''); //get the widget prefix id. ?> <!-- You can append all your content herev--> <span id="<?php echo $this->get_field_id('wp_text_repeater_appendee')?>"></span> <!-- Add button that call jQery function to add "LOVE YOU" word --> <input style="background-color: #08a538; color:white; height: 27px;" class="button widefat" type="button" id="<?php echo $this->get_field_id('wp_text_repeater_button'); ?>" value="Add LOVE YOU" onclick="text_repeater.addLove('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;" /> <script> jQuery(document).ready(function($){ var preIndexID; var numberOfLove = <?php echo $max; ?>; //grab value from the php in order to sync between the front and back end. text_repeater = { addLove :function(widget_id, widget_id_string){ preIndexID = widget_id_string; //get the correct pre-index of the widget. numberOfLove++; numberOfLove = numberOfLove.toString(); //convert int to string for the hidden input field. $("#" + preIndexID + "wp_text_repeater_hidden").val(numberOfLove); //change the value of the hidden input field. $("#" + preIndexID + "wp_text_repeater_appendee").append('<p>LOVE YOU!</p>'); //live update the front-end with "LOVE YOU". } } }); </script> <?php } /** * Processing widget options on save * * @param array $new_instance The new options * @param array $old_instance The previous options */ public function update( $new_instance, $old_instance ) { // processes widget options to be saved $instance = $old_instance; $instance['wp_text_repeater_button'] = sanitize_text_field($new_instance['wp_text_repeater_button']); $instance['wp_text_repeater_appendee'] = sanitize_text_field ($new_instance['wp_text_repeater_appendee']); $instance['wp_text_repeater_hidden'] = sanitize_text_field( $new_instance['wp_text_repeater_hidden'] ); return $instance; } } // register wp_text_repeater widget function register_wp_text_repeater_widget() { register_widget( 'wp_text_repeater' ); } add_action( 'widgets_init', 'register_wp_text_repeater_widget' ); ```
258,525
<p>In my website currently for every new registration. New registered user is receiving their credential i.e., username and password in there email.</p> <p>I want to allow the user to set their password at the time of registration and after that an email verification link will sent to their email id.</p> <p>Below is my code which i want to modify:</p> <pre><code>&lt;form method="post" class="wp-user-form " id="wp_signup_form_' . $rand_id . '" enctype="multipart/form-data"&gt; &lt;div class="col-md-12 col-lg-12 col-sm-12 col-xs-12"&gt;'; $cs_opt_array = array( 'id' =&gt; '', 'std' =&gt; '', 'cust_id' =&gt; 'user_login_' . $rand_id, 'cust_name' =&gt; 'user_login' . $rand_id, 'classes' =&gt; 'form-control', 'extra_atr' =&gt; ' size="20" tabindex="101" placeholder="' . __('Username*', 'theme_domain') . '"', 'return' =&gt; true, ); $output .= $cs_form_fields2-&gt;cs_form_text_render($cs_opt_array); $output .= '&lt;/div&gt;'; $output .=$cs_form_fields_frontend-&gt;cs_form_text_render( array('name' =&gt; __('Email*', 'theme_domain'), 'id' =&gt; 'user_email' . $rand_id . '', 'classes' =&gt; 'col-md-12 col-lg-12 col-sm-12 col-xs-12', 'std' =&gt; '', 'description' =&gt; '', 'return' =&gt; true, 'hint' =&gt; '' ) ); $output .=$cs_form_fields_frontend-&gt;cs_form_hidden_render( array('name' =&gt; __('Post Type', 'theme_domain'), 'id' =&gt; 'user_role_type' . $rand_id . '', 'classes' =&gt; 'col-md-12 col-lg-12 col-sm-12 col-xs-12', 'std' =&gt; 'candidate', 'description' =&gt; '', 'return' =&gt; true, 'hint' =&gt; '' ) ); if (is_user_logged_in()) { $output .= '&lt;div class="col-md-6 col-lg-6 col-sm-12 col-xs-12"&gt;'; $cs_opt_array = array( 'id' =&gt; '', 'std' =&gt; __('Create Account', 'theme_domain'), 'cust_id' =&gt; 'submitbtn' . $rand_id, 'cust_name' =&gt; 'user-submit', 'cust_type' =&gt; 'button', 'extra_atr' =&gt; ' tabindex="103" onclick="javascript:show_alert_msg(\'' . __("Please logout first then try to registration again", "theme_domain") . '\')"', 'classes' =&gt; 'cs-bgcolor user-submit acc-submit', 'return' =&gt; true, ); $output .= $cs_form_fields2-&gt;cs_form_text_render($cs_opt_array); $output .= ' &lt;!--&lt;/div&gt;--&gt; &lt;/div&gt;'; } else { $output .= '&lt;div class="col-md-6 col-lg-6 col-sm-12 col-xs-12"&gt;'; $cs_opt_array = array( 'id' =&gt; '', 'std' =&gt; __('Create Account', 'theme_domain'), 'cust_id' =&gt; 'submitbtn' . $rand_id, 'cust_name' =&gt; 'user-submit', 'cust_type' =&gt; 'button', 'extra_atr' =&gt; ' tabindex="103" onclick="javascript:cs_registration_validation(\'' . admin_url("admin-ajax.php") . '\',\'' . $rand_id . '\')"', 'classes' =&gt; 'cs-bgcolor user-submit acc-submit', 'return' =&gt; true, ); $output .= $cs_form_fields2-&gt;cs_form_text_render($cs_opt_array); $cs_opt_array = array( 'id' =&gt; '', 'std' =&gt; $role, 'cust_id' =&gt; 'login-role', 'cust_name' =&gt; 'role', 'cust_type' =&gt; 'hidden', 'return' =&gt; true, ); $output .= $cs_form_fields2-&gt;cs_form_text_render($cs_opt_array); $cs_opt_array = array( 'id' =&gt; '', 'std' =&gt; 'cs_registration_validation', 'cust_name' =&gt; 'action', 'cust_type' =&gt; 'hidden', 'return' =&gt; true, ); $output .= $cs_form_fields2-&gt;cs_form_text_render($cs_opt_array); $output .= ' &lt;/div&gt; '; } $output .=' &lt;div class="col-md-6 col-lg-6 col-sm-12 col-xs-12 login-section"&gt; &lt;i class="icon-user-add"&gt;&lt;/i&gt; ' . __("Already have an account?", "theme_domain") . ' &lt;a href="#" class="login-link-page"&gt;' . __('Login Now', 'theme_domain') . '&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="result_' . $rand_id . '" class="status-message"&gt;&lt;p class="status"&gt;&lt;/p&gt;&lt;/div&gt; &lt;/div&gt;'; $output .='&lt;/form&gt;'; $output .='&lt;/div&gt;'; </code></pre> <p>Below is the function currently i am using in my website</p> <pre><code>function mytheme_registration_save($user_id) { if ( isset($_REQUEST['action']) &amp;&amp; $_REQUEST['action'] == 'register' ) { $random_password = wp_generate_password($length = 12, $include_standard_special_chars = false); wp_set_password($random_password, $user_id); $reg_user = get_user_by('ID', $user_id); if ( isset($reg_user-&gt;roles) &amp;&amp; (in_array('subscriber', $reg_user-&gt;roles) || in_array('editor', $reg_user-&gt;roles) || in_array('author', $reg_user-&gt;roles)) ) { // Site owner email hook do_action('theme_domain_new_user_notification_site_owner', $reg_user-&gt;data-&gt;user_login, $reg_user-&gt;data-&gt;user_email); // normal user email hook do_action('theme_domain_user_register', $reg_user, $random_password); } } } } </code></pre>
[ { "answer_id": 258526, "author": "Fernando Baltazar", "author_id": 10218, "author_profile": "https://wordpress.stackexchange.com/users/10218", "pm_score": 4, "selected": true, "text": "<p>Well, you can create your own login form which I´ve have done also few years ago, but it is easier to do it with a plugin. there are a lot of these plugins, for example: <strong>Auto login new user</strong> <a href=\"https://wordpress.org/plugins/auto-login-new-user-after-registration/\" rel=\"noreferrer\">https://wordpress.org/plugins/auto-login-new-user-after-registration/</a>; also you can add <strong>social login</strong> to your Wordpress, this creates an automatic registration on your site.</p>\n" }, { "answer_id": 259161, "author": "Nitish Paswan", "author_id": 106282, "author_profile": "https://wordpress.stackexchange.com/users/106282", "pm_score": 1, "selected": false, "text": "<p>For adding custom password instead of generating the default password i used the below code to add password field to my form:</p>\n\n<pre><code>//Add Custom Password Field\n $output .= '&lt;div class=\"col-md-12 col-lg-12 col-sm-12 col-xs-12\"&gt;';\n $output .='&lt;label class=\"password\"&gt;';\n\n $cs_opt_array = array(\n 'id' =&gt; '',\n 'std' =&gt; __('Password', 'jobhunt'),\n 'cust_id' =&gt; 'user_pass' . $rand_id,\n 'cust_name' =&gt; 'pass1',\n 'cust_type' =&gt; 'password',\n 'classes' =&gt; 'form-control',\n 'extra_atr' =&gt; ' size=\"100\" tabindex=\"101\" placeholder=\"' . __('Password*', 'jobhunt') . '\"',\n 'return' =&gt; true,\n\n\n );\n $output .= $cs_form_fields2-&gt;cs_form_text_render($cs_opt_array);\n\n $output .='&lt;/label&gt;';\n\n $output .= '&lt;/div&gt;';\n $output .= '&lt;div class=\"col-md-12 col-lg-12 col-sm-12 col-xs-12\"&gt;';\n $output .='&lt;label class=\"password\"&gt;';\n\n $cs_opt_array = array(\n 'id' =&gt; '',\n 'std' =&gt; __('Password', 'jobhunt'),\n 'cust_id' =&gt; 'user_pass' . $rand_id,\n 'cust_name' =&gt; 'pass2',\n 'cust_type' =&gt; 'password',\n 'classes' =&gt; 'form-control',\n 'extra_atr' =&gt; ' size=\"100\" tabindex=\"101\" placeholder=\"' . __('Repeat Password*', 'jobhunt') . '\"',\n 'return' =&gt; true,\n );\n $output .= $cs_form_fields2-&gt;cs_form_text_render($cs_opt_array);\n\n $output .='&lt;/label&gt;';\n $output .= '&lt;/div&gt;';\n //End\n</code></pre>\n\n<p>After that i validate this two fields by below code:</p>\n\n<pre><code> if ( empty( $_POST['pass1'] ) || ! empty( $_POST['pass1'] ) &amp;&amp; trim( $_POST['pass1'] ) == '' ) {\n $json['type'] = \"error\";\n $json['message'] = $cs_danger_html . __('&lt;strong&gt;ERROR&lt;/strong&gt;: Password field is required.') . $cs_msg_html;\n echo json_encode($json);\n exit();\n }\n if ( empty( $_POST['pass2'] ) || ! empty( $_POST['pass2'] ) &amp;&amp; trim( $_POST['pass2'] ) == '' ) {\n $json['type'] = \"error\";\n $json['message'] = $cs_danger_html . __('&lt;strong&gt;ERROR&lt;/strong&gt;: Confirm Password field is required.') . $cs_msg_html;\n echo json_encode($json);\n exit();\n }\n if ( $_POST['pass1'] != $_POST['pass2'] ) {\n $json['type'] = \"error\";\n $json['message'] = $cs_danger_html . __('&lt;strong&gt;ERROR&lt;/strong&gt;: Password field and Confirm Password field do not match.') . $cs_msg_html;\n echo json_encode($json);\n exit();\n }\n\n $random_password = $_POST['pass1'];\n</code></pre>\n\n<p>After validation its time to save the data in database and i used below code for saving the entered password:</p>\n\n<pre><code>function mytheme_registration_save($user_id) {\n\n\nif ( isset($_REQUEST['action']) &amp;&amp; $_REQUEST['action'] == 'register' ) {\n\n $random_password = $_POST['pass1'];\n wp_set_password($random_password, $user_id);\n $reg_user = get_user_by('ID', $user_id);\n if ( isset($reg_user-&gt;roles) &amp;&amp; (in_array('subscriber', $reg_user-&gt;roles) || in_array('editor', $reg_user-&gt;roles) || in_array('author', $reg_user-&gt;roles)) ) {\n // Site owner email hook\n do_action('theme_domain_new_user_notification_site_owner', $reg_user-&gt;data-&gt;user_login, $reg_user-&gt;data-&gt;user_email);\n // normal user email hook\n do_action('theme_domain_user_register', $reg_user, $random_password);\n }\n}\n}\n}\n</code></pre>\n\n<p>Now for sending the verification email i found the below link.And its really very helpful for me.\n<a href=\"https://hungred.com/how-to/woocommerce-email-verification-wordpress-code/\" rel=\"nofollow noreferrer\">Email Verification Link</a> \nAnd Many thanks to <a href=\"https://hungred.com/author/clay/\" rel=\"nofollow noreferrer\">Clay</a> author of Email Verification post.</p>\n\n<p>I simply used the below to my theme's functions.php</p>\n\n<pre><code>function wc_registration_redirect( $redirect_to ) {\nwp_logout();\nwp_redirect( '/sign-in/?q=');\nexit;\n}\n// when user login, we will check whether this guy email is verify\nfunction wp_authenticate_user( $userdata ) {\n$isActivated = get_user_meta($userdata-&gt;ID, 'is_activated', true);\nif ( !$isActivated ) {\n $userdata = new WP_Error(\n 'inkfool_confirmation_error',\n __( '&lt;strong&gt;ERROR:&lt;/strong&gt; Your account has to be activated before you can login. You can resend by clicking &lt;a href=\"/sign-in/?u='.$userdata-&gt;ID.'\"&gt;here&lt;/a&gt;', 'inkfool' )\n );\n}\nreturn $userdata;\n }\n// when a user register we need to send them an email to verify their account\nfunction my_user_register($user_id) {\n // get user data\n $user_info = get_userdata($user_id);\n // create md5 code to verify later\n $code = md5(time());\n // make it into a code to send it to user via email\n $string = array('id'=&gt;$user_id, 'code'=&gt;$code);\n // create the activation code and activation status\n update_user_meta($user_id, 'is_activated', 0);\n update_user_meta($user_id, 'activationcode', $code);\n // create the url\n $url = get_site_url(). '/sign-in/?p=' .base64_encode( serialize($string));\n // basically we will edit here to make this nicer\n $html = 'Please click the following links &lt;br/&gt;&lt;br/&gt; &lt;a href=\"'.$url.'\"&gt;'.$url.'&lt;/a&gt;';\n // send an email out to user\n wc_mail($user_info-&gt;user_email, __('Please activate your account'), $html);\n}\n// we need this to handle all the getty hacks i made\nfunction my_init(){\n // check whether we get the activation message\n if(isset($_GET['p'])){\n $data = unserialize(base64_decode($_GET['p']));\n $code = get_user_meta($data['id'], 'activationcode', true);\n // check whether the code given is the same as ours\n if($code == $data['code']){\n // update the db on the activation process\n update_user_meta($data['id'], 'is_activated', 1);\n wc_add_notice( __( '&lt;strong&gt;Success:&lt;/strong&gt; Your account has been activated! ', 'inkfool' ) );\n }else{\n wc_add_notice( __( '&lt;strong&gt;Error:&lt;/strong&gt; Activation fails, please contact our administrator. ', 'inkfool' ) );\n }\n }\n if(isset($_GET['q'])){\n wc_add_notice( __( '&lt;strong&gt;Error:&lt;/strong&gt; Your account has to be activated before you can login. Please check your email.', 'inkfool' ) );\n }\n if(isset($_GET['u'])){\n my_user_register($_GET['u']);\n wc_add_notice( __( '&lt;strong&gt;Succes:&lt;/strong&gt; Your activation email has been resend. Please check your email.', 'inkfool' ) );\n }\n}\n// hooks handler\nadd_action( 'init', 'my_init' );\nadd_filter('woocommerce_registration_redirect', 'wc_registration_redirect');\nadd_filter('wp_authenticate_user', 'wp_authenticate_user',10,2);\nadd_action('user_register', 'my_user_register',10,2);\n</code></pre>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258525", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106282/" ]
In my website currently for every new registration. New registered user is receiving their credential i.e., username and password in there email. I want to allow the user to set their password at the time of registration and after that an email verification link will sent to their email id. Below is my code which i want to modify: ``` <form method="post" class="wp-user-form " id="wp_signup_form_' . $rand_id . '" enctype="multipart/form-data"> <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12">'; $cs_opt_array = array( 'id' => '', 'std' => '', 'cust_id' => 'user_login_' . $rand_id, 'cust_name' => 'user_login' . $rand_id, 'classes' => 'form-control', 'extra_atr' => ' size="20" tabindex="101" placeholder="' . __('Username*', 'theme_domain') . '"', 'return' => true, ); $output .= $cs_form_fields2->cs_form_text_render($cs_opt_array); $output .= '</div>'; $output .=$cs_form_fields_frontend->cs_form_text_render( array('name' => __('Email*', 'theme_domain'), 'id' => 'user_email' . $rand_id . '', 'classes' => 'col-md-12 col-lg-12 col-sm-12 col-xs-12', 'std' => '', 'description' => '', 'return' => true, 'hint' => '' ) ); $output .=$cs_form_fields_frontend->cs_form_hidden_render( array('name' => __('Post Type', 'theme_domain'), 'id' => 'user_role_type' . $rand_id . '', 'classes' => 'col-md-12 col-lg-12 col-sm-12 col-xs-12', 'std' => 'candidate', 'description' => '', 'return' => true, 'hint' => '' ) ); if (is_user_logged_in()) { $output .= '<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12">'; $cs_opt_array = array( 'id' => '', 'std' => __('Create Account', 'theme_domain'), 'cust_id' => 'submitbtn' . $rand_id, 'cust_name' => 'user-submit', 'cust_type' => 'button', 'extra_atr' => ' tabindex="103" onclick="javascript:show_alert_msg(\'' . __("Please logout first then try to registration again", "theme_domain") . '\')"', 'classes' => 'cs-bgcolor user-submit acc-submit', 'return' => true, ); $output .= $cs_form_fields2->cs_form_text_render($cs_opt_array); $output .= ' <!--</div>--> </div>'; } else { $output .= '<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12">'; $cs_opt_array = array( 'id' => '', 'std' => __('Create Account', 'theme_domain'), 'cust_id' => 'submitbtn' . $rand_id, 'cust_name' => 'user-submit', 'cust_type' => 'button', 'extra_atr' => ' tabindex="103" onclick="javascript:cs_registration_validation(\'' . admin_url("admin-ajax.php") . '\',\'' . $rand_id . '\')"', 'classes' => 'cs-bgcolor user-submit acc-submit', 'return' => true, ); $output .= $cs_form_fields2->cs_form_text_render($cs_opt_array); $cs_opt_array = array( 'id' => '', 'std' => $role, 'cust_id' => 'login-role', 'cust_name' => 'role', 'cust_type' => 'hidden', 'return' => true, ); $output .= $cs_form_fields2->cs_form_text_render($cs_opt_array); $cs_opt_array = array( 'id' => '', 'std' => 'cs_registration_validation', 'cust_name' => 'action', 'cust_type' => 'hidden', 'return' => true, ); $output .= $cs_form_fields2->cs_form_text_render($cs_opt_array); $output .= ' </div> '; } $output .=' <div class="col-md-6 col-lg-6 col-sm-12 col-xs-12 login-section"> <i class="icon-user-add"></i> ' . __("Already have an account?", "theme_domain") . ' <a href="#" class="login-link-page">' . __('Login Now', 'theme_domain') . '</a> </div> </div> </div> <div id="result_' . $rand_id . '" class="status-message"><p class="status"></p></div> </div>'; $output .='</form>'; $output .='</div>'; ``` Below is the function currently i am using in my website ``` function mytheme_registration_save($user_id) { if ( isset($_REQUEST['action']) && $_REQUEST['action'] == 'register' ) { $random_password = wp_generate_password($length = 12, $include_standard_special_chars = false); wp_set_password($random_password, $user_id); $reg_user = get_user_by('ID', $user_id); if ( isset($reg_user->roles) && (in_array('subscriber', $reg_user->roles) || in_array('editor', $reg_user->roles) || in_array('author', $reg_user->roles)) ) { // Site owner email hook do_action('theme_domain_new_user_notification_site_owner', $reg_user->data->user_login, $reg_user->data->user_email); // normal user email hook do_action('theme_domain_user_register', $reg_user, $random_password); } } } } ```
Well, you can create your own login form which I´ve have done also few years ago, but it is easier to do it with a plugin. there are a lot of these plugins, for example: **Auto login new user** <https://wordpress.org/plugins/auto-login-new-user-after-registration/>; also you can add **social login** to your Wordpress, this creates an automatic registration on your site.
258,529
<p>i have installed word press + woo commerce, my site is running in Arabic language. </p> <p>my check out page is contain these fields (first name - last name - E-mail - phone) </p> <p>what i want: i hope to edit my checkout page by adding an extra fields like (Company name - position) how to do this </p> <p>i hope if you explain me i didn't have any experience in PHP, CSS just i will apply your suggestions</p>
[ { "answer_id": 258533, "author": "Fernando Baltazar", "author_id": 10218, "author_profile": "https://wordpress.stackexchange.com/users/10218", "pm_score": 0, "selected": false, "text": "<p>Try to use a plugin to acheive this. there are several plugins on repository <a href=\"https://wordpress.org/plugins/search.php?type=term&amp;q=custom+field+checkout\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/search.php?type=term&amp;q=custom+field+checkout</a>.</p>\n\n<p>So from here you can test some of these and choose your favorite. For example this one is easy to use <a href=\"https://wordpress.org/plugins/woo-custom-checkout-field/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/woo-custom-checkout-field/</a></p>\n" }, { "answer_id": 258557, "author": "Kristoffer M", "author_id": 113286, "author_profile": "https://wordpress.stackexchange.com/users/113286", "pm_score": 1, "selected": false, "text": "<p>If you at least know how to open your \"functions.php\" file, the following should work if you simply add it at the bottom of your functions.php file of your (child-)theme:</p>\n\n<pre><code>// Hook in\n\nadd_filter( 'woocommerce_checkout_fields' , 'custom_add_checkout_fields' );\n\n// Our hooked in function - $fields is passed via the filter!\nfunction custom_add_checkout_fields( $fields ) {\n $fields['billing']['Company'] = array(\n 'label' =&gt; __('Company', 'woocommerce'),\n 'placeholder' =&gt; _x('Company Name', 'placeholder', 'woocommerce'),\n 'required' =&gt; true,\n 'class' =&gt; array('form-row-wide'),\n 'clear' =&gt; true\n );\n\n\n $fields['billing']['Position'] = array(\n 'label' =&gt; __('Position', 'woocommerce'),\n 'placeholder' =&gt; _x('Position', 'placeholder', 'woocommerce'),\n 'required' =&gt; true,\n 'class' =&gt; array('form-row-wide'),\n 'clear' =&gt; true\n );\n\n\n return $fields;\n}\n</code></pre>\n\n<p>This should add the fields to the checkout page and have them be required. Then if you want to also add that information to the emails:</p>\n\n<pre><code>add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys');\n\nfunction my_custom_order_meta_keys( $keys ) {\n $keys[] = 'Company'; // This will look for a custom field called 'Company' and add it to emails\n $keys[] = 'Position';\n return $keys;\n}\n</code></pre>\n\n<p>Snippets used from <a href=\"https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/\" rel=\"nofollow noreferrer\" title=\"this woocommerce doc\">this woocommerce doc</a></p>\n\n<p><strong>PLEASE NOTE</strong></p>\n\n<p>Adding this directly to your functions.php file of your theme and then updating your theme removes it - creating a child theme is best practice.\nI know this whole answer might not help you, but it might help someone else.</p>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114524/" ]
i have installed word press + woo commerce, my site is running in Arabic language. my check out page is contain these fields (first name - last name - E-mail - phone) what i want: i hope to edit my checkout page by adding an extra fields like (Company name - position) how to do this i hope if you explain me i didn't have any experience in PHP, CSS just i will apply your suggestions
If you at least know how to open your "functions.php" file, the following should work if you simply add it at the bottom of your functions.php file of your (child-)theme: ``` // Hook in add_filter( 'woocommerce_checkout_fields' , 'custom_add_checkout_fields' ); // Our hooked in function - $fields is passed via the filter! function custom_add_checkout_fields( $fields ) { $fields['billing']['Company'] = array( 'label' => __('Company', 'woocommerce'), 'placeholder' => _x('Company Name', 'placeholder', 'woocommerce'), 'required' => true, 'class' => array('form-row-wide'), 'clear' => true ); $fields['billing']['Position'] = array( 'label' => __('Position', 'woocommerce'), 'placeholder' => _x('Position', 'placeholder', 'woocommerce'), 'required' => true, 'class' => array('form-row-wide'), 'clear' => true ); return $fields; } ``` This should add the fields to the checkout page and have them be required. Then if you want to also add that information to the emails: ``` add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys'); function my_custom_order_meta_keys( $keys ) { $keys[] = 'Company'; // This will look for a custom field called 'Company' and add it to emails $keys[] = 'Position'; return $keys; } ``` Snippets used from [this woocommerce doc](https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/ "this woocommerce doc") **PLEASE NOTE** Adding this directly to your functions.php file of your theme and then updating your theme removes it - creating a child theme is best practice. I know this whole answer might not help you, but it might help someone else.
258,541
<p>I tried echoing <code>get_the_excerpt(1)</code>, on different locations outside the loops:</p> <ul> <li>somewhere in <code>footer.php</code></li> <li>somewhere in <code>header.php</code></li> </ul> <p>(The post with ID 1 has no defined excerpt btw, so I was hoping for the auto-generated ones to came out)</p> <hr> <p>The one in <code>footer.php</code> printed the stuff just fine, but the one in <code>header.php</code> somehow printed nothing (blank).</p> <p>May I ask for simple explanation on how such thing could happen? And a workaround to make auto-generated excerpt printed correctly on both locations.</p> <p>Thank You.</p>
[ { "answer_id": 258550, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>Outside the loop you could try something like this:</p>\n\n<pre><code>$post_id = 1;\n$myexcerpt = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));\n\necho $myexcerpt;\n</code></pre>\n" }, { "answer_id": 258560, "author": "tillinberlin", "author_id": 26059, "author_profile": "https://wordpress.stackexchange.com/users/26059", "pm_score": 1, "selected": false, "text": "<p>So you are basically also looking for a fallback in case your excerpt is empty? I suppose this question/answer could be helpful for you: \"<a href=\"https://wordpress.stackexchange.com/questions/87620/get-the-excerpt-with-fallback-like-the-excerpt\">get_the_excerpt() with fallback like the_excerpt()</a>\". It describes, how to build your own \"excerpt\" in case there is none – like this: </p>\n\n<pre><code>$excerpt = get_the_content();\n$excerpt = esc_attr( strip_tags( stripslashes( $excerpt ) ) );\n$excerpt = wp_trim_words( $excerpt, $num_words = 55, $more = NULL );\n</code></pre>\n\n<p>In your case you would probably add the ID to it: <code>$excerpt = get_the_content(1);</code>. I don't know if your SE privileges allow this, but should probably add \"<em>I'm looking for a solution for when has (the article) no defined excerpt / the post_excerpt is empty</em>\" to your question to clarify what you are actually looking for…</p>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258541", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114526/" ]
I tried echoing `get_the_excerpt(1)`, on different locations outside the loops: * somewhere in `footer.php` * somewhere in `header.php` (The post with ID 1 has no defined excerpt btw, so I was hoping for the auto-generated ones to came out) --- The one in `footer.php` printed the stuff just fine, but the one in `header.php` somehow printed nothing (blank). May I ask for simple explanation on how such thing could happen? And a workaround to make auto-generated excerpt printed correctly on both locations. Thank You.
So you are basically also looking for a fallback in case your excerpt is empty? I suppose this question/answer could be helpful for you: "[get\_the\_excerpt() with fallback like the\_excerpt()](https://wordpress.stackexchange.com/questions/87620/get-the-excerpt-with-fallback-like-the-excerpt)". It describes, how to build your own "excerpt" in case there is none – like this: ``` $excerpt = get_the_content(); $excerpt = esc_attr( strip_tags( stripslashes( $excerpt ) ) ); $excerpt = wp_trim_words( $excerpt, $num_words = 55, $more = NULL ); ``` In your case you would probably add the ID to it: `$excerpt = get_the_content(1);`. I don't know if your SE privileges allow this, but should probably add "*I'm looking for a solution for when has (the article) no defined excerpt / the post\_excerpt is empty*" to your question to clarify what you are actually looking for…
258,573
<p>I'm working on WordPress website locally and I'm using Git. I followed this tutorial <a href="http://www.designcollective.io/blogs/manage-wordpress-with-git" rel="nofollow noreferrer">http://www.designcollective.io/blogs/manage-wordpress-with-git</a> and everything works fine on localhost. I moved my website to server, changed database name etc. And homepage works fine but I can't log into wp-admin. It gives me this:</p> <pre><code>Not Found The requested URL /index.php was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. </code></pre> <p>Same goes for any other page except homepage. I checked database, wp-config, permissions of folders. Only thing diffrent from normal wordpress installation is that I have wp-content outside of wordpress folder same with wp-config but I point it out in index.php the way it's described in tutorial.</p> <p>Any sugestions? Can't modify httpd.conf as I'm on shared hosting. </p> <p>That's my .htacess file:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>And that's my directory</p> <p><a href="https://i.stack.imgur.com/zajH2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zajH2.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 258576, "author": "Elex", "author_id": 113687, "author_profile": "https://wordpress.stackexchange.com/users/113687", "pm_score": 0, "selected": false, "text": "<p>Can you show us your directory and your <code>.htaccess</code> file ?\nTo be honest, moving the wp-config.php outside of WordPress directory is a good thing, but for wp-content, it's not in my opinion.</p>\n" }, { "answer_id": 259012, "author": "zubmic", "author_id": 113194, "author_profile": "https://wordpress.stackexchange.com/users/113194", "pm_score": 2, "selected": true, "text": "<p>Tried to solve the problem on my own. I changed structure to typical wordpress installation but it didn't help. So I deleted wordpress, cleaned database, installed wordpress again and manually moved my theme to Wordpress. Now everything works fine. </p>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258573", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113194/" ]
I'm working on WordPress website locally and I'm using Git. I followed this tutorial <http://www.designcollective.io/blogs/manage-wordpress-with-git> and everything works fine on localhost. I moved my website to server, changed database name etc. And homepage works fine but I can't log into wp-admin. It gives me this: ``` Not Found The requested URL /index.php was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. ``` Same goes for any other page except homepage. I checked database, wp-config, permissions of folders. Only thing diffrent from normal wordpress installation is that I have wp-content outside of wordpress folder same with wp-config but I point it out in index.php the way it's described in tutorial. Any sugestions? Can't modify httpd.conf as I'm on shared hosting. That's my .htacess file: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` And that's my directory [![enter image description here](https://i.stack.imgur.com/zajH2.jpg)](https://i.stack.imgur.com/zajH2.jpg)
Tried to solve the problem on my own. I changed structure to typical wordpress installation but it didn't help. So I deleted wordpress, cleaned database, installed wordpress again and manually moved my theme to Wordpress. Now everything works fine.
258,592
<p>I am trying to use the .htaccess file to restrict access to the wp-admin directory to an IP range as prescribed <a href="https://codex.wordpress.org/Brute_Force_Attacks#Limit_Access_to_wp-admin_by_IP" rel="nofollow noreferrer">here</a></p> <pre><code># Block access to wp-admin. order deny,allow allow from x.x.x.* deny from all' </code></pre> <p><strong>It does precisely nothing:</strong> I removed the allow line altogether and I am able to login just fine.</p> <p>What am I missing?</p>
[ { "answer_id": 258603, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 0, "selected": false, "text": "<pre><code>order deny,allow\ndeny from all\nallow from x.x.x \n</code></pre>\n\n<p>or</p>\n\n<pre><code>order deny,allow\ndeny from all\nallow from x.x.x.0/32\n</code></pre>\n\n<p>If on Apache 2.4 try this:</p>\n\n<pre><code>Require all denied\nRequire ip x.x.x\n</code></pre>\n\n<p>or </p>\n\n<pre><code>Require all denied\nRequire ip x.x.x.0/32\n</code></pre>\n" }, { "answer_id": 258631, "author": "Lew", "author_id": 114569, "author_profile": "https://wordpress.stackexchange.com/users/114569", "pm_score": 1, "selected": false, "text": "<p>I have traced the problem to a set of directions in the .conf file:\nthe Virtual Host was missing this:</p>\n\n<pre><code>&lt;Directory \"/var/www\"&gt;\nAllowOverride All\n&lt;/Directory&gt;\n</code></pre>\n\n<p>Which made the server to ignore .htaccess files altogether.</p>\n\n<p>The full answer is <a href=\"https://askubuntu.com/questions/429869/is-this-a-correct-way-to-enable-htaccess-in-apache-2-4-7-on-ubuntu-12-04\">here</a></p>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258592", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114569/" ]
I am trying to use the .htaccess file to restrict access to the wp-admin directory to an IP range as prescribed [here](https://codex.wordpress.org/Brute_Force_Attacks#Limit_Access_to_wp-admin_by_IP) ``` # Block access to wp-admin. order deny,allow allow from x.x.x.* deny from all' ``` **It does precisely nothing:** I removed the allow line altogether and I am able to login just fine. What am I missing?
I have traced the problem to a set of directions in the .conf file: the Virtual Host was missing this: ``` <Directory "/var/www"> AllowOverride All </Directory> ``` Which made the server to ignore .htaccess files altogether. The full answer is [here](https://askubuntu.com/questions/429869/is-this-a-correct-way-to-enable-htaccess-in-apache-2-4-7-on-ubuntu-12-04)
258,615
<p>I need to add custom links, on the fly, to the navigation menu. I can add custom links to the first level of items (created via Appearance > Menus), but for some reason, I cannot add a custom link, child of another custom link create previously.. </p> <p>Here's my code:</p> <pre><code>function on_the_fly($items) { $menu_items = array(); foreach ($items as $item) { $item-&gt;menu_order = count($menu_items) + 1; $menu_items[] = $item; $new_menu_item = new \WP_Post((object) array( 'ID' =&gt; $item-&gt;ID . "00", )); $new_menu_item-&gt;post_author = 1; $new_menu_item-&gt;comment_status = 'closed'; $new_menu_item-&gt;ping_status = 'closed'; $new_menu_item-&gt;post_type = 'nav_menu_item'; $new_menu_item-&gt;post_title = 'test 1'; $new_menu_item-&gt;post_name = 'test 1'; $new_menu_item-&gt;filter = 'raw'; $new_menu_item-&gt;object_id = $new_menu_item-&gt;ID; $new_menu_item-&gt;object = 'custom'; $new_menu_item-&gt;type = 'custom'; $new_menu_item-&gt;type_label = 'Custom Link'; $new_menu_item-&gt;menu_order = count($menu_items) + 1; $new_menu_item-&gt;menu_item_parent = $item-&gt;ID; $new_menu_item-&gt;url = str_replace("//", "/", $item-&gt;url . "/" . sanitize_title('test 1')); $new_menu_item-&gt;title = 'test 1'; $menu_items[] = $new_menu_item; $new_menu_item_2 = new \WP_Post((object) array( 'ID' =&gt; $new_menu_item-&gt;ID . "00", )); $new_menu_item_2-&gt;post_author = 1; $new_menu_item_2-&gt;comment_status = 'closed'; $new_menu_item_2-&gt;ping_status = 'closed'; $new_menu_item_2-&gt;post_type = 'nav_menu_item'; $new_menu_item_2-&gt;post_title = 'test 2'; $new_menu_item_2-&gt;post_name = 'test 2'; $new_menu_item_2-&gt;filter = 'raw'; $new_menu_item_2-&gt;object_id = $new_menu_item-&gt;ID; $new_menu_item_2-&gt;object = 'custom'; $new_menu_item_2-&gt;type = 'custom'; $new_menu_item_2-&gt;type_label = 'Custom Link'; $new_menu_item_2-&gt;menu_order = count($menu_items) + 1; $new_menu_item_2-&gt;menu_item_parent = $new_menu_item-&gt;ID; $new_menu_item_2-&gt;url = str_replace("//", "/", $item-&gt;url . "/" . sanitize_title('test 2')); $new_menu_item_2-&gt;title = 'test 2'; $menu_items[] = $new_menu_item_2; } return $menu_items; } add_filter('wp_nav_menu_objects', 'on_the_fly', 1,1); </code></pre> <p>Result:</p> <pre><code>&gt; - Application &gt; - test 1 &gt; - test 2 </code></pre> <p>And not:</p> <pre><code>&gt; - Application &gt; - test 1 &gt; - test 2 </code></pre> <p>How can I achieve the desired result?</p>
[ { "answer_id": 258626, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>There is a really good example on this page if you want to have a look and see if it helps - <a href=\"https://isabelcastillo.com/dynamically-sub-menu-item-wp_nav_menu\" rel=\"nofollow noreferrer\">https://isabelcastillo.com/dynamically-sub-menu-item-wp_nav_menu</a></p>\n" }, { "answer_id": 258719, "author": "MGP", "author_id": 56387, "author_profile": "https://wordpress.stackexchange.com/users/56387", "pm_score": 0, "selected": false, "text": "<p>It seems that the missing argument was \"db_id\". \nIf defined, the tree will be created as intended.</p>\n\n<pre><code>$new_menu_item-&gt;db_id = $new_menu_item-&gt;ID;\n</code></pre>\n\n<p>Thanks</p>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258615", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56387/" ]
I need to add custom links, on the fly, to the navigation menu. I can add custom links to the first level of items (created via Appearance > Menus), but for some reason, I cannot add a custom link, child of another custom link create previously.. Here's my code: ``` function on_the_fly($items) { $menu_items = array(); foreach ($items as $item) { $item->menu_order = count($menu_items) + 1; $menu_items[] = $item; $new_menu_item = new \WP_Post((object) array( 'ID' => $item->ID . "00", )); $new_menu_item->post_author = 1; $new_menu_item->comment_status = 'closed'; $new_menu_item->ping_status = 'closed'; $new_menu_item->post_type = 'nav_menu_item'; $new_menu_item->post_title = 'test 1'; $new_menu_item->post_name = 'test 1'; $new_menu_item->filter = 'raw'; $new_menu_item->object_id = $new_menu_item->ID; $new_menu_item->object = 'custom'; $new_menu_item->type = 'custom'; $new_menu_item->type_label = 'Custom Link'; $new_menu_item->menu_order = count($menu_items) + 1; $new_menu_item->menu_item_parent = $item->ID; $new_menu_item->url = str_replace("//", "/", $item->url . "/" . sanitize_title('test 1')); $new_menu_item->title = 'test 1'; $menu_items[] = $new_menu_item; $new_menu_item_2 = new \WP_Post((object) array( 'ID' => $new_menu_item->ID . "00", )); $new_menu_item_2->post_author = 1; $new_menu_item_2->comment_status = 'closed'; $new_menu_item_2->ping_status = 'closed'; $new_menu_item_2->post_type = 'nav_menu_item'; $new_menu_item_2->post_title = 'test 2'; $new_menu_item_2->post_name = 'test 2'; $new_menu_item_2->filter = 'raw'; $new_menu_item_2->object_id = $new_menu_item->ID; $new_menu_item_2->object = 'custom'; $new_menu_item_2->type = 'custom'; $new_menu_item_2->type_label = 'Custom Link'; $new_menu_item_2->menu_order = count($menu_items) + 1; $new_menu_item_2->menu_item_parent = $new_menu_item->ID; $new_menu_item_2->url = str_replace("//", "/", $item->url . "/" . sanitize_title('test 2')); $new_menu_item_2->title = 'test 2'; $menu_items[] = $new_menu_item_2; } return $menu_items; } add_filter('wp_nav_menu_objects', 'on_the_fly', 1,1); ``` Result: ``` > - Application > - test 1 > - test 2 ``` And not: ``` > - Application > - test 1 > - test 2 ``` How can I achieve the desired result?
There is a really good example on this page if you want to have a look and see if it helps - <https://isabelcastillo.com/dynamically-sub-menu-item-wp_nav_menu>
258,616
<p>Im brand new to coding in wordpress, usually I use ModX. In ModX there is a plugin called phpthumb which automatically crops images to a specified h and w. How can I achieve this in Wordpress?</p> <p>Image Code:</p> <pre><code>&lt;?php $thumbnail_id = get_post_thumbnail_id($post-&gt;ID); $thumbnail = wp_get_attachment_image_src($thumbnail_id,'featured works'); echo '&lt;div data-src="'.$thumbnail[0].'" alt="[[+name]]"&gt;&lt;/div&gt;'; ?&gt; </code></pre> <p>Thanks for any insight.</p>
[ { "answer_id": 258626, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 2, "selected": false, "text": "<p>There is a really good example on this page if you want to have a look and see if it helps - <a href=\"https://isabelcastillo.com/dynamically-sub-menu-item-wp_nav_menu\" rel=\"nofollow noreferrer\">https://isabelcastillo.com/dynamically-sub-menu-item-wp_nav_menu</a></p>\n" }, { "answer_id": 258719, "author": "MGP", "author_id": 56387, "author_profile": "https://wordpress.stackexchange.com/users/56387", "pm_score": 0, "selected": false, "text": "<p>It seems that the missing argument was \"db_id\". \nIf defined, the tree will be created as intended.</p>\n\n<pre><code>$new_menu_item-&gt;db_id = $new_menu_item-&gt;ID;\n</code></pre>\n\n<p>Thanks</p>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258616", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114585/" ]
Im brand new to coding in wordpress, usually I use ModX. In ModX there is a plugin called phpthumb which automatically crops images to a specified h and w. How can I achieve this in Wordpress? Image Code: ``` <?php $thumbnail_id = get_post_thumbnail_id($post->ID); $thumbnail = wp_get_attachment_image_src($thumbnail_id,'featured works'); echo '<div data-src="'.$thumbnail[0].'" alt="[[+name]]"></div>'; ?> ``` Thanks for any insight.
There is a really good example on this page if you want to have a look and see if it helps - <https://isabelcastillo.com/dynamically-sub-menu-item-wp_nav_menu>
258,652
<p>I have custom table where I store quotes and author:</p> <pre><code>function quote_install(){ global $wpdb; global $quote_db_version; $table_name = $wpdb-&gt;prefix . 'quote'; // create sql your table $sql = "CREATE TABLE " . $table_name . " ( ID int(11) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, quote text NOT NULL, author text NOT NULL, qtag ENUM('G', 'W', 'Z', 'H', 'M') NOT NULL default 'G', PRIMARY KEY (ID) );"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } </code></pre> <p>Then I want to get single row with quote and author to display.</p> <pre><code>function read_single_Quote( $id=NULL ) { global $wpdb; $table_name = $wpdb-&gt;prefix . 'quotes'; // random select if($id ==NULL){ $sql = $wpdb-&gt;prepare( " SELECT * FROM {$wpdb-&gt;prefix}'quotes' ORDER BY RAND() LIMIT 1 "); } //get the row id = $id else { $sql = $wpdb-&gt;prepare( " SELECT * FROM {$wpdb-&gt;prefix}'quotes' WHERE ID = %d LIMIT 1 ", $id ); } $result = $wpdb-&gt;get_results( $sql ); // databse error, return false if ( ! $result ) { return false; } // return first result return $result[0]; </code></pre> <p>}</p> <p>What is wrong? What is the most efficient way to get random row from custom table?</p>
[ { "answer_id": 258655, "author": "marwyk87", "author_id": 114372, "author_profile": "https://wordpress.stackexchange.com/users/114372", "pm_score": 0, "selected": false, "text": "<p>I think you might have an syntax problem in your TSQL. If your doing</p>\n\n<pre><code>$table_name = $wpdb-&gt;prefix . 'quotes';\n</code></pre>\n\n<p>then you can have</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM \".$table_name.\"\n ORDER BY RAND()\n LIMIT 1\n\");\n</code></pre>\n" }, { "answer_id": 258656, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 2, "selected": false, "text": "<p>[Note: @marwyk87 posted his answer while I was composing this, which represents another way to fix the problem]</p>\n\n<p>You've got a simple syntax error in your SQL, because of the way you're referencing the table name. You should just say</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM {$wpdb-&gt;prefix}quotes\n ORDER BY RAND()\n LIMIT 1\n \");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM {$wpdb-&gt;prefix}quotes\n WHERE ID = %d\n LIMIT 1\n \", $id );\n</code></pre>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258652", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112581/" ]
I have custom table where I store quotes and author: ``` function quote_install(){ global $wpdb; global $quote_db_version; $table_name = $wpdb->prefix . 'quote'; // create sql your table $sql = "CREATE TABLE " . $table_name . " ( ID int(11) NOT NULL AUTO_INCREMENT, time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, quote text NOT NULL, author text NOT NULL, qtag ENUM('G', 'W', 'Z', 'H', 'M') NOT NULL default 'G', PRIMARY KEY (ID) );"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } ``` Then I want to get single row with quote and author to display. ``` function read_single_Quote( $id=NULL ) { global $wpdb; $table_name = $wpdb->prefix . 'quotes'; // random select if($id ==NULL){ $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}'quotes' ORDER BY RAND() LIMIT 1 "); } //get the row id = $id else { $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}'quotes' WHERE ID = %d LIMIT 1 ", $id ); } $result = $wpdb->get_results( $sql ); // databse error, return false if ( ! $result ) { return false; } // return first result return $result[0]; ``` } What is wrong? What is the most efficient way to get random row from custom table?
[Note: @marwyk87 posted his answer while I was composing this, which represents another way to fix the problem] You've got a simple syntax error in your SQL, because of the way you're referencing the table name. You should just say ``` $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}quotes ORDER BY RAND() LIMIT 1 "); ``` and ``` $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}quotes WHERE ID = %d LIMIT 1 ", $id ); ```
258,654
<p>I'm doing a project for a web-based app.</p> <p>It is the first time I use wordpress and I have found that I can not edit the template (the "edit" option does not appear in appearance.).</p> <p>And I need to see the files to be able to remove the "hamburger" menu for mobile devices.</p> <p>For now I'm not premmium.</p> <p>In wix if the option to remove it, however I switch to wordpress because it loads much faster.</p> <p><a href="https://i.stack.imgur.com/Qb5SC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qb5SC.png" alt=""></a></p> <p>[![EDITOR?][2]][2]</p> <p>I also do not find how to import the plugins.</p> <p>When I press on plug in it sends me to another page that has this:</p> <p><a href="https://i.stack.imgur.com/nXc5Z.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nXc5Z.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 258655, "author": "marwyk87", "author_id": 114372, "author_profile": "https://wordpress.stackexchange.com/users/114372", "pm_score": 0, "selected": false, "text": "<p>I think you might have an syntax problem in your TSQL. If your doing</p>\n\n<pre><code>$table_name = $wpdb-&gt;prefix . 'quotes';\n</code></pre>\n\n<p>then you can have</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM \".$table_name.\"\n ORDER BY RAND()\n LIMIT 1\n\");\n</code></pre>\n" }, { "answer_id": 258656, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 2, "selected": false, "text": "<p>[Note: @marwyk87 posted his answer while I was composing this, which represents another way to fix the problem]</p>\n\n<p>You've got a simple syntax error in your SQL, because of the way you're referencing the table name. You should just say</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM {$wpdb-&gt;prefix}quotes\n ORDER BY RAND()\n LIMIT 1\n \");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM {$wpdb-&gt;prefix}quotes\n WHERE ID = %d\n LIMIT 1\n \", $id );\n</code></pre>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258654", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114601/" ]
I'm doing a project for a web-based app. It is the first time I use wordpress and I have found that I can not edit the template (the "edit" option does not appear in appearance.). And I need to see the files to be able to remove the "hamburger" menu for mobile devices. For now I'm not premmium. In wix if the option to remove it, however I switch to wordpress because it loads much faster. [![](https://i.stack.imgur.com/Qb5SC.png)](https://i.stack.imgur.com/Qb5SC.png) [![EDITOR?][2]][2] I also do not find how to import the plugins. When I press on plug in it sends me to another page that has this: [![enter image description here](https://i.stack.imgur.com/nXc5Z.jpg)](https://i.stack.imgur.com/nXc5Z.jpg)
[Note: @marwyk87 posted his answer while I was composing this, which represents another way to fix the problem] You've got a simple syntax error in your SQL, because of the way you're referencing the table name. You should just say ``` $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}quotes ORDER BY RAND() LIMIT 1 "); ``` and ``` $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}quotes WHERE ID = %d LIMIT 1 ", $id ); ```
258,657
<p>For some reason when doing crawl tests I'm finding pages with the domain name being tacked on the end and causing 404 errors. For example: <a href="http://domainname.com/page-name/http://domainname.com" rel="nofollow noreferrer">http://domainname.com/page-name/http://domainname.com</a></p> <p>This is happening to all pages, posts and even category type</p> <ol> <li>Site is in Wordpress</li> <li>Using Yoast SEO plugin</li> </ol> <p>Any suggestions? </p> <p>Thanks!</p> <p>For Example <a href="https://i.stack.imgur.com/D47Fh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D47Fh.png" alt="enter image description here"></a></p>
[ { "answer_id": 258655, "author": "marwyk87", "author_id": 114372, "author_profile": "https://wordpress.stackexchange.com/users/114372", "pm_score": 0, "selected": false, "text": "<p>I think you might have an syntax problem in your TSQL. If your doing</p>\n\n<pre><code>$table_name = $wpdb-&gt;prefix . 'quotes';\n</code></pre>\n\n<p>then you can have</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM \".$table_name.\"\n ORDER BY RAND()\n LIMIT 1\n\");\n</code></pre>\n" }, { "answer_id": 258656, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 2, "selected": false, "text": "<p>[Note: @marwyk87 posted his answer while I was composing this, which represents another way to fix the problem]</p>\n\n<p>You've got a simple syntax error in your SQL, because of the way you're referencing the table name. You should just say</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM {$wpdb-&gt;prefix}quotes\n ORDER BY RAND()\n LIMIT 1\n \");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$sql = $wpdb-&gt;prepare( \"\n SELECT *\n FROM {$wpdb-&gt;prefix}quotes\n WHERE ID = %d\n LIMIT 1\n \", $id );\n</code></pre>\n" } ]
2017/03/02
[ "https://wordpress.stackexchange.com/questions/258657", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93558/" ]
For some reason when doing crawl tests I'm finding pages with the domain name being tacked on the end and causing 404 errors. For example: <http://domainname.com/page-name/http://domainname.com> This is happening to all pages, posts and even category type 1. Site is in Wordpress 2. Using Yoast SEO plugin Any suggestions? Thanks! For Example [![enter image description here](https://i.stack.imgur.com/D47Fh.png)](https://i.stack.imgur.com/D47Fh.png)
[Note: @marwyk87 posted his answer while I was composing this, which represents another way to fix the problem] You've got a simple syntax error in your SQL, because of the way you're referencing the table name. You should just say ``` $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}quotes ORDER BY RAND() LIMIT 1 "); ``` and ``` $sql = $wpdb->prepare( " SELECT * FROM {$wpdb->prefix}quotes WHERE ID = %d LIMIT 1 ", $id ); ```
258,664
<p>I have placed the following Blog Loop into my 'index.php' file:</p> <pre><code>&lt;?php if ( have_posts() ): while( have_posts() ): the_post(); ?&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;small&gt;This entry was posted on: &lt;?php the_date('l, jS F Y'); ?&gt; at &lt;?php the_time('g:i a'); ?&gt; and is filed under &lt;?php the_category(); ?&gt;&lt;/small&gt; &lt;?php endwhile; endif; ?&gt; </code></pre> <p>On my Home page, the above code does not call any Blog Posts as I have appointed a 'Blog' page for my Blogs. That said, the above <code>&lt;small&gt;This entry was posted on: &lt;?php the_date('l, jS F Y'); ?&gt; at &lt;?php the_time('g:i a'); ?&gt; and is filed under &lt;?php the_category(); ?&gt;&lt;/small&gt;</code> is appearing on my Home page as well as other pages. I realise that this is because I have hard coded it into my index.php but how do I remove this. If I simply remove it from my code, it does not appear on my appointed Blog page.</p> <p>Any suggestions?</p>
[ { "answer_id": 258667, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>what about surrounding it in the if is_home() statement so it only shows on your blog page?</p>\n\n<pre><code>&lt;?php\nif ( have_posts() ):\n while( have_posts() ): the_post(); \n?&gt;\n&lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; \n&lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt;\nif ( is_home() ) :?&gt;\n &lt;small&gt;This entry was posted on: &lt;?php the_date('l, jS F Y'); ?&gt; at &lt;?php the_time('g:i a'); ?&gt; and is filed under &lt;?php the_category(); ?&gt;&lt;/small&gt;\n&lt;?php \nendif;\n endwhile;\n endif;\n?&gt;\n</code></pre>\n" }, { "answer_id": 258682, "author": "Craig", "author_id": 112472, "author_profile": "https://wordpress.stackexchange.com/users/112472", "pm_score": 1, "selected": true, "text": "<p>I have managed to resolve the issue. The code I used, should anyone find themselves in a similar situation, is as follows:</p>\n\n<pre><code>&lt;?php if( is_home() ): ?&gt; \n&lt;h1&gt;Blog Page&lt;/h1&gt;\n&lt;?php endif; ?&gt;\n\n&lt;?php \nif ( have_posts() ): \nwhile( have_posts() ): the_post();\n?&gt; \n\n &lt;?php if( is_home() ): ?&gt; \n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; \n &lt;?php the_content();?&gt;\n &lt;small&gt;This entry was posted on: &lt;?php the_date('l, jS F Y'); ?&gt; at &lt;?php the_time('g:i a'); ?&gt; and is filed under &lt;?php the_category(); ?&gt;&lt;/small&gt;;\n\n &lt;?php else: ?&gt;\n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; \n\n &lt;?php endif; ?&gt;\n\n&lt;?php endwhile; ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258664", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112472/" ]
I have placed the following Blog Loop into my 'index.php' file: ``` <?php if ( have_posts() ): while( have_posts() ): the_post(); ?> <h3><?php the_title(); ?></h3> <p><?php the_content(); ?></p> <small>This entry was posted on: <?php the_date('l, jS F Y'); ?> at <?php the_time('g:i a'); ?> and is filed under <?php the_category(); ?></small> <?php endwhile; endif; ?> ``` On my Home page, the above code does not call any Blog Posts as I have appointed a 'Blog' page for my Blogs. That said, the above `<small>This entry was posted on: <?php the_date('l, jS F Y'); ?> at <?php the_time('g:i a'); ?> and is filed under <?php the_category(); ?></small>` is appearing on my Home page as well as other pages. I realise that this is because I have hard coded it into my index.php but how do I remove this. If I simply remove it from my code, it does not appear on my appointed Blog page. Any suggestions?
I have managed to resolve the issue. The code I used, should anyone find themselves in a similar situation, is as follows: ``` <?php if( is_home() ): ?> <h1>Blog Page</h1> <?php endif; ?> <?php if ( have_posts() ): while( have_posts() ): the_post(); ?> <?php if( is_home() ): ?> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <?php the_content();?> <small>This entry was posted on: <?php the_date('l, jS F Y'); ?> at <?php the_time('g:i a'); ?> and is filed under <?php the_category(); ?></small>; <?php else: ?> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <?php endif; ?> <?php endwhile; ?> <?php endif; ?> ```
258,681
<p>I have create child theme with style.css and functions.css, I edit parts style.css in child theme to get best style. But some page have no effect and style.css from child theme repeated with another version.</p> <p>style.css</p> <pre><code>#masthead { top: 0px; background: black !important; border-top: 2px solid rgba(250,105, 0, 1); border-bottom: 2px solid rgba(250,105,0, 1); } </code></pre> <p>functions.php</p> <pre><code>&lt;?php function my_theme_enqueue_styles() { $parent_style = 'parent-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?&gt; </code></pre> <p><a href="https://i.stack.imgur.com/u3d3f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3d3f.png" alt="child theme style.css repeated"></a></p>
[ { "answer_id": 258667, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>what about surrounding it in the if is_home() statement so it only shows on your blog page?</p>\n\n<pre><code>&lt;?php\nif ( have_posts() ):\n while( have_posts() ): the_post(); \n?&gt;\n&lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; \n&lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt;\nif ( is_home() ) :?&gt;\n &lt;small&gt;This entry was posted on: &lt;?php the_date('l, jS F Y'); ?&gt; at &lt;?php the_time('g:i a'); ?&gt; and is filed under &lt;?php the_category(); ?&gt;&lt;/small&gt;\n&lt;?php \nendif;\n endwhile;\n endif;\n?&gt;\n</code></pre>\n" }, { "answer_id": 258682, "author": "Craig", "author_id": 112472, "author_profile": "https://wordpress.stackexchange.com/users/112472", "pm_score": 1, "selected": true, "text": "<p>I have managed to resolve the issue. The code I used, should anyone find themselves in a similar situation, is as follows:</p>\n\n<pre><code>&lt;?php if( is_home() ): ?&gt; \n&lt;h1&gt;Blog Page&lt;/h1&gt;\n&lt;?php endif; ?&gt;\n\n&lt;?php \nif ( have_posts() ): \nwhile( have_posts() ): the_post();\n?&gt; \n\n &lt;?php if( is_home() ): ?&gt; \n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; \n &lt;?php the_content();?&gt;\n &lt;small&gt;This entry was posted on: &lt;?php the_date('l, jS F Y'); ?&gt; at &lt;?php the_time('g:i a'); ?&gt; and is filed under &lt;?php the_category(); ?&gt;&lt;/small&gt;;\n\n &lt;?php else: ?&gt;\n &lt;h3&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; \n\n &lt;?php endif; ?&gt;\n\n&lt;?php endwhile; ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258681", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88507/" ]
I have create child theme with style.css and functions.css, I edit parts style.css in child theme to get best style. But some page have no effect and style.css from child theme repeated with another version. style.css ``` #masthead { top: 0px; background: black !important; border-top: 2px solid rgba(250,105, 0, 1); border-bottom: 2px solid rgba(250,105,0, 1); } ``` functions.php ``` <?php function my_theme_enqueue_styles() { $parent_style = 'parent-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); ?> ``` [![child theme style.css repeated](https://i.stack.imgur.com/u3d3f.png)](https://i.stack.imgur.com/u3d3f.png)
I have managed to resolve the issue. The code I used, should anyone find themselves in a similar situation, is as follows: ``` <?php if( is_home() ): ?> <h1>Blog Page</h1> <?php endif; ?> <?php if ( have_posts() ): while( have_posts() ): the_post(); ?> <?php if( is_home() ): ?> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <?php the_content();?> <small>This entry was posted on: <?php the_date('l, jS F Y'); ?> at <?php the_time('g:i a'); ?> and is filed under <?php the_category(); ?></small>; <?php else: ?> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <?php endif; ?> <?php endwhile; ?> <?php endif; ?> ```
258,694
<p>I want to write a cronjob for myself. But I need to get access to <code>WP_Query</code> and the permissions to delete posts etc.</p> <p>My question now is, how can I include the <code>WP_Query</code> function to my own PHP file and do I need to edit or change some permissions in order to delete or create posts with that cronjob?</p>
[ { "answer_id": 258697, "author": "Kinna T", "author_id": 97336, "author_profile": "https://wordpress.stackexchange.com/users/97336", "pm_score": 0, "selected": false, "text": "<p>Is this to delete or create sites within a WordPress Multisite environment?\nIf so, you can access WP_Query to handle sites by putting the function into a PHP file in a network-activated mu-plugin's folder.</p>\n" }, { "answer_id": 258734, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 5, "selected": true, "text": "<h1>Load WordPress in custom PHP Script:</h1>\n\n<p>You need to load essential WordPress core functionality in your custom PHP script for <code>WP_Query</code> to work properly.</p>\n\n<p>For example, let's say you have a custom PHP file named <code>my-cron.php</code> and WordPress is installed in the web root, like this:</p>\n\n<pre><code>public_html/\n index.php\n my-cron.php &lt;--\n wp-load.php\n wp-settings.php\n ...\n wp-admin/\n wp-content/\n wp-includes/\n</code></pre>\n\n<p>In this setup, if you want to use <code>WP_Query</code> in <code>my-cron.php</code> file, you need to load the <code>wp-load.php</code> file. So in <code>my-cron.php</code> file you need to have the following CODE:</p>\n\n<pre><code>if ( ! defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n\n<h1>Access WP_Query:</h1>\n\n<p>At this point, you'll have the access to <code>WP_Query</code>, so you can use it like this:</p>\n\n<pre><code>// simply selecting posts with category name \"wordpress\"\n$the_query = new WP_Query( array( 'category_name' =&gt; 'wordpress' ) );\nif ( $the_query-&gt;have_posts() ) {\n echo '&lt;ul&gt;';\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n}\nelse {\n echo \"No post found for category named wordpress\";\n}\n</code></pre>\n\n<h1>Delete Posts:</h1>\n\n<p>However, WP_Query doesn't have delete function. For that you'll either need to use the <a href=\"https://developer.wordpress.org/reference/functions/wp_delete_post/\" rel=\"noreferrer\"><code>wp_delete_post()</code></a> function or <a href=\"https://developer.wordpress.org/reference/classes/wpdb/\" rel=\"noreferrer\"><code>WPDB</code></a> class. Using <code>wp_delete_post()</code> is recommended as it'll take care of many dependencies, however, if you need more control, then you may use <code>WPDB</code> class or <code>$wpdb</code> global variable, but be careful if you choose that path.</p>\n\n<p>For example, the following CODE will delete the post with ID <code>1</code>:</p>\n\n<pre><code>$deleted = wp_delete_post( 1 );\nif( $deleted === false ) {\n echo \"Couldn't delete Post with ID=1\";\n}\nelse {\n echo \"Deleted Post with ID=1\"; \n}\n</code></pre>\n\n<p>Of course you can combine <code>WP_Query</code> with <code>wp_delete_post</code> to find and delete posts that meet specific criteria.</p>\n\n<h1>Setup Cron:</h1>\n\n<p>Once you are done writing the custom PHP script, you need to <a href=\"https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/#mac-os-x-and-linux\" rel=\"noreferrer\">setup cron job</a> to run as a HTTP request, like the following:</p>\n\n<pre><code>5 * * * * wget -q -O - http://your-domain.com/my-cron.php\n</code></pre>\n\n<h1>Security:</h1>\n\n<p>Since accessing <code>WP_Query</code> or <code>wp_delete_post</code> function <strong>doesn't require any authentication</strong> (or permission) by default, you need to make sure <code>my-cron.php</code> is not publicly accessible. For example, you can add the following at the beginning of <code>my-cron.php</code> file to give access to <code>localhost</code> only:</p>\n\n<pre><code>$allowed_ip = '127.0.0.1';\nif( $allowed_ip !== $_SERVER['REMOTE_ADDR'] ) {\n exit( 0 );\n}\n</code></pre>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258694", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114434/" ]
I want to write a cronjob for myself. But I need to get access to `WP_Query` and the permissions to delete posts etc. My question now is, how can I include the `WP_Query` function to my own PHP file and do I need to edit or change some permissions in order to delete or create posts with that cronjob?
Load WordPress in custom PHP Script: ==================================== You need to load essential WordPress core functionality in your custom PHP script for `WP_Query` to work properly. For example, let's say you have a custom PHP file named `my-cron.php` and WordPress is installed in the web root, like this: ``` public_html/ index.php my-cron.php <-- wp-load.php wp-settings.php ... wp-admin/ wp-content/ wp-includes/ ``` In this setup, if you want to use `WP_Query` in `my-cron.php` file, you need to load the `wp-load.php` file. So in `my-cron.php` file you need to have the following CODE: ``` if ( ! defined('ABSPATH') ) { /** Set up WordPress environment */ require_once( dirname( __FILE__ ) . '/wp-load.php' ); } ``` Access WP\_Query: ================= At this point, you'll have the access to `WP_Query`, so you can use it like this: ``` // simply selecting posts with category name "wordpress" $the_query = new WP_Query( array( 'category_name' => 'wordpress' ) ); if ( $the_query->have_posts() ) { echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; } else { echo "No post found for category named wordpress"; } ``` Delete Posts: ============= However, WP\_Query doesn't have delete function. For that you'll either need to use the [`wp_delete_post()`](https://developer.wordpress.org/reference/functions/wp_delete_post/) function or [`WPDB`](https://developer.wordpress.org/reference/classes/wpdb/) class. Using `wp_delete_post()` is recommended as it'll take care of many dependencies, however, if you need more control, then you may use `WPDB` class or `$wpdb` global variable, but be careful if you choose that path. For example, the following CODE will delete the post with ID `1`: ``` $deleted = wp_delete_post( 1 ); if( $deleted === false ) { echo "Couldn't delete Post with ID=1"; } else { echo "Deleted Post with ID=1"; } ``` Of course you can combine `WP_Query` with `wp_delete_post` to find and delete posts that meet specific criteria. Setup Cron: =========== Once you are done writing the custom PHP script, you need to [setup cron job](https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/#mac-os-x-and-linux) to run as a HTTP request, like the following: ``` 5 * * * * wget -q -O - http://your-domain.com/my-cron.php ``` Security: ========= Since accessing `WP_Query` or `wp_delete_post` function **doesn't require any authentication** (or permission) by default, you need to make sure `my-cron.php` is not publicly accessible. For example, you can add the following at the beginning of `my-cron.php` file to give access to `localhost` only: ``` $allowed_ip = '127.0.0.1'; if( $allowed_ip !== $_SERVER['REMOTE_ADDR'] ) { exit( 0 ); } ```
258,700
<p>It's since 1 month ago, every day we'll receive some tens of new user registration with username containing like <code>YggrnCyhorgeVH</code> or <code>AurizarCyhorgeVH</code>, etc..</p> <p>Ip and user agent are different every time, so I thinked to avoid user registration with this name.</p> <p><strong>Is there a hook/action/filter where to intercept the user registration and deny it?</strong></p> <p>PLEASE do not suggests plugin/captcha or others. I made a specific question. </p>
[ { "answer_id": 258721, "author": "Kristoffer M", "author_id": 113286, "author_profile": "https://wordpress.stackexchange.com/users/113286", "pm_score": 0, "selected": false, "text": "<p>Get spam filters for your site - captcha, Wordfence etc. General security helps against stuff like this.</p>\n" }, { "answer_id": 258744, "author": "Juraj.Lorinc", "author_id": 67602, "author_profile": "https://wordpress.stackexchange.com/users/67602", "pm_score": 2, "selected": true, "text": "<p>Following code should work for you, but I can not guarantee that because your form is so heavily (and badly) customized. I have tested it on not customized registration form and it worked just fine.</p>\n\n<pre><code>function cyhorge_check_fields( $errors, $sanitized_user_login, $user_email ) {\n\n if ( preg_match('/(CyhorgeVH)/', $sanitized_user_login ) ) {\n $errors-&gt;add( 'username_error', __( '&lt;strong&gt;ERROR&lt;/strong&gt;: User contains CyhorgeVH string.', 'my_textdomain' ) );\n }\n\n return $errors;\n}\n\nadd_filter( 'registration_errors', 'cyhorge_check_fields', 10, 3 );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_errors\" rel=\"nofollow noreferrer\">SOURCE</a></p>\n\n<p><strong>EDIT:</strong> Another possible solution:</p>\n\n<pre><code>function prevent_cyhorge_user( $user_login, $user_email, $errors ) {\n\n if ( strpos( $user_login, 'CyhorgeVH' ) ) {\n $errors-&gt;add( 'username_error', __( '&lt;strong&gt;ERROR&lt;/strong&gt;: User contains CyhorgeVH string.', 'my_textdomain' ) );\n }\n\n}\n\nadd_action( 'register_post', 'prevent_cyhorge_user', 10, 3 );\n</code></pre>\n\n<p>Notice that the second function is using <code>strpos</code> instead of <code>preg_match</code> which probably a bit faster, but <code>preg_match</code> provides more flexibility if needed.</p>\n\n<p>Both should work from either theme's <code>functions.php</code> or as a plugin.</p>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94289/" ]
It's since 1 month ago, every day we'll receive some tens of new user registration with username containing like `YggrnCyhorgeVH` or `AurizarCyhorgeVH`, etc.. Ip and user agent are different every time, so I thinked to avoid user registration with this name. **Is there a hook/action/filter where to intercept the user registration and deny it?** PLEASE do not suggests plugin/captcha or others. I made a specific question.
Following code should work for you, but I can not guarantee that because your form is so heavily (and badly) customized. I have tested it on not customized registration form and it worked just fine. ``` function cyhorge_check_fields( $errors, $sanitized_user_login, $user_email ) { if ( preg_match('/(CyhorgeVH)/', $sanitized_user_login ) ) { $errors->add( 'username_error', __( '<strong>ERROR</strong>: User contains CyhorgeVH string.', 'my_textdomain' ) ); } return $errors; } add_filter( 'registration_errors', 'cyhorge_check_fields', 10, 3 ); ``` [SOURCE](https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_errors) **EDIT:** Another possible solution: ``` function prevent_cyhorge_user( $user_login, $user_email, $errors ) { if ( strpos( $user_login, 'CyhorgeVH' ) ) { $errors->add( 'username_error', __( '<strong>ERROR</strong>: User contains CyhorgeVH string.', 'my_textdomain' ) ); } } add_action( 'register_post', 'prevent_cyhorge_user', 10, 3 ); ``` Notice that the second function is using `strpos` instead of `preg_match` which probably a bit faster, but `preg_match` provides more flexibility if needed. Both should work from either theme's `functions.php` or as a plugin.
258,707
<p>I want to add pagination in single page of custom post type.</p> <p>This is the code for single page (custom post type):</p> <pre><code>&lt;?php $paged = get_query_var('paged') ? get_query_var('paged') : 1; $args = array('post_type' =&gt; 'news', 'posts_per_page' =&gt; 1, 'paged' =&gt; $paged); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; // Loop &lt;?php endwhile; wp_reset_postdata(); ?&gt; &lt;div id="pagination" class="clearfix"&gt; &lt;?php next_posts_link( 'Older Entries', $loop-&gt;max_num_pages ); previous_posts_link( 'Newer Entries' );//posts_nav_link(); ?&gt; &lt;/div&gt; //// Function page code //// //// add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'news', array('labels' =&gt; array( 'name' =&gt; __('News', 'post type general name'), /* This is the Title of the Group */ 'singular_name' =&gt; __('News', 'post type singular name'), /* This is the individual type */ 'add_new' =&gt; __('Add New', 'custom post type item'), /* The add new menu item */ 'add_new_item' =&gt; __('Add New'), /* Add New Display Title */ 'edit' =&gt; __( 'Edit' ), /* Edit Dialog */ 'edit_item' =&gt; __('Edit'), /* Edit Display Title */ 'new_item' =&gt; __('New '), /* New Display Title */ 'view_item' =&gt; __('View'), /* View Display Title */ 'search_items' =&gt; __('Search news'), /* Search Custom Type Title */ 'not_found' =&gt; __('Nothing found in the Database.'), /* This displays if there are no entries yet */ 'not_found_in_trash' =&gt; __('Nothing found in Trash'), /* This displays if there is nothing in the trash */ 'parent_item_colon' =&gt; '' ), /* end of arrays */ 'description' =&gt; __( 'This is the example custom post type' ), /* Custom Type Description */ 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'exclude_from_search' =&gt; false, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'menu_position' =&gt; 2, /* this is what order you want it to appear in on the left hand side menu */ 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'rewrite' =&gt; array('slug' =&gt; 'news', 'with_front' =&gt; true ), 'has_archive' =&gt; true, /* the next one is important, it tells what's enabled in the post editor */ 'supports' =&gt; array( 'title', 'editor', 'thumbnail') ) ); } </code></pre>
[ { "answer_id": 258720, "author": "Svartbaard", "author_id": 112928, "author_profile": "https://wordpress.stackexchange.com/users/112928", "pm_score": 0, "selected": false, "text": "<p>The functions</p>\n\n<pre><code>next_posts_link\n</code></pre>\n\n<p>and</p>\n\n<pre><code>previous_posts_link\n</code></pre>\n\n<p>should be called before you reset the post data.</p>\n" }, { "answer_id": 258749, "author": "Dixita", "author_id": 114646, "author_profile": "https://wordpress.stackexchange.com/users/114646", "pm_score": 0, "selected": false, "text": "<p>Reset query after pagination link\nTry this:</p>\n\n<pre><code>&lt;?php\n $paged = get_query_var('paged') ? get_query_var('paged') : 1;\n $args = array('post_type' =&gt; 'news', 'posts_per_page' =&gt; 1, 'paged' =&gt; $paged);\n $loop = new WP_Query( $args );\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n?&gt;\n\n// Loop\n\n&lt;?php endwhile; ?&gt;\n\n&lt;div id=\"pagination\" class=\"clearfix\"&gt;\n &lt;?php next_posts_link( 'Older Entries', $loop-&gt;max_num_pages );\nprevious_posts_link( 'Newer Entries' );//posts_nav_link(); ?&gt;\n&lt;/div&gt;\n\n&lt;?php wp_reset_query(); ?&gt;\n</code></pre>\n" }, { "answer_id": 258760, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 0, "selected": false, "text": "<p><code>next_posts_link</code> and <code>previous_posts_link</code> both check <code>is_single</code> and prevent output in that case. They are intended for archive pages and will not work on singular views.</p>\n" }, { "answer_id": 352423, "author": "Firdaus Rudy", "author_id": 112977, "author_profile": "https://wordpress.stackexchange.com/users/112977", "pm_score": 1, "selected": false, "text": "<p>Don't need to start with a new Query in archive.php loop</p>\n\n<p>Only need to create a different loop file for the custom taxonomy and default loop post</p>\n\n<p>See here for more details <a href=\"https://wordpress.stackexchange.com/questions/226923/filtering-a-custom-post-type-by-custom-taxonomy-in-archive-template/352422#352422\">Filtering a custom post type by custom taxonomy in archive template</a></p>\n\n<p>example I have taxonomy \"service\"</p>\n\n<p>archive.php file</p>\n\n<pre><code>\n&lt;?php \nget_header();\n\nif (is_post_type_archive('service') || is_tax('services-category') || is_tax('services-tags')){\n get_template_part('my-loop-service'); // Get Loop for Taxonomy service\n} else {\n get_template_part('my-loop-post'); // Default Loop for Post\n\n}\n\n // Navigation\n echo '&lt;div id=\"my-navigation\"&gt;';\n the_posts_pagination( array(\n 'mid_size' =&gt; 2,\n 'prev_text' =&gt; __( 'Prev', 'text-domain' ),\n 'next_text' =&gt; __( 'Next', 'text-domain' ),\n ));\n echo '&lt;/div&gt;';\n\nget_footer(); \n?&gt;\n</code></pre>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258707", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112648/" ]
I want to add pagination in single page of custom post type. This is the code for single page (custom post type): ``` <?php $paged = get_query_var('paged') ? get_query_var('paged') : 1; $args = array('post_type' => 'news', 'posts_per_page' => 1, 'paged' => $paged); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> // Loop <?php endwhile; wp_reset_postdata(); ?> <div id="pagination" class="clearfix"> <?php next_posts_link( 'Older Entries', $loop->max_num_pages ); previous_posts_link( 'Newer Entries' );//posts_nav_link(); ?> </div> //// Function page code //// //// add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'news', array('labels' => array( 'name' => __('News', 'post type general name'), /* This is the Title of the Group */ 'singular_name' => __('News', 'post type singular name'), /* This is the individual type */ 'add_new' => __('Add New', 'custom post type item'), /* The add new menu item */ 'add_new_item' => __('Add New'), /* Add New Display Title */ 'edit' => __( 'Edit' ), /* Edit Dialog */ 'edit_item' => __('Edit'), /* Edit Display Title */ 'new_item' => __('New '), /* New Display Title */ 'view_item' => __('View'), /* View Display Title */ 'search_items' => __('Search news'), /* Search Custom Type Title */ 'not_found' => __('Nothing found in the Database.'), /* This displays if there are no entries yet */ 'not_found_in_trash' => __('Nothing found in Trash'), /* This displays if there is nothing in the trash */ 'parent_item_colon' => '' ), /* end of arrays */ 'description' => __( 'This is the example custom post type' ), /* Custom Type Description */ 'public' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'show_ui' => true, 'query_var' => true, 'menu_position' => 2, /* this is what order you want it to appear in on the left hand side menu */ 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => array('slug' => 'news', 'with_front' => true ), 'has_archive' => true, /* the next one is important, it tells what's enabled in the post editor */ 'supports' => array( 'title', 'editor', 'thumbnail') ) ); } ```
Don't need to start with a new Query in archive.php loop Only need to create a different loop file for the custom taxonomy and default loop post See here for more details [Filtering a custom post type by custom taxonomy in archive template](https://wordpress.stackexchange.com/questions/226923/filtering-a-custom-post-type-by-custom-taxonomy-in-archive-template/352422#352422) example I have taxonomy "service" archive.php file ``` <?php get_header(); if (is_post_type_archive('service') || is_tax('services-category') || is_tax('services-tags')){ get_template_part('my-loop-service'); // Get Loop for Taxonomy service } else { get_template_part('my-loop-post'); // Default Loop for Post } // Navigation echo '<div id="my-navigation">'; the_posts_pagination( array( 'mid_size' => 2, 'prev_text' => __( 'Prev', 'text-domain' ), 'next_text' => __( 'Next', 'text-domain' ), )); echo '</div>'; get_footer(); ?> ```
258,726
<p>I really read a lot of articles relating adding dynamic inline stylesheet. but this one drives me crazy. i have a simple dev setup. this is my global style:</p> <pre><code>function bootstrap_scripts_styles() { wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri().'/style.css', array(), '2016-07-18' ); } add_action( 'wp_enqueue_scripts', 'bootstrap_scripts_styles' ); </code></pre> <p>because i need to trigger custom styles from single.php, i added some sample code here:</p> <pre><code>$custom_css = ".intro { background: red; }"; wp_add_inline_style( 'custom-style', $custom_css ); </code></pre> <p>using this, nothing happens. i don't see any inline style in frontend code. But when i debug WP_Styles() and look for "custom-style" i can see, the style is being appended:</p> <pre><code>[custom-style] =&gt; _WP_Dependency Object ( [handle] =&gt; custom-style [src] =&gt; http://localhost/westerland/wp-content/themes/westerland/style.css [deps] =&gt; Array ( ) [ver] =&gt; 2013-07-18 [args] =&gt; all [extra] =&gt; Array ( [after] =&gt; Array ( [0] =&gt; .intro { background: red; } ) ) ) </code></pre> <p>so i wonder why it does not get printed?! i found a way to print it, but then, it gets printed in <code>&lt;body&gt;</code> instead right behind the <code>&lt;link&gt;</code> tag of global style:</p> <pre><code>$custom_css = ".intro { background: red; }"; wp_add_inline_style( 'custom-style', $custom_css ); WP_Styles()-&gt;print_inline_style("custom-style"); </code></pre> <p>so this feels a little bit "hacky" because i want this as clean as possible to appear in the <code>&lt;head&gt;</code> tag. is this some kind of bug? i am using latest WP.</p>
[ { "answer_id": 258724, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 2, "selected": false, "text": "<p>You need to first understand how WP theme hierarchy works , then only you will be able to find which file you need to define.</p>\n\n<p>Below is the URL to understand how WP theme hierarchy works.</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n" }, { "answer_id": 315607, "author": "Komu Stephen", "author_id": 151568, "author_profile": "https://wordpress.stackexchange.com/users/151568", "pm_score": 0, "selected": false, "text": "<p>My trick is not to move the button but create another button.</p>\n\n<pre><code> &lt;style&gt;\n/*remove the default button*/\n article p a{\n display: none\n }\n &lt;/style&gt;\n&lt;!---create a new button in the loop.php file with a link ---&gt;\n&lt;a href=\"&lt;?php the_permalink()?&gt;\"&gt;\n &lt;button class=\"btn btn-outline-info\"&gt;\n Read more\n &lt;/button&gt;\n &lt;/a&gt;\n</code></pre>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258726", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74101/" ]
I really read a lot of articles relating adding dynamic inline stylesheet. but this one drives me crazy. i have a simple dev setup. this is my global style: ``` function bootstrap_scripts_styles() { wp_enqueue_style( 'custom-style', get_stylesheet_directory_uri().'/style.css', array(), '2016-07-18' ); } add_action( 'wp_enqueue_scripts', 'bootstrap_scripts_styles' ); ``` because i need to trigger custom styles from single.php, i added some sample code here: ``` $custom_css = ".intro { background: red; }"; wp_add_inline_style( 'custom-style', $custom_css ); ``` using this, nothing happens. i don't see any inline style in frontend code. But when i debug WP\_Styles() and look for "custom-style" i can see, the style is being appended: ``` [custom-style] => _WP_Dependency Object ( [handle] => custom-style [src] => http://localhost/westerland/wp-content/themes/westerland/style.css [deps] => Array ( ) [ver] => 2013-07-18 [args] => all [extra] => Array ( [after] => Array ( [0] => .intro { background: red; } ) ) ) ``` so i wonder why it does not get printed?! i found a way to print it, but then, it gets printed in `<body>` instead right behind the `<link>` tag of global style: ``` $custom_css = ".intro { background: red; }"; wp_add_inline_style( 'custom-style', $custom_css ); WP_Styles()->print_inline_style("custom-style"); ``` so this feels a little bit "hacky" because i want this as clean as possible to appear in the `<head>` tag. is this some kind of bug? i am using latest WP.
You need to first understand how WP theme hierarchy works , then only you will be able to find which file you need to define. Below is the URL to understand how WP theme hierarchy works. <https://developer.wordpress.org/themes/basics/template-hierarchy/>
258,727
<p>I have created 15 post and assigned to the custom taxonomy. It is not displaying all the 15 post. It shows only 10 post.</p> <p>Please guide me. Thanks </p> <pre><code>wp_reset_query(); $args = array( 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'parent_login_gallery', 'field' =&gt; 'term_id', 'terms' =&gt; array($_REQUEST['term_id']), 'operator' =&gt; 'IN', 'public' =&gt; true, 'has_archive' =&gt; true, ), ) ); </code></pre>
[ { "answer_id": 258724, "author": "Aftab", "author_id": 64614, "author_profile": "https://wordpress.stackexchange.com/users/64614", "pm_score": 2, "selected": false, "text": "<p>You need to first understand how WP theme hierarchy works , then only you will be able to find which file you need to define.</p>\n\n<p>Below is the URL to understand how WP theme hierarchy works.</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a></p>\n" }, { "answer_id": 315607, "author": "Komu Stephen", "author_id": 151568, "author_profile": "https://wordpress.stackexchange.com/users/151568", "pm_score": 0, "selected": false, "text": "<p>My trick is not to move the button but create another button.</p>\n\n<pre><code> &lt;style&gt;\n/*remove the default button*/\n article p a{\n display: none\n }\n &lt;/style&gt;\n&lt;!---create a new button in the loop.php file with a link ---&gt;\n&lt;a href=\"&lt;?php the_permalink()?&gt;\"&gt;\n &lt;button class=\"btn btn-outline-info\"&gt;\n Read more\n &lt;/button&gt;\n &lt;/a&gt;\n</code></pre>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80578/" ]
I have created 15 post and assigned to the custom taxonomy. It is not displaying all the 15 post. It shows only 10 post. Please guide me. Thanks ``` wp_reset_query(); $args = array( 'tax_query' => array( array( 'taxonomy' => 'parent_login_gallery', 'field' => 'term_id', 'terms' => array($_REQUEST['term_id']), 'operator' => 'IN', 'public' => true, 'has_archive' => true, ), ) ); ```
You need to first understand how WP theme hierarchy works , then only you will be able to find which file you need to define. Below is the URL to understand how WP theme hierarchy works. <https://developer.wordpress.org/themes/basics/template-hierarchy/>
258,741
<p>How can I modify the slug for the default wp posts without affecting other posttypes? </p> <p>example: <code>www.example.com/slug-of-post/</code> should become <code>www.example.com/blog/slug-of-post/</code></p> <p>I made a few custom post types where I rewrote the slug by using <code>'rewrite' =&gt; array('slug' =&gt; 'portfolio'),</code> in the <code>function.php</code> file.</p> <p>Result: <code>www.example.com/post-type-slug/slug-of-post</code></p> <p>I need the same result but for the default posts.</p> <p>Thanks.</p>
[ { "answer_id": 258745, "author": "pouria", "author_id": 101909, "author_profile": "https://wordpress.stackexchange.com/users/101909", "pm_score": 2, "selected": false, "text": "<p>According to the docs: <a href=\"https://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Using_Permalinks</a> </p>\n\n<p>Go to settings -> permalinks -> custom structure </p>\n\n<p>and change that to: <code>/blog/%postname%/</code></p>\n\n<p>But please make sure that in your custom post types definition, (<code>register_post_type</code>) set </p>\n\n<pre><code>'rewrite' =&gt; array( 'with_front' =&gt; false ),\n</code></pre>\n\n<p>unless the URL of all of your custom post types will be prefixed by /blog/</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>As @rudtek mentioned in the comment, after your set <code>'with_front' =&gt; false</code>, you must go to settings->permalinks and hit save again to flush rewrite rules. (This is the solution for many permalink issues) </p>\n" }, { "answer_id": 378593, "author": "geoff", "author_id": 44304, "author_profile": "https://wordpress.stackexchange.com/users/44304", "pm_score": 0, "selected": false, "text": "<p>In extension to <a href=\"https://wordpress.stackexchange.com/a/258745\">pooria's answer above</a>:</p>\n<p>If you are using the CPT UI plugin to manage your custom post types, there is a dropdown to toggle the <code>with_front</code> option:</p>\n<p><a href=\"https://i.stack.imgur.com/CIAZc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CIAZc.png\" alt=\"&quot;With Front&quot; option on CPT UI plugin\" /></a></p>\n<p>By default this option is set to True so you will have to change it for all post types for which you want to start the permalink with your site URL.</p>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258741", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112184/" ]
How can I modify the slug for the default wp posts without affecting other posttypes? example: `www.example.com/slug-of-post/` should become `www.example.com/blog/slug-of-post/` I made a few custom post types where I rewrote the slug by using `'rewrite' => array('slug' => 'portfolio'),` in the `function.php` file. Result: `www.example.com/post-type-slug/slug-of-post` I need the same result but for the default posts. Thanks.
According to the docs: <https://codex.wordpress.org/Using_Permalinks> Go to settings -> permalinks -> custom structure and change that to: `/blog/%postname%/` But please make sure that in your custom post types definition, (`register_post_type`) set ``` 'rewrite' => array( 'with_front' => false ), ``` unless the URL of all of your custom post types will be prefixed by /blog/ **UPDATE:** As @rudtek mentioned in the comment, after your set `'with_front' => false`, you must go to settings->permalinks and hit save again to flush rewrite rules. (This is the solution for many permalink issues)
258,751
<p>I need to create a custom WordPress admin interface for a client. I want to completely disable the sticky post feature from admin area.</p> <p>I found some posts on the internet that suggest to hide the checkbox using css, but I would really like to disable that feature both from edit and from quick edit screen.</p> <p>Any ideas?</p>
[ { "answer_id": 258763, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>In addition to CSS you could try to unstick each post as soon as it has been made sticky (untested):</p>\n\n<pre><code>add_action( 'post_stuck', function( $post_id )\n{\n unstick_post( $post_id );\n} );\n</code></pre>\n\n<p>If you're looking for another approach, than hiding it from the UI with CSS, then consider using <strong>custom post types</strong> instead of the <code>post</code> post type. </p>\n\n<p>As far as I remember the <em>sticky</em> UI feature is only supported by the <code>post</code> post type. At least a quick look at the posts list table class, shows a check like this one: </p>\n\n<pre><code>if ( 'post' === $post_type &amp;&amp; $sticky_posts = get_option( 'sticky_posts' ) ) {\n</code></pre>\n\n<p>But not using the <code>post</code> post type, might not be suitable in many cases, and it might need further adjustments for your site.</p>\n" }, { "answer_id": 258791, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>you could add this code:</p>\n\n<pre><code>// Hide sticky posts\nadd_action( 'admin_print_styles', 'hide_sticky_option' );\nfunction hide_sticky_option() {\nglobal $post_type, $pagenow;\nif( 'post.php' != $pagenow &amp;&amp; 'post-new.php' != $pagenow &amp;&amp; 'edit.php' != $pagenow )\n return;\n?&gt;\n&lt;style type=\"text/css\"&gt;#sticky-span { display:none!important }\n.quick-edit-row .inline-edit-col-right div.inline-edit-col &gt; :last-child &gt; label.alignleft:last-child{ display:none!important; }&lt;/style&gt;\n&lt;?php\n}\n</code></pre>\n\n<p>This works great for me.</p>\n" }, { "answer_id": 258959, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 0, "selected": false, "text": "<p>The best and most optimal solution is to simply \"ignore\" sticky posts on all queries which can be done with this code:</p>\n\n<pre><code>add_filter( 'pre_get_posts', function( $query ) {\n if ( ! is_admin() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'ignore_sticky_posts', 1 );\n }\n} );\n</code></pre>\n\n<p>Of course the user can still click the checkbox but it won't actually do anything so it won't matter. But here is a good article showing how to hide with CSS if wanted - <a href=\"https://wordpress.stackexchange.com/questions/10676/is-there-a-way-to-disable-the-sticky-posts-feature\">Is there a way to disable the sticky posts feature?</a></p>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258751", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85556/" ]
I need to create a custom WordPress admin interface for a client. I want to completely disable the sticky post feature from admin area. I found some posts on the internet that suggest to hide the checkbox using css, but I would really like to disable that feature both from edit and from quick edit screen. Any ideas?
In addition to CSS you could try to unstick each post as soon as it has been made sticky (untested): ``` add_action( 'post_stuck', function( $post_id ) { unstick_post( $post_id ); } ); ``` If you're looking for another approach, than hiding it from the UI with CSS, then consider using **custom post types** instead of the `post` post type. As far as I remember the *sticky* UI feature is only supported by the `post` post type. At least a quick look at the posts list table class, shows a check like this one: ``` if ( 'post' === $post_type && $sticky_posts = get_option( 'sticky_posts' ) ) { ``` But not using the `post` post type, might not be suitable in many cases, and it might need further adjustments for your site.
258,754
<p>When using FormData with Wordpress Admin Ajax I'm only getting back a '0' response. Usually this is because there's no action, however I'm including the action and still have the problem. I've seen similar questions on here but they all assume jQuery is being used, and in my case it isn't.</p> <p>Javascript:</p> <pre><code> if ($this.valid()) { var form_data = new FormData(form); form_data.append('security', WP.nonce); form_data.append('action', form.action); console.log(form.action); // console shows http://test.dev/newsletter_signup u.jax.post(WP.ajax, form_data, onSent); function onSent(result) { if (result.success) { $this.html('&lt;p class="form-sent"&gt;' + $this.data('success') + '&lt;/p&gt;'); } else { $this.html('&lt;p class="form-sent"&gt;' + result.data + '&lt;/p&gt;'); } } } </code></pre> <p>PHP:</p> <pre><code>add_action('wp_ajax_newsletter_signup', 'newsletter_signup'); add_action('wp_ajax_nopriv_newsletter_signup', 'newsletter_signup'); </code></pre> <p>HTML:</p> <pre><code>&lt;form action="newsletter_signup" class="newsletter-signup js-process-form" autocomplete="off"&gt; &lt;div class="field"&gt; &lt;label for="newsletter-email" class="field__label"&gt;Your Email Address&lt;/label&gt; &lt;input type="email" class="field__input" name="email-address" id="newsletter-email" required data-msg-required="We need to know your email address" value="[email protected]"&gt; &lt;button type="submit" class="field__button"&gt;submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>The only problem I can see is that the action is getting the domain appended before it. If I do this with jquery ajax, it works fine, so the code seems down to the javascript. I can provide the ajax functions but they're pretty generic.</p> <p>If there's any more code you need, let me know.</p> <p>Thanks.</p> <p><strong>Edit for comments:</strong></p> <p>I have tried changing the form to the hidden action input field as mentioned in the comments:</p> <pre><code>&lt;form action=""&gt; &lt;input type="hidden" name="action" value="newsletter_signup"/&gt; &lt;div class="field"&gt; &lt;label&gt;Your Email Address&lt;/label&gt; &lt;input type="email" name="email-address"&gt; &lt;button type="submit"&gt;submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>This is the formdata sent on submit:</p> <pre><code>------WebKitFormBoundarycskAgc8KcinCzpoG Content-Disposition: form-data; name:"action" newsletter_signup ------WebKitFormBoundarycskAgc8KcinCzpoG Content-Disposition: form-data; name="email-address" [email protected] ------WebKitFormBoundarycskAgc8KcinCzpoG-- </code></pre> <p>And it's being sent to: </p> <p><code>http://test.dev/wp-admin/admin-ajax.php</code></p> <p><strong>Edit #2:</strong></p> <p>Sending a get request like:</p> <pre><code>u.jax.get('http://test.dev/wp-admin/admin-ajax.php?action=newsletter_si‌​gnup&amp;email-address=t‌​[email protected]', function(s){ console.log(s) }); </code></pre> <p>Also results in a response of <code>0</code>.</p> <p>Here are my js ajax functions, incase it provides some clarity:</p> <pre><code>// ===== Ajax Utilities // Handles Ajax Responses function _handleResponse(request, success) { request.onreadystatechange = function() { if (request.status &gt;= 200 &amp;&amp; request.status &lt; 400) { if (typeof request.responseText == 'string') { data = request.responseText; } else { data = JSON.parse(request.responseText); } success(data); } else { return request.status + ' failed request: '+ JSON.parse(request.responseText); } }; request.onerror = function() { return request.status + ' failed request: '+ JSON.parse(request.responseText); }; } // Ajax GET &amp; POST u.jax = { get: function(url, success) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.send(null); _handleResponse(request, success); }, post: function(url, data, success) { var request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(data); _handleResponse(request, success); } }; </code></pre> <p>Postman Headers for the get request:</p> <pre><code>Cache-Control →no-cache, must-revalidate, max-age=0 Connection →Keep-Alive Content-Length →1 Content-Type →text/html; charset=UTF-8 Date →Fri, 03 Mar 2017 16:16:54 GMT Expires →Wed, 11 Jan 1984 05:00:00 GMT Keep-Alive →timeout=5, max=100 Server →Apache/2.4.20 (Unix) PHP/5.5.35 mod_wsgi/3.5 Python/3.5.1 OpenSSL/1.0.1p X-Content-Type-Options →nosniff X-Frame-Options →SAMEORIGIN X-Powered-By →PHP/5.5.35 X-Robots-Tag →noindex </code></pre>
[ { "answer_id": 258779, "author": "Spartacus", "author_id": 32329, "author_profile": "https://wordpress.stackexchange.com/users/32329", "pm_score": 1, "selected": false, "text": "<p>FormData is processing the action of your form tag as part of the form data, when that's not what you want to send to admin-ajax.php. Try to find another way to send 'newsletter_signup' as the action to admin-ajax.php, mainly by constructing your own array:</p>\n\n<pre><code>var form_data = new FormData(form);\n form_data.append('security', WP.nonce);\n form_data.append('value', form.value);\n // etc. etc., for each value you want to send\n\nvar formData = {\n\n action: 'newsletter_signup',\n data: form_data\n\n}\n\nu.jax.post(WP.ajax, formData, onSent);\n</code></pre>\n\n<p>Also, what's sending the 0? Is it admin-ajax.php, or is it a <code>die()</code> somewhere in your php script that's processing this form data?</p>\n" }, { "answer_id": 259021, "author": "evu", "author_id": 51164, "author_profile": "https://wordpress.stackexchange.com/users/51164", "pm_score": 3, "selected": true, "text": "<p>So it turns out the only problem was the header content type.</p>\n\n<p>By removing\n<code>request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');</code> and just leaving it out, it worked fine. That's also with the form action being grabbed and appended.</p>\n\n<p>Ajax call:</p>\n\n<pre><code>var formData = new FormData(form);\nformData.append('security', WP.nonce);\nformData.append('action', form.getAttribute('action'));\n\nu.jax.post(WP.ajax, formData, onSent);\n</code></pre>\n\n<p>Ajax Function:</p>\n\n<pre><code>u.jax.post = function(url, data, success) {\n var request = new XMLHttpRequest();\n\n request.open('POST', url, true);\n request.send(data);\n\n request.onreadystatechange = function() {\n if (request.readyState === 4) {\n\n if (typeof request.responseText == 'string') {\n data = request.responseText;\n } else {\n data = JSON.parse(request.responseText);\n }\n\n success(data);\n return;\n\n }\n };\n}\n</code></pre>\n\n<p>Form:</p>\n\n<pre><code>&lt;form action=\"newsletter_signup\"&gt;\n\n &lt;div class=\"field\"&gt;\n &lt;label&gt;Your Email Address&lt;/label&gt;\n &lt;input type=\"email\" name=\"email-address\"&gt;\n &lt;button type=\"submit\"&gt;submit&lt;/button&gt;\n &lt;/div&gt;\n\n&lt;/form&gt;\n</code></pre>\n\n<p>PHP:</p>\n\n<pre><code>function newsletter_signup(){\n\n // Get the email address\n $email = sanitize_email($_POST['email-address']);\n\n // Do what you wish with the email address.\n\n //Setup the data to send back\n $data = array();\n\n // json encode the data to send back\n echo json_encode($data);\n exit;\n\n}\n\nadd_action('wp_ajax_newsletter_signup', 'newsletter_signup');\nadd_action('wp_ajax_nopriv_newsletter_signup', 'newsletter_signup');\n</code></pre>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258754", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51164/" ]
When using FormData with Wordpress Admin Ajax I'm only getting back a '0' response. Usually this is because there's no action, however I'm including the action and still have the problem. I've seen similar questions on here but they all assume jQuery is being used, and in my case it isn't. Javascript: ``` if ($this.valid()) { var form_data = new FormData(form); form_data.append('security', WP.nonce); form_data.append('action', form.action); console.log(form.action); // console shows http://test.dev/newsletter_signup u.jax.post(WP.ajax, form_data, onSent); function onSent(result) { if (result.success) { $this.html('<p class="form-sent">' + $this.data('success') + '</p>'); } else { $this.html('<p class="form-sent">' + result.data + '</p>'); } } } ``` PHP: ``` add_action('wp_ajax_newsletter_signup', 'newsletter_signup'); add_action('wp_ajax_nopriv_newsletter_signup', 'newsletter_signup'); ``` HTML: ``` <form action="newsletter_signup" class="newsletter-signup js-process-form" autocomplete="off"> <div class="field"> <label for="newsletter-email" class="field__label">Your Email Address</label> <input type="email" class="field__input" name="email-address" id="newsletter-email" required data-msg-required="We need to know your email address" value="[email protected]"> <button type="submit" class="field__button">submit</button> </div> </form> ``` The only problem I can see is that the action is getting the domain appended before it. If I do this with jquery ajax, it works fine, so the code seems down to the javascript. I can provide the ajax functions but they're pretty generic. If there's any more code you need, let me know. Thanks. **Edit for comments:** I have tried changing the form to the hidden action input field as mentioned in the comments: ``` <form action=""> <input type="hidden" name="action" value="newsletter_signup"/> <div class="field"> <label>Your Email Address</label> <input type="email" name="email-address"> <button type="submit">submit</button> </div> </form> ``` This is the formdata sent on submit: ``` ------WebKitFormBoundarycskAgc8KcinCzpoG Content-Disposition: form-data; name:"action" newsletter_signup ------WebKitFormBoundarycskAgc8KcinCzpoG Content-Disposition: form-data; name="email-address" [email protected] ------WebKitFormBoundarycskAgc8KcinCzpoG-- ``` And it's being sent to: `http://test.dev/wp-admin/admin-ajax.php` **Edit #2:** Sending a get request like: ``` u.jax.get('http://test.dev/wp-admin/admin-ajax.php?action=newsletter_si‌​gnup&email-address=t‌​[email protected]', function(s){ console.log(s) }); ``` Also results in a response of `0`. Here are my js ajax functions, incase it provides some clarity: ``` // ===== Ajax Utilities // Handles Ajax Responses function _handleResponse(request, success) { request.onreadystatechange = function() { if (request.status >= 200 && request.status < 400) { if (typeof request.responseText == 'string') { data = request.responseText; } else { data = JSON.parse(request.responseText); } success(data); } else { return request.status + ' failed request: '+ JSON.parse(request.responseText); } }; request.onerror = function() { return request.status + ' failed request: '+ JSON.parse(request.responseText); }; } // Ajax GET & POST u.jax = { get: function(url, success) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.send(null); _handleResponse(request, success); }, post: function(url, data, success) { var request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(data); _handleResponse(request, success); } }; ``` Postman Headers for the get request: ``` Cache-Control →no-cache, must-revalidate, max-age=0 Connection →Keep-Alive Content-Length →1 Content-Type →text/html; charset=UTF-8 Date →Fri, 03 Mar 2017 16:16:54 GMT Expires →Wed, 11 Jan 1984 05:00:00 GMT Keep-Alive →timeout=5, max=100 Server →Apache/2.4.20 (Unix) PHP/5.5.35 mod_wsgi/3.5 Python/3.5.1 OpenSSL/1.0.1p X-Content-Type-Options →nosniff X-Frame-Options →SAMEORIGIN X-Powered-By →PHP/5.5.35 X-Robots-Tag →noindex ```
So it turns out the only problem was the header content type. By removing `request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');` and just leaving it out, it worked fine. That's also with the form action being grabbed and appended. Ajax call: ``` var formData = new FormData(form); formData.append('security', WP.nonce); formData.append('action', form.getAttribute('action')); u.jax.post(WP.ajax, formData, onSent); ``` Ajax Function: ``` u.jax.post = function(url, data, success) { var request = new XMLHttpRequest(); request.open('POST', url, true); request.send(data); request.onreadystatechange = function() { if (request.readyState === 4) { if (typeof request.responseText == 'string') { data = request.responseText; } else { data = JSON.parse(request.responseText); } success(data); return; } }; } ``` Form: ``` <form action="newsletter_signup"> <div class="field"> <label>Your Email Address</label> <input type="email" name="email-address"> <button type="submit">submit</button> </div> </form> ``` PHP: ``` function newsletter_signup(){ // Get the email address $email = sanitize_email($_POST['email-address']); // Do what you wish with the email address. //Setup the data to send back $data = array(); // json encode the data to send back echo json_encode($data); exit; } add_action('wp_ajax_newsletter_signup', 'newsletter_signup'); add_action('wp_ajax_nopriv_newsletter_signup', 'newsletter_signup'); ```
258,764
<p>Somewhere in the plugin class there is this hook :</p> <p><code>add_action( 'woocommerce_some_hook', array( $this, 'some_function') );</code></p> <p>it adds something I don't want there. In my functions.php in my theme, I have tried everything such as : <code>remove_action('woocommerce_some_hook','some_function');</code></p> <p>or</p> <pre><code>remove_action( 'woocommerce_some_hook', array('original_plugin_class', 'some_function',)); </code></pre> <p>but still, I simply can't remove the hook!</p>
[ { "answer_id": 258765, "author": "TrubinE", "author_id": 111011, "author_profile": "https://wordpress.stackexchange.com/users/111011", "pm_score": 0, "selected": false, "text": "<p>It is necessary to pass an instance in which the hook was set up</p>\n\n<pre><code>global $my_class;\nremove_action( 'woocommerce_some_hook', array( $my_class, 'some_function' ) );\n</code></pre>\n\n<p>make sure that the instance of the class is available</p>\n" }, { "answer_id": 258767, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": false, "text": "<p>One problem with the way WordPress handles hooks is that to remove a specific hook with an OOP callback, you must have access to the <em>exact same instance</em> of the class as when the callback was added. This is generally easy enough to handle in your own plugins/themes.</p>\n\n<p>However, it makes it nearly impossible to remove a hook from another plugin unless that developer globalized the instance of the class. If that's the case, then you can use the <code>global</code> keyword and remove the hook like normal. Another popular pattern is to use a singleton method to only allow one instance of the class.</p>\n\n<p>Unfortunately, it seems that a lot of plugins (including WC) initialize the class when the file is included. To further complicate things, they add hooks in the constructor of the class. This makes it extremely difficult to remove hooks.</p>\n\n<p>I've been working on a class that will remove a hook from the <code>$wp_filter</code> global variable if you know the Namespace\\Class and Method of the callback. I've done limited testing of the class, so use at your own risk, but it does work for me.</p>\n\n<p>Hopefully this will point you in right direction.</p>\n\n<pre><code>&lt;?php\n\nnamespace WPSE\\Q_258764;\n\n/**\n * Class for interacting with hooks\n */\n\nclass hooks {\n\n /**\n * @var Namespace of the hook\n *\n * @access protected\n * @since 0.2\n */\n protected $namespace;\n\n /**\n * Object constructor\n *\n * @param string $namespace The namespace of the hook. Optional.\n *\n * @access public\n * @since 0.2\n */\n public function __construct( $namespace = __NAMESPACE__ ) {\n $this-&gt;namespace = $namespace;\n }\n\n /**\n * Remove a hook from the $wp_filter global\n *\n * @param string $tag The hook which the callback is attached to\n * @param callable $callback The callback to remove\n * @param int $priority The priority of the callback\n *\n * @access public\n * @since 0.2\n *\n * @return bool Whether the filter was originally in the $wp_filter global\n */\n public function remove_hook( $tag, $callback, $priority = 10 ) {\n global $wp_filter;\n $tag_hooks = $wp_filter[ $tag ]-&gt;callbacks[ $priority ];\n foreach ( $tag_hooks as $the_tag =&gt; $the_callback ) {\n if( $this-&gt;parse_callback( $the_callback ) === $callback ) {\n return \\remove_filter( $tag, $the_callback[ 'function' ], $priority );\n }\n }\n return \\remove_filter( $tag, $callback, $priority );\n }\n\n /**\n * Trim backslash from string\n *\n * @param string $string\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function trim_backslash( $string ) {\n return trim( $string, '\\\\' );\n }\n\n /**\n * Remove the namespace from the string\n *\n * @param string $string\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function remove_namespace( $string ) {\n return str_ireplace( $this-&gt;namespace, '', $string );\n }\n\n /**\n * Get the class name of an object\n *\n * @param object $object\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function get_class( $object ) {\n return get_class( $object );\n }\n\n /**\n * Return the callback object\n *\n * @param array $callback\n *\n * @access protected\n * @since 0.2\n *\n * @return object\n */\n protected function callback_object( $callback ) {\n return $callback[ 'function' ][ 0 ];\n }\n\n /**\n * Return the callback method\n *\n * @param array $callback\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function callback_method( $callback ) {\n return $callback[ 'function' ][ 1 ];\n }\n\n /**\n * Return the class from the callback\n *\n * @param array $callback\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function get_class_from_callback( $callback ) {\n return $this-&gt;get_class( $this-&gt;callback_object( $callback ) );\n }\n\n /**\n * Wrapper for strtolower\n *\n * @param string $string\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function strtolower( $string ) {\n return strtolower( $string );\n }\n\n /**\n * Parse the callback into an array\n *\n * @param array $callback\n *\n * @access protected\n * @since 0.2\n *\n * @return array\n */\n protected function parse_callback( $callback ) {\n return is_array( $callback[ 'function' ] ) ?\n [ $this-&gt;class( $callback ), $this-&gt;method( $callback ) ] : false;\n }\n\n /**\n * Return the class of a callback\n *\n * @param array $callback\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function class( $callback ) {\n $class = $this-&gt;get_class_from_callback( $callback );\n $class = $this-&gt;strtolower( $class );\n $class = $this-&gt;remove_namespace( $class );\n return $this-&gt;trim_backslash( $class );\n }\n\n /**\n * Return the method of a callback\n *\n * @param array $callback\n *\n * @access protected\n * @since 0.2\n *\n * @return string\n */\n protected function method( $callback ) {\n return $callback[ 'function' ][ 1 ];\n }\n}\n</code></pre>\n\n<p>Edit: this will only work on WP versions greater than 4.7.</p>\n" }, { "answer_id": 260160, "author": "Vinoth Kumar", "author_id": 88946, "author_profile": "https://wordpress.stackexchange.com/users/88946", "pm_score": 0, "selected": false, "text": "<p>You can try,</p>\n\n<pre><code>remove_action( 'woocommerce_some_hook', array(new original_plugin_class(), 'some_function',));\n</code></pre>\n\n<p>you need to create the instance of the class when they are not globally created. Suppose if they have created the instance of the class some where, then you can use that like @TrubinE mentioned.</p>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258764", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111916/" ]
Somewhere in the plugin class there is this hook : `add_action( 'woocommerce_some_hook', array( $this, 'some_function') );` it adds something I don't want there. In my functions.php in my theme, I have tried everything such as : `remove_action('woocommerce_some_hook','some_function');` or ``` remove_action( 'woocommerce_some_hook', array('original_plugin_class', 'some_function',)); ``` but still, I simply can't remove the hook!
One problem with the way WordPress handles hooks is that to remove a specific hook with an OOP callback, you must have access to the *exact same instance* of the class as when the callback was added. This is generally easy enough to handle in your own plugins/themes. However, it makes it nearly impossible to remove a hook from another plugin unless that developer globalized the instance of the class. If that's the case, then you can use the `global` keyword and remove the hook like normal. Another popular pattern is to use a singleton method to only allow one instance of the class. Unfortunately, it seems that a lot of plugins (including WC) initialize the class when the file is included. To further complicate things, they add hooks in the constructor of the class. This makes it extremely difficult to remove hooks. I've been working on a class that will remove a hook from the `$wp_filter` global variable if you know the Namespace\Class and Method of the callback. I've done limited testing of the class, so use at your own risk, but it does work for me. Hopefully this will point you in right direction. ``` <?php namespace WPSE\Q_258764; /** * Class for interacting with hooks */ class hooks { /** * @var Namespace of the hook * * @access protected * @since 0.2 */ protected $namespace; /** * Object constructor * * @param string $namespace The namespace of the hook. Optional. * * @access public * @since 0.2 */ public function __construct( $namespace = __NAMESPACE__ ) { $this->namespace = $namespace; } /** * Remove a hook from the $wp_filter global * * @param string $tag The hook which the callback is attached to * @param callable $callback The callback to remove * @param int $priority The priority of the callback * * @access public * @since 0.2 * * @return bool Whether the filter was originally in the $wp_filter global */ public function remove_hook( $tag, $callback, $priority = 10 ) { global $wp_filter; $tag_hooks = $wp_filter[ $tag ]->callbacks[ $priority ]; foreach ( $tag_hooks as $the_tag => $the_callback ) { if( $this->parse_callback( $the_callback ) === $callback ) { return \remove_filter( $tag, $the_callback[ 'function' ], $priority ); } } return \remove_filter( $tag, $callback, $priority ); } /** * Trim backslash from string * * @param string $string * * @access protected * @since 0.2 * * @return string */ protected function trim_backslash( $string ) { return trim( $string, '\\' ); } /** * Remove the namespace from the string * * @param string $string * * @access protected * @since 0.2 * * @return string */ protected function remove_namespace( $string ) { return str_ireplace( $this->namespace, '', $string ); } /** * Get the class name of an object * * @param object $object * * @access protected * @since 0.2 * * @return string */ protected function get_class( $object ) { return get_class( $object ); } /** * Return the callback object * * @param array $callback * * @access protected * @since 0.2 * * @return object */ protected function callback_object( $callback ) { return $callback[ 'function' ][ 0 ]; } /** * Return the callback method * * @param array $callback * * @access protected * @since 0.2 * * @return string */ protected function callback_method( $callback ) { return $callback[ 'function' ][ 1 ]; } /** * Return the class from the callback * * @param array $callback * * @access protected * @since 0.2 * * @return string */ protected function get_class_from_callback( $callback ) { return $this->get_class( $this->callback_object( $callback ) ); } /** * Wrapper for strtolower * * @param string $string * * @access protected * @since 0.2 * * @return string */ protected function strtolower( $string ) { return strtolower( $string ); } /** * Parse the callback into an array * * @param array $callback * * @access protected * @since 0.2 * * @return array */ protected function parse_callback( $callback ) { return is_array( $callback[ 'function' ] ) ? [ $this->class( $callback ), $this->method( $callback ) ] : false; } /** * Return the class of a callback * * @param array $callback * * @access protected * @since 0.2 * * @return string */ protected function class( $callback ) { $class = $this->get_class_from_callback( $callback ); $class = $this->strtolower( $class ); $class = $this->remove_namespace( $class ); return $this->trim_backslash( $class ); } /** * Return the method of a callback * * @param array $callback * * @access protected * @since 0.2 * * @return string */ protected function method( $callback ) { return $callback[ 'function' ][ 1 ]; } } ``` Edit: this will only work on WP versions greater than 4.7.
258,786
<p>I have two fields in wp_posts table that <code>wp_update_post()</code> seems to be unable to change. I'm trying to use the following code:</p> <pre><code>$echo $group_access; $echo $tag_list; $my_post = array( 'ID' =&gt; 12095, 'post_title' =&gt; 'Test Title', 'post_content' =&gt; 'Test Content', 'group_access' =&gt; $group_access, 'tag_list' =&gt; $tag_list, ); // Update the post into the database $post_id = wp_update_post( $my_post, true ); if (is_wp_error($post_id)) { $errors = $post_id-&gt;get_error_messages(); foreach ($errors as $error) { echo $error; } } </code></pre> <p>The <code>$group_access</code> and <code>$tag_list</code> variables echo the correct values. The <code>post_title</code> and <code>post_content</code> update correctly. <code>group_access</code> and <code>tag_list</code> do not update, and there is no error either. </p> <p>Naturally, I've checked the table and <code>group_access</code> and <code>tag_list</code> are the correct column headers.</p> <p>I'm baffled why it doesn't work. Is <code>wp_update_post()</code> unable to change columns that are not part of the default WP install? Is it possibly a datatype thing (e.g. I should be passing an array or integer, but I'm passing a string)?</p>
[ { "answer_id": 258787, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>You are correct; WordPress will not update custom database columns using <code>wp_update_post()</code> or <code>wp_insert_post()</code>. Instead of creating custom database columns, consider using post meta and/or taxonomy APIs. </p>\n\n<p>If you must altar the <code>wp_posts</code> table, you will need to update your custom columns on your own and you may run into issues with various other plugins who don't take the custom database columns into account.</p>\n" }, { "answer_id": 258788, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data\" rel=\"nofollow noreferrer\"><code>wp_insert_post_data</code></a> fires almost immediately before the post data is inserted into the database. The only thing that happens after this is that the $data is <code>wp_unslash()</code>. You should be able to use this filter to compare the $postarr you sent wp_update_post with the $postarr that is passed to this filter. If the two are different, then you can format the $data before it's inserted into the database.</p>\n\n<p>I quickly mocked this up. Haven't tested it, but it should work with minor modifications.</p>\n\n<p>In class-wpse-258786.php:</p>\n\n<pre><code>class wpse_258786 {\n protected $postarr;\n public function __construct( $postarr ) {\n $this-&gt;postarr = $postarr;\n }\n public function insert_post_data( $data, $postarr ) {\n //* Make sure this is added each time before each post\n remove_action( 'wp_insert_post_data', [ $this , 'insert_post_data' ] , 10 );\n\n if( $postarr !== $this-&gt;postarr ) {\n //* Format the $data to insert into table\n }\n return $data;\n }\n}\n</code></pre>\n\n<p>in your-file.php</p>\n\n<pre><code>include_once( PATH_TO . 'class-wpse-258786.php' );\n\n...\n\n$echo $group_access;\n$echo $tag_list;\n$my_post = array(\n 'ID' =&gt; 12095, \n 'post_title' =&gt; 'Test Title',\n 'post_content' =&gt; 'Test Content', \n 'group_access' =&gt; $group_access,\n 'tag_list' =&gt; $tag_list,\n );\n\n//* Filter the post data before inserting into database\nadd_action( 'wp_insert_post_data',\n [ new wpse_258786( $my_post ), 'insert_post_data' ], 10, 2 );\n\n// Update the post into the database\n$post_id = wp_update_post( $my_post, true );\n</code></pre>\n\n<hr>\n\n<p>Edit to add:\nWhat I would do would be to place the class in a separate file, include it once, and then add the filter to the class. Then right before you <code>wp_update_post()</code> add the filter with the post data in the constructor. When the hook fires, then you can remove the filter to make sure it doesn't fire more than once.</p>\n\n<p>In response to your comment, you <em>could</em> use $wpdb, and in fact, that's how <code>wp_insert_post()</code> does it. The great thing about using the <code>wp_insert_post()</code> abstraction is that it introduces a lot of action and filter hooks that we can use to modify the data before it's entered into the database. Check out the <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-includes/post.php#L3013\" rel=\"nofollow noreferrer\"><code>wp_insert_post()</code></a> function on trac.</p>\n" } ]
2017/03/03
[ "https://wordpress.stackexchange.com/questions/258786", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38365/" ]
I have two fields in wp\_posts table that `wp_update_post()` seems to be unable to change. I'm trying to use the following code: ``` $echo $group_access; $echo $tag_list; $my_post = array( 'ID' => 12095, 'post_title' => 'Test Title', 'post_content' => 'Test Content', 'group_access' => $group_access, 'tag_list' => $tag_list, ); // Update the post into the database $post_id = wp_update_post( $my_post, true ); if (is_wp_error($post_id)) { $errors = $post_id->get_error_messages(); foreach ($errors as $error) { echo $error; } } ``` The `$group_access` and `$tag_list` variables echo the correct values. The `post_title` and `post_content` update correctly. `group_access` and `tag_list` do not update, and there is no error either. Naturally, I've checked the table and `group_access` and `tag_list` are the correct column headers. I'm baffled why it doesn't work. Is `wp_update_post()` unable to change columns that are not part of the default WP install? Is it possibly a datatype thing (e.g. I should be passing an array or integer, but I'm passing a string)?
You are correct; WordPress will not update custom database columns using `wp_update_post()` or `wp_insert_post()`. Instead of creating custom database columns, consider using post meta and/or taxonomy APIs. If you must altar the `wp_posts` table, you will need to update your custom columns on your own and you may run into issues with various other plugins who don't take the custom database columns into account.
258,806
<p>Google Adsense requires its activation code to be pasted right after the <code>&lt;head&gt;</code> tag of a site.</p> <p>However, I'm using a WordPress child theme.</p> <p>How can I paste my Google Adsense code in a child theme?</p>
[ { "answer_id": 258812, "author": "Irfan Modan", "author_id": 65452, "author_profile": "https://wordpress.stackexchange.com/users/65452", "pm_score": -1, "selected": false, "text": "<p>Use wp_head hook in functions.php</p>\n\n<pre><code>add_action('wp_head','add_adsense');\n</code></pre>\n" }, { "answer_id": 258817, "author": "nyedidikeke", "author_id": 105480, "author_profile": "https://wordpress.stackexchange.com/users/105480", "pm_score": 2, "selected": false, "text": "<p>You can easily put your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site by using either of these methods in your <code>functions.php</code> file or by creating a plugin for that purpose:</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is stored within in your plugins directory, under the\n * the file named: gads.js, which contains your Google Adsense Code.\n * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js\n */\nfunction load_my_google_adsense_code() {\n wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true );\n}\nadd_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' );\n</code></pre>\n\n<p>Alternatively, you can include it directly as part of your function as below;</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is contained directly in your function.\n */\nfunction load_my_google_adsense_code() {\n ?&gt;\n &lt;script&gt;\n // Your Google Adsense Code here.\n &lt;/script&gt;\n &lt;?php\n}\nadd_action('wp_head', 'load_my_google_adsense_code');\n</code></pre>\n\n<p><em>Please note:</em></p>\n\n<p>The two (2) approaches above will enable you to have your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site, usually right before <code>&lt;/head&gt;</code>, but this is really theme dependent as it depends on the placement of the <code>wp_head()</code> hook within the <code>header.php</code>.</p>\n\n<p>Its generally recommended to have the <code>&lt;?php wp_head(); ?&gt;</code> declaration before the <code>&lt;/head&gt;</code> which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&gt;&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Other contents here --&gt;\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n &lt;!-- Other contents may follow --&gt;\n</code></pre>\n\n<p>As such, the options provided above will work as <em>Google Adsense requires, per your OP</em>, should your the <code>wp_head()</code> hook of your theme satisfy that condition: occurring right below your <code>&lt;head&gt;</code> element.</p>\n\n<p>Should that not be the case and you still need to achieve this as <em>Google Adsense requires</em>, you will need to directly edit your <code>header.php</code> file for that purpose, either:</p>\n\n<p>1- Putting the <code>wp_head()</code> hook right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;?php wp_head(); ?&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.</em></p>\n\n<p>or</p>\n\n<p>2- Pasting your code directly in your <code>header.php</code> file, right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Your Google Adsense code here, right after the &lt;head&gt; element --&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>Always remember to back up your files before doing such edits.</em></p>\n" }, { "answer_id": 258823, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": -1, "selected": false, "text": "<pre><code>add_action( 'wp_head', 'add_google_adsense_code' );\nfunction add_google_adsense_code() {\n?&gt;&lt;script&gt;\n// Your Google Adsense Code here.\n&lt;/script&gt;&lt;?php \n}\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">action hooks</a></p>\n\n<p>Added to your child themes functions file, this hook fires after wp_head therefore printing your script after the closing <code>&lt;/head&gt;</code> tag.</p>\n" } ]
2017/03/04
[ "https://wordpress.stackexchange.com/questions/258806", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114691/" ]
Google Adsense requires its activation code to be pasted right after the `<head>` tag of a site. However, I'm using a WordPress child theme. How can I paste my Google Adsense code in a child theme?
You can easily put your Google Adsense code within the `<head>` element of your WordPress site by using either of these methods in your `functions.php` file or by creating a plugin for that purpose: ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is stored within in your plugins directory, under the * the file named: gads.js, which contains your Google Adsense Code. * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js */ function load_my_google_adsense_code() { wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true ); } add_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' ); ``` Alternatively, you can include it directly as part of your function as below; ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is contained directly in your function. */ function load_my_google_adsense_code() { ?> <script> // Your Google Adsense Code here. </script> <?php } add_action('wp_head', 'load_my_google_adsense_code'); ``` *Please note:* The two (2) approaches above will enable you to have your Google Adsense code within the `<head>` element of your WordPress site, usually right before `</head>`, but this is really theme dependent as it depends on the placement of the `wp_head()` hook within the `header.php`. Its generally recommended to have the `<?php wp_head(); ?>` declaration before the `</head>` which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below: ``` <?php /** * The header for our theme * File name: header.php */ ?><!DOCTYPE html> <html> <head> <!-- Other contents here --> <?php wp_head(); ?> </head> <!-- Other contents may follow --> ``` As such, the options provided above will work as *Google Adsense requires, per your OP*, should your the `wp_head()` hook of your theme satisfy that condition: occurring right below your `<head>` element. Should that not be the case and you still need to achieve this as *Google Adsense requires*, you will need to directly edit your `header.php` file for that purpose, either: 1- Putting the `wp_head()` hook right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <?php wp_head(); ?> <!-- Other contents here --> ``` *In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.* or 2- Pasting your code directly in your `header.php` file, right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <!-- Your Google Adsense code here, right after the <head> element --> <!-- Other contents here --> ``` *Always remember to back up your files before doing such edits.*
258,834
<p>In WordPress I have a custom post type called 'places' and these posts have one "places tag" each.</p> <p>What PHP code should I insert in the sidebar to print the tag of the current post?</p>
[ { "answer_id": 258812, "author": "Irfan Modan", "author_id": 65452, "author_profile": "https://wordpress.stackexchange.com/users/65452", "pm_score": -1, "selected": false, "text": "<p>Use wp_head hook in functions.php</p>\n\n<pre><code>add_action('wp_head','add_adsense');\n</code></pre>\n" }, { "answer_id": 258817, "author": "nyedidikeke", "author_id": 105480, "author_profile": "https://wordpress.stackexchange.com/users/105480", "pm_score": 2, "selected": false, "text": "<p>You can easily put your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site by using either of these methods in your <code>functions.php</code> file or by creating a plugin for that purpose:</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is stored within in your plugins directory, under the\n * the file named: gads.js, which contains your Google Adsense Code.\n * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js\n */\nfunction load_my_google_adsense_code() {\n wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true );\n}\nadd_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' );\n</code></pre>\n\n<p>Alternatively, you can include it directly as part of your function as below;</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is contained directly in your function.\n */\nfunction load_my_google_adsense_code() {\n ?&gt;\n &lt;script&gt;\n // Your Google Adsense Code here.\n &lt;/script&gt;\n &lt;?php\n}\nadd_action('wp_head', 'load_my_google_adsense_code');\n</code></pre>\n\n<p><em>Please note:</em></p>\n\n<p>The two (2) approaches above will enable you to have your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site, usually right before <code>&lt;/head&gt;</code>, but this is really theme dependent as it depends on the placement of the <code>wp_head()</code> hook within the <code>header.php</code>.</p>\n\n<p>Its generally recommended to have the <code>&lt;?php wp_head(); ?&gt;</code> declaration before the <code>&lt;/head&gt;</code> which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&gt;&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Other contents here --&gt;\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n &lt;!-- Other contents may follow --&gt;\n</code></pre>\n\n<p>As such, the options provided above will work as <em>Google Adsense requires, per your OP</em>, should your the <code>wp_head()</code> hook of your theme satisfy that condition: occurring right below your <code>&lt;head&gt;</code> element.</p>\n\n<p>Should that not be the case and you still need to achieve this as <em>Google Adsense requires</em>, you will need to directly edit your <code>header.php</code> file for that purpose, either:</p>\n\n<p>1- Putting the <code>wp_head()</code> hook right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;?php wp_head(); ?&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.</em></p>\n\n<p>or</p>\n\n<p>2- Pasting your code directly in your <code>header.php</code> file, right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Your Google Adsense code here, right after the &lt;head&gt; element --&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>Always remember to back up your files before doing such edits.</em></p>\n" }, { "answer_id": 258823, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": -1, "selected": false, "text": "<pre><code>add_action( 'wp_head', 'add_google_adsense_code' );\nfunction add_google_adsense_code() {\n?&gt;&lt;script&gt;\n// Your Google Adsense Code here.\n&lt;/script&gt;&lt;?php \n}\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">action hooks</a></p>\n\n<p>Added to your child themes functions file, this hook fires after wp_head therefore printing your script after the closing <code>&lt;/head&gt;</code> tag.</p>\n" } ]
2017/03/04
[ "https://wordpress.stackexchange.com/questions/258834", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114710/" ]
In WordPress I have a custom post type called 'places' and these posts have one "places tag" each. What PHP code should I insert in the sidebar to print the tag of the current post?
You can easily put your Google Adsense code within the `<head>` element of your WordPress site by using either of these methods in your `functions.php` file or by creating a plugin for that purpose: ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is stored within in your plugins directory, under the * the file named: gads.js, which contains your Google Adsense Code. * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js */ function load_my_google_adsense_code() { wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true ); } add_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' ); ``` Alternatively, you can include it directly as part of your function as below; ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is contained directly in your function. */ function load_my_google_adsense_code() { ?> <script> // Your Google Adsense Code here. </script> <?php } add_action('wp_head', 'load_my_google_adsense_code'); ``` *Please note:* The two (2) approaches above will enable you to have your Google Adsense code within the `<head>` element of your WordPress site, usually right before `</head>`, but this is really theme dependent as it depends on the placement of the `wp_head()` hook within the `header.php`. Its generally recommended to have the `<?php wp_head(); ?>` declaration before the `</head>` which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below: ``` <?php /** * The header for our theme * File name: header.php */ ?><!DOCTYPE html> <html> <head> <!-- Other contents here --> <?php wp_head(); ?> </head> <!-- Other contents may follow --> ``` As such, the options provided above will work as *Google Adsense requires, per your OP*, should your the `wp_head()` hook of your theme satisfy that condition: occurring right below your `<head>` element. Should that not be the case and you still need to achieve this as *Google Adsense requires*, you will need to directly edit your `header.php` file for that purpose, either: 1- Putting the `wp_head()` hook right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <?php wp_head(); ?> <!-- Other contents here --> ``` *In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.* or 2- Pasting your code directly in your `header.php` file, right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <!-- Your Google Adsense code here, right after the <head> element --> <!-- Other contents here --> ``` *Always remember to back up your files before doing such edits.*
258,835
<p>How we can use function with filter to add ads before and after content, Every ad has its priority. How we can use parameters at function then use it at filter This is the function</p> <pre><code> function mywp_before_after($content) { if(is_page() || is_single()) { $beforecontent = 'This goes before the content. Isn\'t that awesome!'; $aftercontent = 'And this will come after, so that you can remind them of something, like following you on Facebook for instance.'; $fullcontent = $beforecontent . $content . $aftercontent; } else { $fullcontent = $content; } return $fullcontent; } add_filter('the_content', 'mywp_before_after'); </code></pre> <p>Needed</p> <pre><code>function mywp_before_after($content,$place,$priority) { if ($place =='before'): $fullcontent = $beforecontent . $content; else: $fullcontent =$content . $aftercontent; } add_filter('the_content', 'mywp_before_after',10,2,$place,$priority); </code></pre>
[ { "answer_id": 258812, "author": "Irfan Modan", "author_id": 65452, "author_profile": "https://wordpress.stackexchange.com/users/65452", "pm_score": -1, "selected": false, "text": "<p>Use wp_head hook in functions.php</p>\n\n<pre><code>add_action('wp_head','add_adsense');\n</code></pre>\n" }, { "answer_id": 258817, "author": "nyedidikeke", "author_id": 105480, "author_profile": "https://wordpress.stackexchange.com/users/105480", "pm_score": 2, "selected": false, "text": "<p>You can easily put your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site by using either of these methods in your <code>functions.php</code> file or by creating a plugin for that purpose:</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is stored within in your plugins directory, under the\n * the file named: gads.js, which contains your Google Adsense Code.\n * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js\n */\nfunction load_my_google_adsense_code() {\n wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true );\n}\nadd_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' );\n</code></pre>\n\n<p>Alternatively, you can include it directly as part of your function as below;</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is contained directly in your function.\n */\nfunction load_my_google_adsense_code() {\n ?&gt;\n &lt;script&gt;\n // Your Google Adsense Code here.\n &lt;/script&gt;\n &lt;?php\n}\nadd_action('wp_head', 'load_my_google_adsense_code');\n</code></pre>\n\n<p><em>Please note:</em></p>\n\n<p>The two (2) approaches above will enable you to have your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site, usually right before <code>&lt;/head&gt;</code>, but this is really theme dependent as it depends on the placement of the <code>wp_head()</code> hook within the <code>header.php</code>.</p>\n\n<p>Its generally recommended to have the <code>&lt;?php wp_head(); ?&gt;</code> declaration before the <code>&lt;/head&gt;</code> which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&gt;&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Other contents here --&gt;\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n &lt;!-- Other contents may follow --&gt;\n</code></pre>\n\n<p>As such, the options provided above will work as <em>Google Adsense requires, per your OP</em>, should your the <code>wp_head()</code> hook of your theme satisfy that condition: occurring right below your <code>&lt;head&gt;</code> element.</p>\n\n<p>Should that not be the case and you still need to achieve this as <em>Google Adsense requires</em>, you will need to directly edit your <code>header.php</code> file for that purpose, either:</p>\n\n<p>1- Putting the <code>wp_head()</code> hook right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;?php wp_head(); ?&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.</em></p>\n\n<p>or</p>\n\n<p>2- Pasting your code directly in your <code>header.php</code> file, right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Your Google Adsense code here, right after the &lt;head&gt; element --&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>Always remember to back up your files before doing such edits.</em></p>\n" }, { "answer_id": 258823, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": -1, "selected": false, "text": "<pre><code>add_action( 'wp_head', 'add_google_adsense_code' );\nfunction add_google_adsense_code() {\n?&gt;&lt;script&gt;\n// Your Google Adsense Code here.\n&lt;/script&gt;&lt;?php \n}\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">action hooks</a></p>\n\n<p>Added to your child themes functions file, this hook fires after wp_head therefore printing your script after the closing <code>&lt;/head&gt;</code> tag.</p>\n" } ]
2017/03/04
[ "https://wordpress.stackexchange.com/questions/258835", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82877/" ]
How we can use function with filter to add ads before and after content, Every ad has its priority. How we can use parameters at function then use it at filter This is the function ``` function mywp_before_after($content) { if(is_page() || is_single()) { $beforecontent = 'This goes before the content. Isn\'t that awesome!'; $aftercontent = 'And this will come after, so that you can remind them of something, like following you on Facebook for instance.'; $fullcontent = $beforecontent . $content . $aftercontent; } else { $fullcontent = $content; } return $fullcontent; } add_filter('the_content', 'mywp_before_after'); ``` Needed ``` function mywp_before_after($content,$place,$priority) { if ($place =='before'): $fullcontent = $beforecontent . $content; else: $fullcontent =$content . $aftercontent; } add_filter('the_content', 'mywp_before_after',10,2,$place,$priority); ```
You can easily put your Google Adsense code within the `<head>` element of your WordPress site by using either of these methods in your `functions.php` file or by creating a plugin for that purpose: ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is stored within in your plugins directory, under the * the file named: gads.js, which contains your Google Adsense Code. * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js */ function load_my_google_adsense_code() { wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true ); } add_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' ); ``` Alternatively, you can include it directly as part of your function as below; ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is contained directly in your function. */ function load_my_google_adsense_code() { ?> <script> // Your Google Adsense Code here. </script> <?php } add_action('wp_head', 'load_my_google_adsense_code'); ``` *Please note:* The two (2) approaches above will enable you to have your Google Adsense code within the `<head>` element of your WordPress site, usually right before `</head>`, but this is really theme dependent as it depends on the placement of the `wp_head()` hook within the `header.php`. Its generally recommended to have the `<?php wp_head(); ?>` declaration before the `</head>` which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below: ``` <?php /** * The header for our theme * File name: header.php */ ?><!DOCTYPE html> <html> <head> <!-- Other contents here --> <?php wp_head(); ?> </head> <!-- Other contents may follow --> ``` As such, the options provided above will work as *Google Adsense requires, per your OP*, should your the `wp_head()` hook of your theme satisfy that condition: occurring right below your `<head>` element. Should that not be the case and you still need to achieve this as *Google Adsense requires*, you will need to directly edit your `header.php` file for that purpose, either: 1- Putting the `wp_head()` hook right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <?php wp_head(); ?> <!-- Other contents here --> ``` *In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.* or 2- Pasting your code directly in your `header.php` file, right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <!-- Your Google Adsense code here, right after the <head> element --> <!-- Other contents here --> ``` *Always remember to back up your files before doing such edits.*
258,843
<p>i need to attach an image from a specific post by using post id of custom post type which i created new... how can i..? actually i created a new 5 post type named 'flips'... and meta content areas are website, title back, content back, main title, thumbnail etc.,.</p> <pre><code>&lt;?php $mypost = get_post(28); echo apply_filters('the_content',$mypost-&gt;post_content); ?&gt; &lt;?php $mypost = get_post(28); echo apply_filters('website',$mypost-&gt;website); echo apply_filters('titleback',$mypost-&gt;titleback); echo apply_filters('contentback',$mypost-&gt;contentback); ?&gt; </code></pre> <p>i need to add post thumbnail to display here also how can i?</p>
[ { "answer_id": 258812, "author": "Irfan Modan", "author_id": 65452, "author_profile": "https://wordpress.stackexchange.com/users/65452", "pm_score": -1, "selected": false, "text": "<p>Use wp_head hook in functions.php</p>\n\n<pre><code>add_action('wp_head','add_adsense');\n</code></pre>\n" }, { "answer_id": 258817, "author": "nyedidikeke", "author_id": 105480, "author_profile": "https://wordpress.stackexchange.com/users/105480", "pm_score": 2, "selected": false, "text": "<p>You can easily put your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site by using either of these methods in your <code>functions.php</code> file or by creating a plugin for that purpose:</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is stored within in your plugins directory, under the\n * the file named: gads.js, which contains your Google Adsense Code.\n * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js\n */\nfunction load_my_google_adsense_code() {\n wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true );\n}\nadd_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' );\n</code></pre>\n\n<p>Alternatively, you can include it directly as part of your function as below;</p>\n\n<pre><code>/**\n * Load my Google Adsense code.\n *\n * Here, your Google Adsense Code is contained directly in your function.\n */\nfunction load_my_google_adsense_code() {\n ?&gt;\n &lt;script&gt;\n // Your Google Adsense Code here.\n &lt;/script&gt;\n &lt;?php\n}\nadd_action('wp_head', 'load_my_google_adsense_code');\n</code></pre>\n\n<p><em>Please note:</em></p>\n\n<p>The two (2) approaches above will enable you to have your Google Adsense code within the <code>&lt;head&gt;</code> element of your WordPress site, usually right before <code>&lt;/head&gt;</code>, but this is really theme dependent as it depends on the placement of the <code>wp_head()</code> hook within the <code>header.php</code>.</p>\n\n<p>Its generally recommended to have the <code>&lt;?php wp_head(); ?&gt;</code> declaration before the <code>&lt;/head&gt;</code> which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&gt;&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Other contents here --&gt;\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n &lt;!-- Other contents may follow --&gt;\n</code></pre>\n\n<p>As such, the options provided above will work as <em>Google Adsense requires, per your OP</em>, should your the <code>wp_head()</code> hook of your theme satisfy that condition: occurring right below your <code>&lt;head&gt;</code> element.</p>\n\n<p>Should that not be the case and you still need to achieve this as <em>Google Adsense requires</em>, you will need to directly edit your <code>header.php</code> file for that purpose, either:</p>\n\n<p>1- Putting the <code>wp_head()</code> hook right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;?php wp_head(); ?&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.</em></p>\n\n<p>or</p>\n\n<p>2- Pasting your code directly in your <code>header.php</code> file, right after your <code>&lt;head&gt;</code> element as in:</p>\n\n<pre><code>&lt;?php\n/**\n * The header for our theme\n * File name: header.php\n */\n\n?&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;!-- Your Google Adsense code here, right after the &lt;head&gt; element --&gt;\n &lt;!-- Other contents here --&gt;\n</code></pre>\n\n<p><em>Always remember to back up your files before doing such edits.</em></p>\n" }, { "answer_id": 258823, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": -1, "selected": false, "text": "<pre><code>add_action( 'wp_head', 'add_google_adsense_code' );\nfunction add_google_adsense_code() {\n?&gt;&lt;script&gt;\n// Your Google Adsense Code here.\n&lt;/script&gt;&lt;?php \n}\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">action hooks</a></p>\n\n<p>Added to your child themes functions file, this hook fires after wp_head therefore printing your script after the closing <code>&lt;/head&gt;</code> tag.</p>\n" } ]
2017/03/04
[ "https://wordpress.stackexchange.com/questions/258843", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114712/" ]
i need to attach an image from a specific post by using post id of custom post type which i created new... how can i..? actually i created a new 5 post type named 'flips'... and meta content areas are website, title back, content back, main title, thumbnail etc.,. ``` <?php $mypost = get_post(28); echo apply_filters('the_content',$mypost->post_content); ?> <?php $mypost = get_post(28); echo apply_filters('website',$mypost->website); echo apply_filters('titleback',$mypost->titleback); echo apply_filters('contentback',$mypost->contentback); ?> ``` i need to add post thumbnail to display here also how can i?
You can easily put your Google Adsense code within the `<head>` element of your WordPress site by using either of these methods in your `functions.php` file or by creating a plugin for that purpose: ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is stored within in your plugins directory, under the * the file named: gads.js, which contains your Google Adsense Code. * The full file path for the purpose below: wp-content/plugins/my-plugin-name/inc/gads.js */ function load_my_google_adsense_code() { wp_enqueue_script( 'gads', plugins_url('/inc/gads.js', __FILE__), null, '', true ); } add_action( 'wp_enqueue_scripts', 'load_my_google_adsense_code' ); ``` Alternatively, you can include it directly as part of your function as below; ``` /** * Load my Google Adsense code. * * Here, your Google Adsense Code is contained directly in your function. */ function load_my_google_adsense_code() { ?> <script> // Your Google Adsense Code here. </script> <?php } add_action('wp_head', 'load_my_google_adsense_code'); ``` *Please note:* The two (2) approaches above will enable you to have your Google Adsense code within the `<head>` element of your WordPress site, usually right before `</head>`, but this is really theme dependent as it depends on the placement of the `wp_head()` hook within the `header.php`. Its generally recommended to have the `<?php wp_head(); ?>` declaration before the `</head>` which explains the point above, purposely to avoid potential conflicts with plugins among others and implemented as below: ``` <?php /** * The header for our theme * File name: header.php */ ?><!DOCTYPE html> <html> <head> <!-- Other contents here --> <?php wp_head(); ?> </head> <!-- Other contents may follow --> ``` As such, the options provided above will work as *Google Adsense requires, per your OP*, should your the `wp_head()` hook of your theme satisfy that condition: occurring right below your `<head>` element. Should that not be the case and you still need to achieve this as *Google Adsense requires*, you will need to directly edit your `header.php` file for that purpose, either: 1- Putting the `wp_head()` hook right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <?php wp_head(); ?> <!-- Other contents here --> ``` *In the above example, you will have to use either of the earlier two enumerated approaches above so as to leverage on this edit in order to achieve your goal.* or 2- Pasting your code directly in your `header.php` file, right after your `<head>` element as in: ``` <?php /** * The header for our theme * File name: header.php */ ?<!DOCTYPE html> <html> <head> <!-- Your Google Adsense code here, right after the <head> element --> <!-- Other contents here --> ``` *Always remember to back up your files before doing such edits.*
258,844
<p>I have a custom post type <code>paper</code> defined in my WordPress plugin that I show along with standard posts in the main query via:</p> <pre><code>function add_custom_post_types_to_query( $query ) { if ( is_home() &amp;&amp; $query-&gt;is_main_query() ) $query-&gt;set( 'post_type', array( 'post', 'paper' ) ); // As was pointed out by Ihor Vorotnov this return is not necessary. // return $query; } add_action( 'pre_get_posts', 'add_custom_post_types_to_query' ); </code></pre> <p>I have also been able to register a custom <code>single-paper.php</code> template from the plugin directory for my post type via:</p> <pre><code>function get_custom_post_type_single_template( $single_template ) { global $post; if ( $post-&gt;post_type == 'paper' ) { $single_template = dirname( __FILE__ ) . '/single-paper.php'; } return $single_template; } add_filter( 'single_template', 'get_custom_post_type_single_template' ); </code></pre> <p>I would like to do something similar for the <code>content-____.php</code> template that is used by my theme (<code>onepress</code>) to have control over how my posts appear in the main query.</p> <p>The <code>index.php</code> of the theme even says:</p> <pre><code>&lt;?php /* Start the Loop */ ?&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;?php /* * Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_format() ); ?&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>but I would rather not want to implement a child theme for this and keep all the code related to the custom post type in the plugin.</p> <p>Is there any way to add a filter such that <code>get_template_part( 'template-parts/content', get_post_format() );</code> uses a custom template supplied by my plugin for <code>paper</code> posts and the standard template of the theme for normal posts?</p> <p>I have tried different variations of the code I used above for the <code>'single_template'</code>, but to no avail.</p>
[ { "answer_id": 258848, "author": "David Lee", "author_id": 111965, "author_profile": "https://wordpress.stackexchange.com/users/111965", "pm_score": 0, "selected": false, "text": "<p>create your own function for it:</p>\n\n<pre><code>function get_template_part_custom($content_name) {\n global $post;\n //its paper type?\n if ($post-&gt;post_type == 'paper') {\n //get template-parts/content-paper.php\n get_template_part( 'template-parts/content', $content_name );\n }else{\n //fallback to the default\n get_template_part( 'template-parts/content', get_post_format($post) );\n }\n}\n</code></pre>\n\n<p>use it like this:</p>\n\n<pre><code>get_template_part_custom('paper');\n</code></pre>\n\n<p>if the post is of the type <code>paper</code> it will try to load a file called <code>content-paper.php</code> inside a folder called <code>template-parts</code> in the root theme folder, if the file doesnt exists it will try to load <code>content.php</code>, check the <a href=\"https://developer.wordpress.org/files/2014/10/template-hierarchy.png\" rel=\"nofollow noreferrer\">template-hierarchy</a>, i dont think you need to register your template <code>single-paper.php</code>, WordPress will pick it up for you.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>For loading a template from a plugin:</p>\n\n<pre><code>//load a custom file from the plugin\nadd_filter( 'template_include', 'return_our_template');\n\n//Returns template file\nfunction return_our_template( $template ) {\n\n // Post ID\n $post_id = get_the_ID();\n\n // For all other Types that arent ours\n if ( get_post_type( $post_id ) != 'paper' ) {\n return $template;\n }\n\n // Else use our custom template\n if ( is_single() ) {\n return get_custom_template( 'single' );\n }\n\n}\n\n//Get the custom template if is set\nfunction get_custom_template( $template ) {\n\n // Get the slug\n $template_slug = rtrim( $template, '.php' );\n $template = $template_slug . '.php';\n\n // Check if a custom template exists in the theme folder, if not, load the plugin template file\n if ( $theme_file = locate_template( array( 'plugin_template/' . $template ) ) ) {\n $file = $theme_file;\n }\n else {\n //here path to '/single-paper.php'\n $file = PATH_TO_YOUR_BASE_DIR . $template;\n }\n //create a new filter so the devs can filter this\n return apply_filters( 'filter_template_' . $template, $file );\n}\n</code></pre>\n" }, { "answer_id": 259148, "author": "Ihor Vorotnov", "author_id": 47359, "author_profile": "https://wordpress.stackexchange.com/users/47359", "pm_score": 0, "selected": false, "text": "<p>As far as I can see from the source code, you can't filter <code>get_template_part()</code> as you would normally do. Please see <a href=\"https://wordpress.stackexchange.com/a/153012/47359\">this thread</a> for some solutions.</p>\n" }, { "answer_id": 259307, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<h1>Background</h1>\n\n<p>Unfortunately <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"noreferrer\"><code>get_template_part()</code></a> function doesn't have any suitable filter to achieve what you want. It's possible to use the <code>get_template_part_{$slug}</code> action hook to inject template parts, however, without any change to your theme or a child theme, the original template part will be added anyway. So this way you'll not be able to replace existing template parts.</p>\n\n<p>However, you'll be able to achieve the desired result by following one of the options below:</p>\n\n<hr>\n\n<h1>Option 1: Use the default CSS classes:</h1>\n\n<p>If only thing you want is to change the style for the <code>paper</code> custom post type, then you may simply use the generated CSS class by WordPress. Any standard theme in WordPress will generate <code>$post_type</code> and <code>type-{$post_type}</code> CSS classes for the post content. For example, the custom post type <code>paper</code> will have <code>paper</code> &amp; <code>type-paper</code> CSS classes and general <code>post</code> will have <code>post</code> and <code>type-post</code> CSS classes. Also home page will have <code>home</code> CSS class in the body. So to target <code>paper</code> entries in the home page, you may use the following CSS rules:</p>\n\n<pre><code>body.home .type-paper {\n /* Custom CSS for paper entries in the home page */\n}\n</code></pre>\n\n<h1>Option 2: Modify CSS classes:</h1>\n\n<p>If the default CSS classes are not enough for you, you can also modify (add / remove) CSS classes using the <a href=\"https://codex.wordpress.org/Function_Reference/post_class\" rel=\"noreferrer\"><code>post_class</code></a> filter hook in your plugin. Like this:</p>\n\n<pre><code>add_filter( 'post_class', 'paper_post_class' );\nfunction paper_post_class( $class ) {\n if ( get_post_type() === 'paper' &amp;&amp; is_home() ) {\n\n // remove these classes\n $remove = array( 'css-class-to-remove', 'another-class-to-remove' );\n $class = array_diff( $class, $remove );\n\n // add these classes\n $add = array( 'custom-paper', 'my-paper-class' );\n $class = array_merge( $add, $class );\n }\n return $class;\n}\n</code></pre>\n\n<p>This way you'll be able to remove CSS classes you don't want for <code>paper</code> entries and add new CSS classes you want for <code>paper</code> entries without modifying the theme files. Then use those CSS classes to change the style of <code>paper</code> entries as needed.</p>\n\n<hr>\n\n<h1>Option 3: Modify template &amp; template parts</h1>\n\n<p>If your desired style change is not possible by only targeting CSS classes, then you may change the template parts from your plugin too. However, since replacing template parts added by <code>get_template_part()</code> is not possible by using hooks, you'll have to change the template in a way so that you may modify the <code>get_template_part()</code> call from within the plugin.</p>\n\n<p>To do that, you may target your <code>pre_get_posts</code> hook function and use <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"noreferrer\"><code>template_include</code></a> filter hook to modify the home page template, like the following:</p>\n\n<pre><code>function add_custom_post_types_to_query( $query ) {\n if ( is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'post_type', array( 'post', 'paper' ) );\n\n // now also change the home page template, but only when this condition matches\n add_filter( 'template_include', 'wpse258844_custom_template', 999 );\n }\n}\nadd_action( 'pre_get_posts', 'add_custom_post_types_to_query' ); \n</code></pre>\n\n<p>Then use the following CODE (modify as you need):</p>\n\n<pre><code>// for better file management, use a separate \"theme-{$theme_name_slug}\" directory within your plugin directory\n// so if the active theme name is \"OnePress\", the directory name will be \"theme-onepress\"\n// This will save you a ton of headache if you change the theme,\n// as different themes may use different function calls within the templates, which other themes may not have\ndefine( 'wpse258844_TEMPLATE_DIR', plugin_dir_path( __FILE__ ) . sprintf( 'theme-%s/', sanitize_title( wp_get_theme() ) ) );\n\nfunction wpse258844_custom_template( $template ) {\n // this file will replace your homepage template file\n $index_paper = wpse258844_TEMPLATE_DIR . 'custom-home.php';\n\n // file_exists() check may need clearing stat cache if you change file name, delete the file etc.\n // Once you are done, comment out or remove clearstatcache(); in production\n clearstatcache();\n\n if ( file_exists( $index_paper ) ) {\n $template = $index_paper;\n }\n return $template;\n}\n\nfunction wpse258844_get_template_part( $slug, $name = null ) {\n if( get_post_type() === 'paper' ) {\n\n // just to be consistant with get_template_part() function\n do_action( \"get_template_part_{$slug}\", $slug, $name );\n\n $located = '';\n $name = (string) $name;\n\n // file_exists() check may need clearing stat cache if you change file name, delete the file etc.\n // Once you are done, comment out or remove clearstatcache(); in production\n clearstatcache();\n\n if ( '' !== $name &amp;&amp; file_exists( wpse258844_TEMPLATE_DIR . \"{$slug}-{$name}.php\" ) ) {\n $located = wpse258844_TEMPLATE_DIR . \"{$slug}-{$name}.php\";\n }\n else if ( file_exists( wpse258844_TEMPLATE_DIR . \"{$slug}.php\" ) ) {\n $located = wpse258844_TEMPLATE_DIR . \"{$slug}.php\";\n }\n\n if ( '' != $located ) {\n load_template( $located, false );\n return;\n }\n }\n\n get_template_part( $slug, $name );\n}\n</code></pre>\n\n<p>Once you have the above CODE in your plugin (read the comments within the CODE):</p>\n\n<ol>\n<li><p>Create a new directory within you plugin directory to keep theme template files, e.g. <code>theme-onepress</code>. This will help you in the future if you want to test design changes with a different theme (I suppose that's the main purpose of all these mess ;) ).</p></li>\n<li><p>Within the new <code>theme-onepress</code> directory, create a file named <code>custom-home.php</code>. Copy the CODE of home page template from your theme (may be <code>index.php</code>, or <code>home.php</code> or whatever your theme is using for the home page template). </p></li>\n<li><p>Now in <code>custom-home.php</code> change all the call of <code>get_template_part</code> to <code>wpse258844_get_template_part</code>. No need to change the parameter, only function name. <code>wpse258844_get_template_part()</code> function in the above CODE is identical to <code>get_template_part()</code> function and falls back to default behaviour if custom template part is not found within your plugin's <code>theme-{$theme_name_slug}</code> (e.g. <code>theme-onepress</code>) directory.</p></li>\n<li><p>Finally, replace whatever template part file you wanted to replace in your plugin's <code>theme-{$theme_name_slug}</code> directory.</p>\n\n<p>For example, if the original call was <code>get_template_part( 'template-parts/content', get_post_format() )</code> and you want to replace <code>content.php</code> template part, then simply place a file named <code>content.php</code> in your plugin's <code>theme-onepress/template-parts</code> directory. That means, the <code>theme-onepress</code> directory will behave like a child theme for template parts - i.e. simple drop-in replacement.</p></li>\n</ol>\n" }, { "answer_id": 265091, "author": "cgogolin", "author_id": 114713, "author_profile": "https://wordpress.stackexchange.com/users/114713", "pm_score": 0, "selected": false, "text": "<p>Here is another \"hack\" to achieve what was asked for:</p>\n\n<p>One can use the <code>post format</code> (not to be confused with the <code>post type</code>!) to use a custom template for a custom post type. Remember the line </p>\n\n<pre><code>get_template_part( 'template-parts/content', get_post_format() );\n</code></pre>\n\n<p>in the <code>index.php</code> described in the question. Through this construciton most standard themes load different templates depending on the <code>post format</code>.</p>\n\n<p>One can claim that all posts of a given custom post type, say <code>paper</code> have a certain post format, say <code>aside</code> by calling</p>\n\n<pre><code>set_post_format( $post_id, 'aside' )\n</code></pre>\n\n<p>during the a function hooked into the <code>'save_post'</code> hook and by adding something like</p>\n\n<pre><code>function paper_format_terms( $terms, $post_id, $tax ) {\n if ( 'post_format' === $tax &amp;&amp; empty( $terms ) &amp;&amp; 'paper' === get_post_type( $post_id ) ) {\n $aside = get_term_by( 'slug', 'post-format-aside', $tax );\n $terms = array( $aside );\n }\n return $terms;\n}\nadd_filter( 'get_the_terms', 'paper_format_terms', 10, 3 );\n</code></pre>\n\n<p>to the <code>'get_the_terms'</code> hook.</p>\n\n<p>One can not define custom post formats, but usually there is at least one post format that is not used for anything else. The 'aside' format can be a good choice.</p>\n\n<p>A standard theme will then, whenever it encounters a <code>paper</code> post look for the template <code>.../template-parts/content-aside.php</code>. All that is left to do is to install a suitable template to the theme directory in a way so that it does not get overwritten or deleted when the theme is updated (we want to keep all the code well contained inside the plugin!). This can be done my putting a suitable template into the fiel <code>content-aside.php</code> in the plugins directory and hooking into `'upgrader_process_complete' as follows</p>\n\n<pre><code>function install_aside_template_on_upgrade( $upgrader_object, $options ) {\n if ($options['type'] == 'theme' ) {\n $content_aside = plugin_dir_path( __FILE__ ) . 'content-aside.php';\n $template_parts_content_aside = get_stylesheet_directory() . '/template-parts/content-aside.php';\n\n copy($content_aside, $template_parts_content_aside);\n }\n}\nadd_action( 'upgrader_process_complete', 'install_aside_template_on_upgrade',10, 2);\n</code></pre>\n\n<p>In this way the <code>content-aside.php</code> is copied to the theme directory after each update of the theme.</p>\n\n<p>Keep in mind that this is a pretty terrible hack and it can have unwanted side effects! Still, I thought this can be useful for some...</p>\n" }, { "answer_id": 265094, "author": "cgogolin", "author_id": 114713, "author_profile": "https://wordpress.stackexchange.com/users/114713", "pm_score": 0, "selected": false, "text": "<p>While not exactly an answer to the question as it was posted, there is yet another quite clean and simple way to achieve something similar that, I suspect, will be the actual optimal solution for many people ending up on this page. For me the requirements changed slightly after I asked this question, allowing me to go for this solution in the end.</p>\n\n<p>Instead of using a custom theme, in many cases it is enough to change what a custom post type returns when the theme's template calls <code>the_excerpt()</code>. This can be achieved by hooking into the <code>'the_excerpt'</code> filter as follows:</p>\n\n<pre><code>function paper_get_the_excerpt ($content) {\n global $post;\n $post_id = $post-&gt;ID;\n if ( get_post_type($post_id) === 'paper' ) {\n [do whatever you want with $content]\n }\n return $content;\n}\nadd_filter( 'the_excerpt', 'paper_get_the_excerpt' );\n</code></pre>\n\n<p>Nice, clean and simple and allows for almost as much flexibility as changing the template.</p>\n" } ]
2017/03/04
[ "https://wordpress.stackexchange.com/questions/258844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114713/" ]
I have a custom post type `paper` defined in my WordPress plugin that I show along with standard posts in the main query via: ``` function add_custom_post_types_to_query( $query ) { if ( is_home() && $query->is_main_query() ) $query->set( 'post_type', array( 'post', 'paper' ) ); // As was pointed out by Ihor Vorotnov this return is not necessary. // return $query; } add_action( 'pre_get_posts', 'add_custom_post_types_to_query' ); ``` I have also been able to register a custom `single-paper.php` template from the plugin directory for my post type via: ``` function get_custom_post_type_single_template( $single_template ) { global $post; if ( $post->post_type == 'paper' ) { $single_template = dirname( __FILE__ ) . '/single-paper.php'; } return $single_template; } add_filter( 'single_template', 'get_custom_post_type_single_template' ); ``` I would like to do something similar for the `content-____.php` template that is used by my theme (`onepress`) to have control over how my posts appear in the main query. The `index.php` of the theme even says: ``` <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* * Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_format() ); ?> <?php endwhile; ?> ``` but I would rather not want to implement a child theme for this and keep all the code related to the custom post type in the plugin. Is there any way to add a filter such that `get_template_part( 'template-parts/content', get_post_format() );` uses a custom template supplied by my plugin for `paper` posts and the standard template of the theme for normal posts? I have tried different variations of the code I used above for the `'single_template'`, but to no avail.
Background ========== Unfortunately [`get_template_part()`](https://developer.wordpress.org/reference/functions/get_template_part/) function doesn't have any suitable filter to achieve what you want. It's possible to use the `get_template_part_{$slug}` action hook to inject template parts, however, without any change to your theme or a child theme, the original template part will be added anyway. So this way you'll not be able to replace existing template parts. However, you'll be able to achieve the desired result by following one of the options below: --- Option 1: Use the default CSS classes: ====================================== If only thing you want is to change the style for the `paper` custom post type, then you may simply use the generated CSS class by WordPress. Any standard theme in WordPress will generate `$post_type` and `type-{$post_type}` CSS classes for the post content. For example, the custom post type `paper` will have `paper` & `type-paper` CSS classes and general `post` will have `post` and `type-post` CSS classes. Also home page will have `home` CSS class in the body. So to target `paper` entries in the home page, you may use the following CSS rules: ``` body.home .type-paper { /* Custom CSS for paper entries in the home page */ } ``` Option 2: Modify CSS classes: ============================= If the default CSS classes are not enough for you, you can also modify (add / remove) CSS classes using the [`post_class`](https://codex.wordpress.org/Function_Reference/post_class) filter hook in your plugin. Like this: ``` add_filter( 'post_class', 'paper_post_class' ); function paper_post_class( $class ) { if ( get_post_type() === 'paper' && is_home() ) { // remove these classes $remove = array( 'css-class-to-remove', 'another-class-to-remove' ); $class = array_diff( $class, $remove ); // add these classes $add = array( 'custom-paper', 'my-paper-class' ); $class = array_merge( $add, $class ); } return $class; } ``` This way you'll be able to remove CSS classes you don't want for `paper` entries and add new CSS classes you want for `paper` entries without modifying the theme files. Then use those CSS classes to change the style of `paper` entries as needed. --- Option 3: Modify template & template parts ========================================== If your desired style change is not possible by only targeting CSS classes, then you may change the template parts from your plugin too. However, since replacing template parts added by `get_template_part()` is not possible by using hooks, you'll have to change the template in a way so that you may modify the `get_template_part()` call from within the plugin. To do that, you may target your `pre_get_posts` hook function and use [`template_include`](https://developer.wordpress.org/reference/hooks/template_include/) filter hook to modify the home page template, like the following: ``` function add_custom_post_types_to_query( $query ) { if ( is_home() && $query->is_main_query() ) { $query->set( 'post_type', array( 'post', 'paper' ) ); // now also change the home page template, but only when this condition matches add_filter( 'template_include', 'wpse258844_custom_template', 999 ); } } add_action( 'pre_get_posts', 'add_custom_post_types_to_query' ); ``` Then use the following CODE (modify as you need): ``` // for better file management, use a separate "theme-{$theme_name_slug}" directory within your plugin directory // so if the active theme name is "OnePress", the directory name will be "theme-onepress" // This will save you a ton of headache if you change the theme, // as different themes may use different function calls within the templates, which other themes may not have define( 'wpse258844_TEMPLATE_DIR', plugin_dir_path( __FILE__ ) . sprintf( 'theme-%s/', sanitize_title( wp_get_theme() ) ) ); function wpse258844_custom_template( $template ) { // this file will replace your homepage template file $index_paper = wpse258844_TEMPLATE_DIR . 'custom-home.php'; // file_exists() check may need clearing stat cache if you change file name, delete the file etc. // Once you are done, comment out or remove clearstatcache(); in production clearstatcache(); if ( file_exists( $index_paper ) ) { $template = $index_paper; } return $template; } function wpse258844_get_template_part( $slug, $name = null ) { if( get_post_type() === 'paper' ) { // just to be consistant with get_template_part() function do_action( "get_template_part_{$slug}", $slug, $name ); $located = ''; $name = (string) $name; // file_exists() check may need clearing stat cache if you change file name, delete the file etc. // Once you are done, comment out or remove clearstatcache(); in production clearstatcache(); if ( '' !== $name && file_exists( wpse258844_TEMPLATE_DIR . "{$slug}-{$name}.php" ) ) { $located = wpse258844_TEMPLATE_DIR . "{$slug}-{$name}.php"; } else if ( file_exists( wpse258844_TEMPLATE_DIR . "{$slug}.php" ) ) { $located = wpse258844_TEMPLATE_DIR . "{$slug}.php"; } if ( '' != $located ) { load_template( $located, false ); return; } } get_template_part( $slug, $name ); } ``` Once you have the above CODE in your plugin (read the comments within the CODE): 1. Create a new directory within you plugin directory to keep theme template files, e.g. `theme-onepress`. This will help you in the future if you want to test design changes with a different theme (I suppose that's the main purpose of all these mess ;) ). 2. Within the new `theme-onepress` directory, create a file named `custom-home.php`. Copy the CODE of home page template from your theme (may be `index.php`, or `home.php` or whatever your theme is using for the home page template). 3. Now in `custom-home.php` change all the call of `get_template_part` to `wpse258844_get_template_part`. No need to change the parameter, only function name. `wpse258844_get_template_part()` function in the above CODE is identical to `get_template_part()` function and falls back to default behaviour if custom template part is not found within your plugin's `theme-{$theme_name_slug}` (e.g. `theme-onepress`) directory. 4. Finally, replace whatever template part file you wanted to replace in your plugin's `theme-{$theme_name_slug}` directory. For example, if the original call was `get_template_part( 'template-parts/content', get_post_format() )` and you want to replace `content.php` template part, then simply place a file named `content.php` in your plugin's `theme-onepress/template-parts` directory. That means, the `theme-onepress` directory will behave like a child theme for template parts - i.e. simple drop-in replacement.
258,879
<p>I have a custom post type called "product" and I want to hide an specific widget only if the post type is "product" I was trying with something like this: </p> <pre><code>&lt;?php function hidewidget() { $args = array( 'name' =&gt; 'product' ); $output = 'objects'; $post_types = get_post_types( $args, $output ); return $post_types; } $widhide = hidewidget(); ?&gt; &lt;?php if ($widhide = 'product') { } else { ?&gt; &lt;div class="widgetclass"&gt;&lt;?php dynamic_sidebar( 'filters' ); ?&gt;&lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>The problem is the following: this function just return the name, I can't do anything with the name. </p> <p>I need to call a function wich return a page with an specific kind of post. </p> <p>It's possible in wordpress? any other solution to hide that div on the product detail page in woocommerce?</p> <p>pd: <strong>I can't remove <code>.widgetclass</code></strong> <strong>it needs to be there</strong>, I try with a plugin "widget display" to hide the widget but the <code>.widgetclass</code> div was still appearing obviously.</p>
[ { "answer_id": 258874, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 1, "selected": false, "text": "<p>My <em>last resort</em> in such cases is to <strong>temporarily</strong> add a call to the PHP <a href=\"http://php.net/manual/en/function.debug-print-backtrace.php\" rel=\"nofollow noreferrer\">debug_print_backtrace()</a> function at the file/line # indicated in the warning message.</p>\n\n<p>By examining the output of <code>debug_print_backtrace()</code> you can see the call stack that lead to the warning message being generated. Some times the call stack is pretty deep and it still takes a while to figure out what is going on.</p>\n" }, { "answer_id": 258893, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": false, "text": "<p>You can search through the installed files in different ways to find occurrences of the function name that is giving the errors/warnings. Here's 3 ways:</p>\n\n<ol>\n<li><p>Download all installed files via FTP. Use a text editor with a Find in Files feature that searches subfolders (eg. TextPad.) This is the slow way, unless you keep a local copy already in which case it's the fast way.</p></li>\n<li><p>Login to your server via SSH and use a search command from the command line.</p></li>\n</ol>\n\n<p><code>cd /home/USERNAME/web/DOMAIN/</code> (path below installation)</p>\n\n<p><code>fgrep -R \"FUNCTION_NAME\" public_html</code> (where public_html is the install dir)</p>\n\n<ol start=\"3\">\n<li>Use a plugin that will search through all installed plugin or theme files from your admin area, eg. <a href=\"http://wordpress.org/plugins/wp-bugbot/\" rel=\"nofollow noreferrer\">WP BugBot</a> (full disclosure: written by yours truly for this very purpose.)</li>\n</ol>\n\n<p>I think it's also possible to have the error messages output more information about the error through altering the PHP configuration or error settings, but that is more advanced option I'll leave that for further research.</p>\n" }, { "answer_id": 258895, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>This is where the rule of avoiding bloat applies best. You should ask yourself why is it that you have so many errors generated with the code you use. In theory you should not fix the errors but wait for the author to fix it as if you fix it yourself you basically forking the plugin/theme.</p>\n\n<p>More specific to your question, the answer is that it is probably impossible to have it right better than 90%. You can use the \"<a href=\"https://wordpress.org/plugins/query-monitor/\" rel=\"nofollow noreferrer\">query monitor</a>\" plugin to get stack trace, but even stack trace will have only limited value for non trivial situation. For example you might get an \"undefined index\" type of error when accessing an array element which is a result of DB access bug that happens when a value is being saved, and which you see the symptoms of it only when it is used.</p>\n\n<p>And since finding and fixing non trivial errors is not trivial, and having errors is always a possible gateway to security breaches or general site malfunctions, you should just not use plugins and themes that leave you figuring this kind of things alone by not having timely updates or good effective support.</p>\n" } ]
2017/03/05
[ "https://wordpress.stackexchange.com/questions/258879", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114736/" ]
I have a custom post type called "product" and I want to hide an specific widget only if the post type is "product" I was trying with something like this: ``` <?php function hidewidget() { $args = array( 'name' => 'product' ); $output = 'objects'; $post_types = get_post_types( $args, $output ); return $post_types; } $widhide = hidewidget(); ?> <?php if ($widhide = 'product') { } else { ?> <div class="widgetclass"><?php dynamic_sidebar( 'filters' ); ?></div> <?php } ?> ``` The problem is the following: this function just return the name, I can't do anything with the name. I need to call a function wich return a page with an specific kind of post. It's possible in wordpress? any other solution to hide that div on the product detail page in woocommerce? pd: **I can't remove `.widgetclass`** **it needs to be there**, I try with a plugin "widget display" to hide the widget but the `.widgetclass` div was still appearing obviously.
This is where the rule of avoiding bloat applies best. You should ask yourself why is it that you have so many errors generated with the code you use. In theory you should not fix the errors but wait for the author to fix it as if you fix it yourself you basically forking the plugin/theme. More specific to your question, the answer is that it is probably impossible to have it right better than 90%. You can use the "[query monitor](https://wordpress.org/plugins/query-monitor/)" plugin to get stack trace, but even stack trace will have only limited value for non trivial situation. For example you might get an "undefined index" type of error when accessing an array element which is a result of DB access bug that happens when a value is being saved, and which you see the symptoms of it only when it is used. And since finding and fixing non trivial errors is not trivial, and having errors is always a possible gateway to security breaches or general site malfunctions, you should just not use plugins and themes that leave you figuring this kind of things alone by not having timely updates or good effective support.
258,937
<p>I have a word press blog and all was fine and one day suddenly all the images in the website have disappeared .. </p> <p>I see the images are there in the wp-content/uploads/ in there specific directory(month &amp; year) but nothing is visible in media library</p> <p>I also noticed all the pages, posts were turned to draft . I republished them but still can't access images in media library ..</p> <p>In settings/media/ </p> <p>I have checked the option </p> <pre><code> Organize my uploads into month- and year-based folders </code></pre> <p>but don't see the the option to put the path of uploads folder..</p> <p>I hope somebody will help in identifying the bug and fix it..</p> <p>Thanks in advance</p>
[ { "answer_id": 260089, "author": "ricotheque", "author_id": 34238, "author_profile": "https://wordpress.stackexchange.com/users/34238", "pm_score": 0, "selected": false, "text": "<p>Unless you haven't updated your WordPress for a long time, you shouldn't have been able to change your upload folder through the Dashboard anyway. This feature was removed in version 3.5, if I'm not mistaken.</p>\n\n<p>First, <strong>back up everything</strong> (your WordPress installation, especially everything under <code>wp-content</code>, and your database). Now what you can do is:</p>\n\n<p><strong>Check your <code>wp-config.php</code></strong> </p>\n\n<ol>\n<li><p>Look for a line similar to <code>define( 'UPLOADS', 'wp-content\\path );</code>. This is the only way to change your media directory on newer versions of WordPress.</p></li>\n<li><p>If you see code like that, try deleting it from <code>wp-config.php</code>.</p></li>\n</ol>\n\n<p><strong>Install the latest version of WordPress</strong></p>\n\n<ol>\n<li>Download the zip from <a href=\"https://wordpress.org/\" rel=\"nofollow noreferrer\">WordPress.org</a>.</li>\n<li>Copy the zip to your WordPress directory.</li>\n<li>Move out <code>wp-config.php</code>.</li>\n<li>Delete everything in your WordPress directory except for the <code>wp-content</code> folder.</li>\n<li>Unzip the file you downloaded from WordPress.org. You'll see a new folder called <code>wordpress</code>. Copy everything from there into your original WordPress directory.</li>\n<li>Put back your <code>wp-config.php</code>.</li>\n</ol>\n\n<p><strong>Ask your host to revert your site to an earlier state</strong></p>\n\n<p>This is a last resort. Just ask your host if they can revert your site to a time before you noticed your image access problem.</p>\n\n<p>Whatever you decide to do, you an always restore your backups in case anything else goes wrong.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 260094, "author": "ferdouswp", "author_id": 114362, "author_profile": "https://wordpress.stackexchange.com/users/114362", "pm_score": -1, "selected": false, "text": "<p>Please check your images img src ftp or cpanel folder upload directory</p>\n\n<p><a href=\"https://i.stack.imgur.com/apon7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/apon7.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 260538, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>The two problems you describe may very well be related. Attachments (images) <a href=\"https://codex.wordpress.org/Using_Image_and_File_Attachments\" rel=\"nofollow noreferrer\">are stored as posts in the database</a> (so title, caption and so on can be stored in relation to the physical image file). It is this post that you see in the image library.</p>\n\n<p>Normally, the <code>post_status</code> of attachments is <code>inherit</code>. However, if the <code>post_status</code> is set as <code>draft</code> the post won't be visible in the media library anymore, even as the physical file is still there and the title/caption is still stored in the database.</p>\n\n<p>So, my guess is that either malware or a rogue/ill-programmed plugin has set all you <code>post_statusses</code> to <code>draft</code>. To find out, you should open your PHP Admin, and check the <code>post_status</code> column in the <code>_posts</code> table of your database. If there aren't a lot of images you can change the <code>post_status</code> manually to make the image posts reappear in the image library (try at least one the check if this solves your problem). Else you'll have to run an SQL query on the table.</p>\n" }, { "answer_id": 260905, "author": "Sam", "author_id": 115586, "author_profile": "https://wordpress.stackexchange.com/users/115586", "pm_score": 0, "selected": false, "text": "<p>Just adding a solution I had when my images in the media bay was not showing up i could still see the names and click the edit button but I only got a small blue square and no image even though they was on the server. The solution that worked for me was to install a thumbnail regenerate plugin and regenerate the images after this they all showed up in the media bay. I don't know if this is the issue your having as mine was not set to draft but thought I would share in case someone else comes across this and finds this solution useful.</p>\n" }, { "answer_id": 366888, "author": "user188305", "author_id": 188305, "author_profile": "https://wordpress.stackexchange.com/users/188305", "pm_score": 0, "selected": false, "text": "<p>I found the solution.</p>\n\n<p>It is default for the Polylang plugin to enable multilingual support for media. This should be turned off. You can do this by unchecking the 'Activate languages and translations for media' option, in the settings area of the Polylang plugin.</p>\n" }, { "answer_id": 370667, "author": "L Uttama", "author_id": 191313, "author_profile": "https://wordpress.stackexchange.com/users/191313", "pm_score": 0, "selected": false, "text": "<p>The same thing happen to me, it was due to some plugins I have installed, I removed all the recently added plugins, then everything worked fine.</p>\n<p>Still doesn't work then add this line: <code>define( 'UPLOADS', 'wp-content/uploads' );</code> at the end of the <code>wp-config.php</code> file.</p>\n" } ]
2017/03/05
[ "https://wordpress.stackexchange.com/questions/258937", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55034/" ]
I have a word press blog and all was fine and one day suddenly all the images in the website have disappeared .. I see the images are there in the wp-content/uploads/ in there specific directory(month & year) but nothing is visible in media library I also noticed all the pages, posts were turned to draft . I republished them but still can't access images in media library .. In settings/media/ I have checked the option ``` Organize my uploads into month- and year-based folders ``` but don't see the the option to put the path of uploads folder.. I hope somebody will help in identifying the bug and fix it.. Thanks in advance
The two problems you describe may very well be related. Attachments (images) [are stored as posts in the database](https://codex.wordpress.org/Using_Image_and_File_Attachments) (so title, caption and so on can be stored in relation to the physical image file). It is this post that you see in the image library. Normally, the `post_status` of attachments is `inherit`. However, if the `post_status` is set as `draft` the post won't be visible in the media library anymore, even as the physical file is still there and the title/caption is still stored in the database. So, my guess is that either malware or a rogue/ill-programmed plugin has set all you `post_statusses` to `draft`. To find out, you should open your PHP Admin, and check the `post_status` column in the `_posts` table of your database. If there aren't a lot of images you can change the `post_status` manually to make the image posts reappear in the image library (try at least one the check if this solves your problem). Else you'll have to run an SQL query on the table.
258,947
<p>i create a Custom Post and i don't want them has a URL.</p> <p>There is a URL like that = site.com/custom-slug/and-id-or-title <a href="https://i.stack.imgur.com/ldPvd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ldPvd.png" alt="enter image description here"></a></p> <p>and i don't want this, how i can do that?</p> <p>Thank you already!</p>
[ { "answer_id": 258948, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 1, "selected": true, "text": "<p>If I correctly understand the question you're asking, you don't want your CPT to be directly available on the front-end. If so, then just set <code>'public' =&gt; false</code> when you register the post_type.</p>\n\n<p>Remember that various other args to <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register_post_type()</a> default to the value of <code>public</code> (e.g., <code>show_ui</code>), show when you set <code>'public' =&gt; false</code> you often times need to explicitly set those args to true, e.g.</p>\n\n<pre><code>$args = array (\n // don't show this CPT on the front-end\n 'public' =&gt; false,\n // but do allow it to be managed on the back-end\n 'show_ui' =&gt; true,\n // other register_post_type() args\n ) ;\nregister_post_type ('my_cpt', $args) ;\n</code></pre>\n" }, { "answer_id": 258956, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>Sparrow Hawk is correct, as \"public' affects several other args options. So, while his solution will work, if you want to avoid having to make some other add'l changes because everything else is working, just set the arg you want to false, which is this one:</p>\n\n<pre><code>'publicly_queryable' =&gt; false,\n</code></pre>\n\n<p>Add this line to the register_post_type function creating your custom post type and you won't have to make any other changes to the code. </p>\n\n<p>ALSO. Be sure to flush your permalinks after you make this change or you won't see any evidence of the change.</p>\n\n<p>(to flush them, go to settings / permalinks and hit save)</p>\n" }, { "answer_id": 258957, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 0, "selected": false, "text": "<p>This is what you are looking for: </p>\n\n<pre><code>/**\n * Remove the slug from custom post type permalinks.\n */\nfunction wpex_remove_cpt_slug( $post_link, $post, $leavename ) {\n\n if ( ! in_array( $post-&gt;post_type, array( 'YOUR_POST_TYPE_NAME' ) ) || 'publish' != $post-&gt;post_status ) {\n return $post_link;\n }\n\n $post_link = str_replace( '/' . $post-&gt;post_type . '/', '/', $post_link );\n\n return $post_link;\n\n}\nadd_filter( 'post_type_link', 'wpex_remove_cpt_slug', 10, 3 );\n\n/**\n * Some hackery to have WordPress match postname to any of our public post types\n * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts\n * Typically core only accounts for posts and pages where the slug is /post-name/\n */\nfunction wpex_parse_request_tricksy( $query ) {\n\n // Only noop the main query\n if ( ! $query-&gt;is_main_query() ) {\n return;\n }\n\n // Only noop our very specific rewrite rule match\n if ( 2 != count( $query-&gt;query ) || ! isset( $query-&gt;query['page'] ) ) {\n return;\n }\n\n // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match\n if ( ! empty( $query-&gt;query['name'] ) ) {\n $query-&gt;set( 'post_type', array( 'post', 'YOUR_POST_TYPE_NAME', 'page' ) );\n }\n\n}\nadd_action( 'pre_get_posts', 'wpex_parse_request_tricksy' );\n</code></pre>\n\n<p>Change \"YOUR_POST_TYPE_NAME\" with your post type name.</p>\n" } ]
2017/03/05
[ "https://wordpress.stackexchange.com/questions/258947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114781/" ]
i create a Custom Post and i don't want them has a URL. There is a URL like that = site.com/custom-slug/and-id-or-title [![enter image description here](https://i.stack.imgur.com/ldPvd.png)](https://i.stack.imgur.com/ldPvd.png) and i don't want this, how i can do that? Thank you already!
If I correctly understand the question you're asking, you don't want your CPT to be directly available on the front-end. If so, then just set `'public' => false` when you register the post\_type. Remember that various other args to [register\_post\_type()](https://developer.wordpress.org/reference/functions/register_post_type/) default to the value of `public` (e.g., `show_ui`), show when you set `'public' => false` you often times need to explicitly set those args to true, e.g. ``` $args = array ( // don't show this CPT on the front-end 'public' => false, // but do allow it to be managed on the back-end 'show_ui' => true, // other register_post_type() args ) ; register_post_type ('my_cpt', $args) ; ```
258,960
<p>I tired esc_url but it doesn't work.</p> <pre><code>if ( $power_by ) { ?&gt; &lt;div class="sponsor-credits"&gt; &lt;span class="sponsor-credits__label"&gt;Powered by &lt;/span&gt; &lt;span class="sponsor-credits__sponsor"&gt; &lt;?php if ( $sponsor_link ) { printf( '&lt;a href="%1$s" class="sponsor-credits__link" target="_blank" alt="%2$s"&gt;%3$s&lt;/a&gt;', esc_url( $sponsor_link ), esc_attr( $sponsor_name ), $power_by ); </code></pre> <p>$power_by is this</p> <pre><code>$power_by = '&lt;img class="sponsor-credits__logo" src="' . esc_url( $sponsor_logo[0] ) . '"&gt;'; </code></pre>
[ { "answer_id": 258948, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 1, "selected": true, "text": "<p>If I correctly understand the question you're asking, you don't want your CPT to be directly available on the front-end. If so, then just set <code>'public' =&gt; false</code> when you register the post_type.</p>\n\n<p>Remember that various other args to <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register_post_type()</a> default to the value of <code>public</code> (e.g., <code>show_ui</code>), show when you set <code>'public' =&gt; false</code> you often times need to explicitly set those args to true, e.g.</p>\n\n<pre><code>$args = array (\n // don't show this CPT on the front-end\n 'public' =&gt; false,\n // but do allow it to be managed on the back-end\n 'show_ui' =&gt; true,\n // other register_post_type() args\n ) ;\nregister_post_type ('my_cpt', $args) ;\n</code></pre>\n" }, { "answer_id": 258956, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>Sparrow Hawk is correct, as \"public' affects several other args options. So, while his solution will work, if you want to avoid having to make some other add'l changes because everything else is working, just set the arg you want to false, which is this one:</p>\n\n<pre><code>'publicly_queryable' =&gt; false,\n</code></pre>\n\n<p>Add this line to the register_post_type function creating your custom post type and you won't have to make any other changes to the code. </p>\n\n<p>ALSO. Be sure to flush your permalinks after you make this change or you won't see any evidence of the change.</p>\n\n<p>(to flush them, go to settings / permalinks and hit save)</p>\n" }, { "answer_id": 258957, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 0, "selected": false, "text": "<p>This is what you are looking for: </p>\n\n<pre><code>/**\n * Remove the slug from custom post type permalinks.\n */\nfunction wpex_remove_cpt_slug( $post_link, $post, $leavename ) {\n\n if ( ! in_array( $post-&gt;post_type, array( 'YOUR_POST_TYPE_NAME' ) ) || 'publish' != $post-&gt;post_status ) {\n return $post_link;\n }\n\n $post_link = str_replace( '/' . $post-&gt;post_type . '/', '/', $post_link );\n\n return $post_link;\n\n}\nadd_filter( 'post_type_link', 'wpex_remove_cpt_slug', 10, 3 );\n\n/**\n * Some hackery to have WordPress match postname to any of our public post types\n * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts\n * Typically core only accounts for posts and pages where the slug is /post-name/\n */\nfunction wpex_parse_request_tricksy( $query ) {\n\n // Only noop the main query\n if ( ! $query-&gt;is_main_query() ) {\n return;\n }\n\n // Only noop our very specific rewrite rule match\n if ( 2 != count( $query-&gt;query ) || ! isset( $query-&gt;query['page'] ) ) {\n return;\n }\n\n // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match\n if ( ! empty( $query-&gt;query['name'] ) ) {\n $query-&gt;set( 'post_type', array( 'post', 'YOUR_POST_TYPE_NAME', 'page' ) );\n }\n\n}\nadd_action( 'pre_get_posts', 'wpex_parse_request_tricksy' );\n</code></pre>\n\n<p>Change \"YOUR_POST_TYPE_NAME\" with your post type name.</p>\n" } ]
2017/03/05
[ "https://wordpress.stackexchange.com/questions/258960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114789/" ]
I tired esc\_url but it doesn't work. ``` if ( $power_by ) { ?> <div class="sponsor-credits"> <span class="sponsor-credits__label">Powered by </span> <span class="sponsor-credits__sponsor"> <?php if ( $sponsor_link ) { printf( '<a href="%1$s" class="sponsor-credits__link" target="_blank" alt="%2$s">%3$s</a>', esc_url( $sponsor_link ), esc_attr( $sponsor_name ), $power_by ); ``` $power\_by is this ``` $power_by = '<img class="sponsor-credits__logo" src="' . esc_url( $sponsor_logo[0] ) . '">'; ```
If I correctly understand the question you're asking, you don't want your CPT to be directly available on the front-end. If so, then just set `'public' => false` when you register the post\_type. Remember that various other args to [register\_post\_type()](https://developer.wordpress.org/reference/functions/register_post_type/) default to the value of `public` (e.g., `show_ui`), show when you set `'public' => false` you often times need to explicitly set those args to true, e.g. ``` $args = array ( // don't show this CPT on the front-end 'public' => false, // but do allow it to be managed on the back-end 'show_ui' => true, // other register_post_type() args ) ; register_post_type ('my_cpt', $args) ; ```
258,974
<p>I'm using the University Hub theme <a href="http://wenthemes.com/item/wordpress-themes/university-hub/" rel="nofollow noreferrer">http://wenthemes.com/item/wordpress-themes/university-hub/</a> and I searched a lot and didn't found a solution. I want to change the main logo on each page of the site. I managed to change with CSS the header background color but for the logo it seems I need a custom solution for this theme, but I really don't know how to do it, any help will be appreciated. Thanks! :D P.D.: I am already using a child theme.</p>
[ { "answer_id": 258975, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>This is not specific to WordPress however you could try removing the header hook and adding it back with a image from a custom field or the featured image meta box. Then output using your header hook <code>university_hub_action_header</code> all from the safety of a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\"><code>child theme</code></a>.</p>\n\n<p>Or</p>\n\n<p>You could filter the custom logo using custom fields or the post thumbnail as your input.</p>\n" }, { "answer_id": 258978, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 2, "selected": true, "text": "<p>I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug:</p>\n\n<p><strong>PHP:</strong></p>\n\n<pre><code>/**\n *\n * Add Page/Post Body Class Slug\n *\n * post-slug-for-post\n * page-slug-for-page\n *\n *\n */\nfunction yourprefix_page_slug_body_class( $classes ) {\n global $post;\n if ( isset( $post ) ) {\n $classes[] = $post-&gt;post_type . '-' . $post-&gt;post_name;\n }\n return $classes;\n}\nadd_filter( 'body_class', 'yourprefix_page_slug_body_class' );\n</code></pre>\n\n<p>Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses <code>.site-branding</code>).</p>\n\n<p><strong>jQuery</strong></p>\n\n<pre><code> ( function( window, $, undefined ) {\n\n 'use strict';\n\n\n $( document ).ready( function( ) {\n\n\n /* ==== change logo based on body class ===\n\n // default logo and path\n var path = 'http://yourdomain.com/wp-content/uploads/',\n logo = 'logo-1.png'; // this is the default\n\n\n // logo 2 conditional change var value\n if ( $( 'body' ).is( '.page-such-and-such' ) ) {\n logo = 'logo-2.png';\n }\n\n // logo 3 conditional change var value\n if ( $( 'body' ).is( '.post-such-and-thing' ) ) {\n logo = 'logo-3.png';\n }\n\n // return the logo src\n $( '.site-branding img' ).attr( 'src', path + logo );\n\n\n // end swapping logo\n\n\n } ); //* end ready\n\n\n} )( this, jQuery );\n</code></pre>\n\n<p>Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.</p>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/258974", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109894/" ]
I'm using the University Hub theme <http://wenthemes.com/item/wordpress-themes/university-hub/> and I searched a lot and didn't found a solution. I want to change the main logo on each page of the site. I managed to change with CSS the header background color but for the logo it seems I need a custom solution for this theme, but I really don't know how to do it, any help will be appreciated. Thanks! :D P.D.: I am already using a child theme.
I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug: **PHP:** ``` /** * * Add Page/Post Body Class Slug * * post-slug-for-post * page-slug-for-page * * */ function yourprefix_page_slug_body_class( $classes ) { global $post; if ( isset( $post ) ) { $classes[] = $post->post_type . '-' . $post->post_name; } return $classes; } add_filter( 'body_class', 'yourprefix_page_slug_body_class' ); ``` Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses `.site-branding`). **jQuery** ``` ( function( window, $, undefined ) { 'use strict'; $( document ).ready( function( ) { /* ==== change logo based on body class === // default logo and path var path = 'http://yourdomain.com/wp-content/uploads/', logo = 'logo-1.png'; // this is the default // logo 2 conditional change var value if ( $( 'body' ).is( '.page-such-and-such' ) ) { logo = 'logo-2.png'; } // logo 3 conditional change var value if ( $( 'body' ).is( '.post-such-and-thing' ) ) { logo = 'logo-3.png'; } // return the logo src $( '.site-branding img' ).attr( 'src', path + logo ); // end swapping logo } ); //* end ready } )( this, jQuery ); ``` Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.
258,982
<p>I've code to display ACF gallery:</p> <pre><code>&lt;?php $images = get_field('portfolio'); if( $images ): ?&gt; &lt;div class="row"&gt; &lt;?php foreach( $images as $image ): ?&gt; &lt;div class="col-lg-3"&gt; &lt;a href="&lt;?php echo $image['url']; ?&gt;"&gt; &lt;img src="&lt;?php echo $image['sizes']['thumb_front']; ?&gt;" alt="&lt;?php echo $image['alt']; ?&gt;" class="img-responsive"/&gt; &lt;/a&gt; &lt;p&gt;&lt;?php echo $image['caption']; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>And I need to wrap every 4 item <code>&lt;div class="col-lg-3"&gt;</code> into the <code>&lt;div class="row"&gt;</code> How can I do this, guys?</p>
[ { "answer_id": 258975, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>This is not specific to WordPress however you could try removing the header hook and adding it back with a image from a custom field or the featured image meta box. Then output using your header hook <code>university_hub_action_header</code> all from the safety of a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\"><code>child theme</code></a>.</p>\n\n<p>Or</p>\n\n<p>You could filter the custom logo using custom fields or the post thumbnail as your input.</p>\n" }, { "answer_id": 258978, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 2, "selected": true, "text": "<p>I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug:</p>\n\n<p><strong>PHP:</strong></p>\n\n<pre><code>/**\n *\n * Add Page/Post Body Class Slug\n *\n * post-slug-for-post\n * page-slug-for-page\n *\n *\n */\nfunction yourprefix_page_slug_body_class( $classes ) {\n global $post;\n if ( isset( $post ) ) {\n $classes[] = $post-&gt;post_type . '-' . $post-&gt;post_name;\n }\n return $classes;\n}\nadd_filter( 'body_class', 'yourprefix_page_slug_body_class' );\n</code></pre>\n\n<p>Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses <code>.site-branding</code>).</p>\n\n<p><strong>jQuery</strong></p>\n\n<pre><code> ( function( window, $, undefined ) {\n\n 'use strict';\n\n\n $( document ).ready( function( ) {\n\n\n /* ==== change logo based on body class ===\n\n // default logo and path\n var path = 'http://yourdomain.com/wp-content/uploads/',\n logo = 'logo-1.png'; // this is the default\n\n\n // logo 2 conditional change var value\n if ( $( 'body' ).is( '.page-such-and-such' ) ) {\n logo = 'logo-2.png';\n }\n\n // logo 3 conditional change var value\n if ( $( 'body' ).is( '.post-such-and-thing' ) ) {\n logo = 'logo-3.png';\n }\n\n // return the logo src\n $( '.site-branding img' ).attr( 'src', path + logo );\n\n\n // end swapping logo\n\n\n } ); //* end ready\n\n\n} )( this, jQuery );\n</code></pre>\n\n<p>Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.</p>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/258982", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48584/" ]
I've code to display ACF gallery: ``` <?php $images = get_field('portfolio'); if( $images ): ?> <div class="row"> <?php foreach( $images as $image ): ?> <div class="col-lg-3"> <a href="<?php echo $image['url']; ?>"> <img src="<?php echo $image['sizes']['thumb_front']; ?>" alt="<?php echo $image['alt']; ?>" class="img-responsive"/> </a> <p><?php echo $image['caption']; ?></p> </div> <?php endforeach; ?> </div> <?php endif; ?> ``` And I need to wrap every 4 item `<div class="col-lg-3">` into the `<div class="row">` How can I do this, guys?
I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug: **PHP:** ``` /** * * Add Page/Post Body Class Slug * * post-slug-for-post * page-slug-for-page * * */ function yourprefix_page_slug_body_class( $classes ) { global $post; if ( isset( $post ) ) { $classes[] = $post->post_type . '-' . $post->post_name; } return $classes; } add_filter( 'body_class', 'yourprefix_page_slug_body_class' ); ``` Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses `.site-branding`). **jQuery** ``` ( function( window, $, undefined ) { 'use strict'; $( document ).ready( function( ) { /* ==== change logo based on body class === // default logo and path var path = 'http://yourdomain.com/wp-content/uploads/', logo = 'logo-1.png'; // this is the default // logo 2 conditional change var value if ( $( 'body' ).is( '.page-such-and-such' ) ) { logo = 'logo-2.png'; } // logo 3 conditional change var value if ( $( 'body' ).is( '.post-such-and-thing' ) ) { logo = 'logo-3.png'; } // return the logo src $( '.site-branding img' ).attr( 'src', path + logo ); // end swapping logo } ); //* end ready } )( this, jQuery ); ``` Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.
258,995
<p>I am a newbie who recently start working on XAMPP and I am unable to access wp-admin on XAMPP server localhost. While installing WordPress, it asked me for user name and password too but when I am trying to access wp-admin with username and password, it says "INVALID USER NAME". As far as I know, I am putting the correct username and password here.</p> <p>Please suggest how to login back and where will I get the correct user details.</p> <p>Thanks</p>
[ { "answer_id": 258975, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>This is not specific to WordPress however you could try removing the header hook and adding it back with a image from a custom field or the featured image meta box. Then output using your header hook <code>university_hub_action_header</code> all from the safety of a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\"><code>child theme</code></a>.</p>\n\n<p>Or</p>\n\n<p>You could filter the custom logo using custom fields or the post thumbnail as your input.</p>\n" }, { "answer_id": 258978, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 2, "selected": true, "text": "<p>I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug:</p>\n\n<p><strong>PHP:</strong></p>\n\n<pre><code>/**\n *\n * Add Page/Post Body Class Slug\n *\n * post-slug-for-post\n * page-slug-for-page\n *\n *\n */\nfunction yourprefix_page_slug_body_class( $classes ) {\n global $post;\n if ( isset( $post ) ) {\n $classes[] = $post-&gt;post_type . '-' . $post-&gt;post_name;\n }\n return $classes;\n}\nadd_filter( 'body_class', 'yourprefix_page_slug_body_class' );\n</code></pre>\n\n<p>Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses <code>.site-branding</code>).</p>\n\n<p><strong>jQuery</strong></p>\n\n<pre><code> ( function( window, $, undefined ) {\n\n 'use strict';\n\n\n $( document ).ready( function( ) {\n\n\n /* ==== change logo based on body class ===\n\n // default logo and path\n var path = 'http://yourdomain.com/wp-content/uploads/',\n logo = 'logo-1.png'; // this is the default\n\n\n // logo 2 conditional change var value\n if ( $( 'body' ).is( '.page-such-and-such' ) ) {\n logo = 'logo-2.png';\n }\n\n // logo 3 conditional change var value\n if ( $( 'body' ).is( '.post-such-and-thing' ) ) {\n logo = 'logo-3.png';\n }\n\n // return the logo src\n $( '.site-branding img' ).attr( 'src', path + logo );\n\n\n // end swapping logo\n\n\n } ); //* end ready\n\n\n} )( this, jQuery );\n</code></pre>\n\n<p>Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.</p>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/258995", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114807/" ]
I am a newbie who recently start working on XAMPP and I am unable to access wp-admin on XAMPP server localhost. While installing WordPress, it asked me for user name and password too but when I am trying to access wp-admin with username and password, it says "INVALID USER NAME". As far as I know, I am putting the correct username and password here. Please suggest how to login back and where will I get the correct user details. Thanks
I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug: **PHP:** ``` /** * * Add Page/Post Body Class Slug * * post-slug-for-post * page-slug-for-page * * */ function yourprefix_page_slug_body_class( $classes ) { global $post; if ( isset( $post ) ) { $classes[] = $post->post_type . '-' . $post->post_name; } return $classes; } add_filter( 'body_class', 'yourprefix_page_slug_body_class' ); ``` Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses `.site-branding`). **jQuery** ``` ( function( window, $, undefined ) { 'use strict'; $( document ).ready( function( ) { /* ==== change logo based on body class === // default logo and path var path = 'http://yourdomain.com/wp-content/uploads/', logo = 'logo-1.png'; // this is the default // logo 2 conditional change var value if ( $( 'body' ).is( '.page-such-and-such' ) ) { logo = 'logo-2.png'; } // logo 3 conditional change var value if ( $( 'body' ).is( '.post-such-and-thing' ) ) { logo = 'logo-3.png'; } // return the logo src $( '.site-branding img' ).attr( 'src', path + logo ); // end swapping logo } ); //* end ready } )( this, jQuery ); ``` Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.
258,999
<p>I have a url structure like this where taobao is a page:</p> <pre><code>http://website.com/taobao/?item=123123 </code></pre> <p>I need to change it to like this </p> <pre><code>http://website.com/taobao/item/123123 </code></pre> <p>I have tried this but it doesn't work </p> <pre><code> add_rewrite_rule( 'product/([^/]+)', 'index.php?product=$matches[1]', 'top' ); </code></pre>
[ { "answer_id": 258975, "author": "Dev", "author_id": 104464, "author_profile": "https://wordpress.stackexchange.com/users/104464", "pm_score": 0, "selected": false, "text": "<p>This is not specific to WordPress however you could try removing the header hook and adding it back with a image from a custom field or the featured image meta box. Then output using your header hook <code>university_hub_action_header</code> all from the safety of a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\"><code>child theme</code></a>.</p>\n\n<p>Or</p>\n\n<p>You could filter the custom logo using custom fields or the post thumbnail as your input.</p>\n" }, { "answer_id": 258978, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 2, "selected": true, "text": "<p>I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug:</p>\n\n<p><strong>PHP:</strong></p>\n\n<pre><code>/**\n *\n * Add Page/Post Body Class Slug\n *\n * post-slug-for-post\n * page-slug-for-page\n *\n *\n */\nfunction yourprefix_page_slug_body_class( $classes ) {\n global $post;\n if ( isset( $post ) ) {\n $classes[] = $post-&gt;post_type . '-' . $post-&gt;post_name;\n }\n return $classes;\n}\nadd_filter( 'body_class', 'yourprefix_page_slug_body_class' );\n</code></pre>\n\n<p>Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses <code>.site-branding</code>).</p>\n\n<p><strong>jQuery</strong></p>\n\n<pre><code> ( function( window, $, undefined ) {\n\n 'use strict';\n\n\n $( document ).ready( function( ) {\n\n\n /* ==== change logo based on body class ===\n\n // default logo and path\n var path = 'http://yourdomain.com/wp-content/uploads/',\n logo = 'logo-1.png'; // this is the default\n\n\n // logo 2 conditional change var value\n if ( $( 'body' ).is( '.page-such-and-such' ) ) {\n logo = 'logo-2.png';\n }\n\n // logo 3 conditional change var value\n if ( $( 'body' ).is( '.post-such-and-thing' ) ) {\n logo = 'logo-3.png';\n }\n\n // return the logo src\n $( '.site-branding img' ).attr( 'src', path + logo );\n\n\n // end swapping logo\n\n\n } ); //* end ready\n\n\n} )( this, jQuery );\n</code></pre>\n\n<p>Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.</p>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/258999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91745/" ]
I have a url structure like this where taobao is a page: ``` http://website.com/taobao/?item=123123 ``` I need to change it to like this ``` http://website.com/taobao/item/123123 ``` I have tried this but it doesn't work ``` add_rewrite_rule( 'product/([^/]+)', 'index.php?product=$matches[1]', 'top' ); ```
I would add a filter to the body class in your functions.php file. This will add a class based on the page/post/cpt slug: **PHP:** ``` /** * * Add Page/Post Body Class Slug * * post-slug-for-post * page-slug-for-page * * */ function yourprefix_page_slug_body_class( $classes ) { global $post; if ( isset( $post ) ) { $classes[] = $post->post_type . '-' . $post->post_name; } return $classes; } add_filter( 'body_class', 'yourprefix_page_slug_body_class' ); ``` Then I would use jQuery to swap the src based on the body class. You will need to change the path variable and possibly the parent class where the logo img is located (the example uses `.site-branding`). **jQuery** ``` ( function( window, $, undefined ) { 'use strict'; $( document ).ready( function( ) { /* ==== change logo based on body class === // default logo and path var path = 'http://yourdomain.com/wp-content/uploads/', logo = 'logo-1.png'; // this is the default // logo 2 conditional change var value if ( $( 'body' ).is( '.page-such-and-such' ) ) { logo = 'logo-2.png'; } // logo 3 conditional change var value if ( $( 'body' ).is( '.post-such-and-thing' ) ) { logo = 'logo-3.png'; } // return the logo src $( '.site-branding img' ).attr( 'src', path + logo ); // end swapping logo } ); //* end ready } )( this, jQuery ); ``` Create a document with your code editor name it swapping-logo.js (or whatever) and enqueue it with jQuery as a dep. The instructions on adding js to your theme are everywhere.
259,007
<p>How do I change the height of the header image (specified in the Header Media section) in the Twenty Seventeen Theme?</p> <p>Specifically I want to change it on the home page because here it fills up nearly the entire page. I want it to be much shorter. The way it appears on other pages such as the built-in About page has a good height so if I could mimic that on the home page I would be satisfied. Although knowing how to do precise control would be great.</p>
[ { "answer_id": 259015, "author": "lalitpendhare", "author_id": 114472, "author_profile": "https://wordpress.stackexchange.com/users/114472", "pm_score": 0, "selected": false, "text": "<p>You can be changed it by cropping the image. in WordPress, there is an option as customizer. You need to follow below steps for cropping image.</p>\n\n<pre><code> 1) Go appearance-&gt;customize\n 2) Header media\n 3) add a new image and then crop that image as per your needs and you go.\n</code></pre>\n" }, { "answer_id": 259093, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>You could use Firebug (or look at the page source code) to find the CSS used to display the header image. Then add the CSS to make the change. The exact CSS you use is dependent on the theme.</p>\n\n<p>Firebug lets you change the CSS temporarily to get it how you want, then copy that new CSS into the CSS page of the theme (if it has that option).</p>\n\n<p>If there is no 'custom CSS' option in your theme, then best way is to create a child theme (lots of tutorials on that), and add your custom css into that child theme's styles.css page. (Never change the parent theme; your changes will be overwritten on the next theme update.)</p>\n" }, { "answer_id": 259108, "author": "User", "author_id": 52057, "author_profile": "https://wordpress.stackexchange.com/users/52057", "pm_score": 2, "selected": false, "text": "<p>I found (part) of the css code that controls the height in <code>wp-content/themes/twentyseventeen/style.css</code>. </p>\n\n<p>There is code that applies when the admin bar <em>is not</em> visible (typical anonymous user) currently at line 3629</p>\n\n<pre><code>.twentyseventeen-front-page.has-header-image .custom-header-media,\n.twentyseventeen-front-page.has-header-video .custom-header-media,\n.home.blog.has-header-image .custom-header-media,\n.home.blog.has-header-video .custom-header-media {\n height: 1200px;\n height: 100vh;\n max-height: 100%;\n overflow: hidden;\n}\n</code></pre>\n\n<p>And code that applies when the admin bar <em>is</em> visible (e.g. you are logged in) currently at line 3646</p>\n\n<pre><code>.admin-bar.twentyseventeen-front-page.has-header-image .custom-header-media,\n.admin-bar.twentyseventeen-front-page.has-header-video .custom-header-media,\n.admin-bar.home.blog.has-header-image .custom-header-media,\n.admin-bar.home.blog.has-header-video .custom-header-media {\n height: calc(100vh - 32px);\n}\n</code></pre>\n\n<p>And then code that applies on mobile currently at line 1638:</p>\n\n<pre><code>.has-header-image.twentyseventeen-front-page .custom-header,\n.has-header-video.twentyseventeen-front-page .custom-header,\n.has-header-image.home.blog .custom-header,\n.has-header-video.home.blog .custom-header {\n display: table;\n height: 300px;\n height: 75vh;\n width: 100%;\n}\n</code></pre>\n\n<p>By copying these three sections of css into my child theme's style.css and modifying the <code>height</code> attribute I was able to tweak the height for the header image on the home page. I set the height to <code>30vh</code>, <code>calc(30vh - 32px)</code>, and <code>30vh</code> respectively in each section. I left the first <code>height: 1200px</code> alone.</p>\n\n<p>Note the height element is set at <code>100vh</code> which sizes the height relative to the viewport height. So 100vh is 100% of the viewport while 50vh is 50% of the viewport.</p>\n\n<p>One odd thing is that on the home page the zoom and position of the header image is different than on other pages.</p>\n\n<p>Not sure if this is the best way. I'm open to better options but so far it's working at a basic level.</p>\n" }, { "answer_id": 275990, "author": "Madivad", "author_id": 37314, "author_profile": "https://wordpress.stackexchange.com/users/37314", "pm_score": 1, "selected": false, "text": "<p>From a comment I made in @User's answer (that's a cool name) ;) I thought I would give it a go.</p>\n\n<p>I am editing the theme file directly because I am working in a throw-away docker container, it is more proof of concept. Adapting it to a child theme will need some tweaking.</p>\n\n<p>In <code>content/themes/twentyseventeen/style.css</code> in the area between 3680~3670ish is where the header image lies. </p>\n\n<p>original code:</p>\n\n<pre><code>.twentyseventeen-front-page.has-header-image .custom-header-media,\n.twentyseventeen-front-page.has-header-video .custom-header-media,\n.home.blog.has-header-image .custom-header-media,\n.home.blog.has-header-video .custom-header-media {\n height: 1200px;\n height: 100vh;\n max-height: 100%;\n overflow: hidden;\n}\n</code></pre>\n\n<p>Changing the size (and order) is good enough to achieve the logged out view:</p>\n\n<pre><code> height: 100vh; \n height: 100%; \n max-height: 500px;\n</code></pre>\n\n<p>I have left the <code>vh</code> and the <code>%</code> to cover those bases where <code>max-height</code> isn't reached, but then set the <code>max-height</code> to what you're after. </p>\n\n<p>There is one caveat to all this:</p>\n\n<p>It's the very top section of pixels. So unless you have a nice portion of image in that area... It looks crappy (many heads chopped off)</p>\n\n<p>more to follow (when I sort it out)</p>\n" }, { "answer_id": 299045, "author": "Ralph", "author_id": 140556, "author_profile": "https://wordpress.stackexchange.com/users/140556", "pm_score": 2, "selected": false, "text": "<p>Just edit the theme from the dashboard and add the following CSS definition into the theme section \"custom css\":</p>\n\n<pre><code>.has-header-image.home.blog .custom-header {\n height: 26vh;\n}\n</code></pre>\n" }, { "answer_id": 357357, "author": "Paris Finley", "author_id": 181750, "author_profile": "https://wordpress.stackexchange.com/users/181750", "pm_score": 0, "selected": false, "text": "<p>I approached this by first setting up a child theme (recommended step by WP). Then in the style.css file of the child theme, I added the css below. The first section controls the height of the image on the front page; the second section controls the height of the space for the image on the front page. Both have to match for this to work. I commented out some lines that interfered with my fixed height image. Now my header on the home page is exactly the same as on all other pages.</p>\n\n<pre><code>.has-header-image .custom-header-media img, \n.has-header-video .custom-header-media video, \n.has-header-image:not(.twentyseventeen-front-page):not(.home) .custom-header-media img {\n /* height: 100%; */\n height: 400px;\n left: 0;\n -o-object-fit: cover;\n object-fit: cover;\n top: 0;\n -ms-transform: none;\n -moz-transform: none;\n -webkit-transform: none;\n transform: none;\n width: 100%;\n}\n.twentyseventeen-front-page.has-header-image .custom-header-media, \n.twentyseventeen-front-page.has-header-video .custom-header-media, \n.home.blog.has-header-image .custom-header-media, \n.home.blog.has-header-video .custom-header-media {\n height: 400px;\n /* height: 100vh; */\n /* max-height: 100%; */\n overflow: hidden;\n}\n</code></pre>\n" }, { "answer_id": 377088, "author": "Victor", "author_id": 196587, "author_profile": "https://wordpress.stackexchange.com/users/196587", "pm_score": 0, "selected": false, "text": "<p>I found this solved my problem, where the object-position allowed me to move the image left and right/up and down.</p>\n<pre><code>img.wp-image-70 {\n max-height:250px;\n object-position: 0 10%;\n object-fit: cover;\n}\n</code></pre>\n" }, { "answer_id": 405051, "author": "Morcilla de Arroz", "author_id": 221504, "author_profile": "https://wordpress.stackexchange.com/users/221504", "pm_score": 1, "selected": false, "text": "<p>Stole from <a href=\"https://medium.com/@bharatkaravadra/how-to-reduce-the-header-height-size-of-the-twenty-seventeen-theme-front-page-562f1230044c\" rel=\"nofollow noreferrer\">this site</a></p>\n<p>This additional/custom CSS worked for me :</p>\n<pre><code>/*Computer screen */\n@media screen and (min-width: 48em) {\n .twentyseventeen-front-page.has-header-image .custom-header-image {\n /*height: 1200px;*/\n /*height: 100vh;*/\n height: 50vh;\n /*max-height: 100%;*/\n /*overflow: hidden;*/\n }\n}\n\n/* Mobile screen*/\n.has-header-image.twentyseventeen-front-page .custom-header {\n /*display: table;*/\n /*height: 300px;*/\n /*height: 75vh;*/\n height: 50vh;\n /*width: 100%;*/\n}\n\n/* Computer screen with logged in user and admin bar showing on front end*/\n@media screen and (min-width: 48em) {\n .admin-bar.twentyseventeen-front-page.has-header-image .custom-header-image {\n /*height: calc(100vh - 32px);*/\n height: calc(50vh - 32px);\n }\n}\n</code></pre>\n<p>You can set the desired height oh 'height' attributes.</p>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/259007", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52057/" ]
How do I change the height of the header image (specified in the Header Media section) in the Twenty Seventeen Theme? Specifically I want to change it on the home page because here it fills up nearly the entire page. I want it to be much shorter. The way it appears on other pages such as the built-in About page has a good height so if I could mimic that on the home page I would be satisfied. Although knowing how to do precise control would be great.
I found (part) of the css code that controls the height in `wp-content/themes/twentyseventeen/style.css`. There is code that applies when the admin bar *is not* visible (typical anonymous user) currently at line 3629 ``` .twentyseventeen-front-page.has-header-image .custom-header-media, .twentyseventeen-front-page.has-header-video .custom-header-media, .home.blog.has-header-image .custom-header-media, .home.blog.has-header-video .custom-header-media { height: 1200px; height: 100vh; max-height: 100%; overflow: hidden; } ``` And code that applies when the admin bar *is* visible (e.g. you are logged in) currently at line 3646 ``` .admin-bar.twentyseventeen-front-page.has-header-image .custom-header-media, .admin-bar.twentyseventeen-front-page.has-header-video .custom-header-media, .admin-bar.home.blog.has-header-image .custom-header-media, .admin-bar.home.blog.has-header-video .custom-header-media { height: calc(100vh - 32px); } ``` And then code that applies on mobile currently at line 1638: ``` .has-header-image.twentyseventeen-front-page .custom-header, .has-header-video.twentyseventeen-front-page .custom-header, .has-header-image.home.blog .custom-header, .has-header-video.home.blog .custom-header { display: table; height: 300px; height: 75vh; width: 100%; } ``` By copying these three sections of css into my child theme's style.css and modifying the `height` attribute I was able to tweak the height for the header image on the home page. I set the height to `30vh`, `calc(30vh - 32px)`, and `30vh` respectively in each section. I left the first `height: 1200px` alone. Note the height element is set at `100vh` which sizes the height relative to the viewport height. So 100vh is 100% of the viewport while 50vh is 50% of the viewport. One odd thing is that on the home page the zoom and position of the header image is different than on other pages. Not sure if this is the best way. I'm open to better options but so far it's working at a basic level.
259,039
<p>I am using wordpress as a submodule and capristrano to deploy.</p> <p>The deployment seems to work correctly and i am able to log in to wp-admin, but when i look at my themes </p> <pre><code>ERROR: The theme directory "sage-master" does not exist. </code></pre> <p>The submodule setup adds the wp-content files to site_url.com/content ie site_url.com/content/themes site_url.com/content/plugins etc</p> <p>Within my wp-config I have </p> <pre><code>define('WP_CONTENT_URL', 'http://site_url.com/content'); define('WP_CONTENT_DIR', realpath($_SERVER['DOCUMENT_ROOT'] . '/content')); </code></pre> <p>This has always worked before, I feel as though Im just making a silly mistake somewhere.</p> <p>Ive checked the DB and the site_url and home are set correctly.</p> <p>Any ideas on what I may have missed?</p> <p>Thanks Nad</p>
[ { "answer_id": 259088, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Look for a folder called 'sage-master' in the themes folder of wp-content. If not found, a similarly-named folder might contain it. Rename the folder to 'sage-master'.</p>\n\n<p>Another way would be to just reinstall the theme. That should put it in the proper place for WP to find.</p>\n" }, { "answer_id": 259097, "author": "Scott", "author_id": 111485, "author_profile": "https://wordpress.stackexchange.com/users/111485", "pm_score": 1, "selected": false, "text": "<p>I'm giving possible cases from the top of my head:</p>\n\n<p><strong><em>Case 1:</em></strong> May be it's related to <a href=\"http://php.net/manual/en/function.realpath.php\" rel=\"nofollow noreferrer\"><code>realpath()</code></a> function. <code>realpath()</code> acts differently in different OS. Also, it returns <code>false</code> if the web server user doesn't have executable permission on the corresponding directory. There are some other problems too, so better try this:</p>\n\n<pre><code>// change it based on the location of wp-config.php file\ndefine( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/content' );\n</code></pre>\n\n<p><strong><em>Case 2:</em></strong> May be the <code>sage-master</code> theme directory actually doesn't exist or it's not accessible by the web server user.</p>\n\n<p><strong><em>Case 3:</em></strong> May be the directories exist but have character case different. Unix systems have case sensitive file system, but windows is case insensitive. So it may work on windows but not on Unix for this reason.</p>\n\n<p>There may be other issues, so better activate debugging in WordPress and check what errors you get.</p>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/259039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114835/" ]
I am using wordpress as a submodule and capristrano to deploy. The deployment seems to work correctly and i am able to log in to wp-admin, but when i look at my themes ``` ERROR: The theme directory "sage-master" does not exist. ``` The submodule setup adds the wp-content files to site\_url.com/content ie site\_url.com/content/themes site\_url.com/content/plugins etc Within my wp-config I have ``` define('WP_CONTENT_URL', 'http://site_url.com/content'); define('WP_CONTENT_DIR', realpath($_SERVER['DOCUMENT_ROOT'] . '/content')); ``` This has always worked before, I feel as though Im just making a silly mistake somewhere. Ive checked the DB and the site\_url and home are set correctly. Any ideas on what I may have missed? Thanks Nad
I'm giving possible cases from the top of my head: ***Case 1:*** May be it's related to [`realpath()`](http://php.net/manual/en/function.realpath.php) function. `realpath()` acts differently in different OS. Also, it returns `false` if the web server user doesn't have executable permission on the corresponding directory. There are some other problems too, so better try this: ``` // change it based on the location of wp-config.php file define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/content' ); ``` ***Case 2:*** May be the `sage-master` theme directory actually doesn't exist or it's not accessible by the web server user. ***Case 3:*** May be the directories exist but have character case different. Unix systems have case sensitive file system, but windows is case insensitive. So it may work on windows but not on Unix for this reason. There may be other issues, so better activate debugging in WordPress and check what errors you get.
259,041
<p>I'm registering a custom post type named Datasheet. When registering it, I register the callback for meta boxes</p> <pre><code>'register_meta_box_cb' =&gt; [ $this, "add_metaboxes" ] </code></pre> <p>This is my callback</p> <pre><code>function add_metaboxes ( $post ) { wp_nonce_field ( plugin_basename(__FILE__), 'datasheet_meta_nonce'); add_meta_box( ....... </code></pre> <p>Also I registered this hook</p> <pre><code>add_action ('save_post_datasheet', [ $this, 'save_datasheet_meta' ], 10, 2); </code></pre> <p>This is the callback </p> <pre><code>function save_datasheet_meta ( $post_id, $post ) { $nonce = wp_verify_nonce ( plugin_basename(__FILE__), 'datasheet_meta_nonce'); if (!$nonce) { die ("Security check failed"); } </code></pre> <p><strong>Expected/dsidered:</strong> I was expecting that this last callback is fired <em>when creating and or updating</em> but <em>ONLY IN THESE CASES</em>; so I can check the nonces.</p> <p><strong>Actual behaviour</strong> If I simply start to create a new Datasheet, I got nothing else than </p> <pre><code>Security check failed </code></pre> <p>This happens simply opening <code>domain.tld/wp-admin/post-new.php?post_type=datasheet</code> from side admin menu</p> <p>So I cannot understand WHY this action is fired just entering the page... causing my nonce check to fail.</p>
[ { "answer_id": 259044, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>You should not have a nonce in your metabox, and obviously not check for it in your save handler. </p>\n\n<p>I know everybody copied the codex page on creating metaboxes but the use of nonce there is just super wrong. Nonce is done and validated on the whole submitted form and there is no additional security, or other value by adding it into metabox.</p>\n\n<p>The only thing that the nonce do, is to validate that the submission is from the page edit and not from the quick edit, xml-rpc, or json api, but for that kind of usage you better use a simple hidden input (this might be required if your metabox contains only checkboxes). </p>\n" }, { "answer_id": 259046, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 3, "selected": true, "text": "<p>When you choose \"Your CPT > Add New\", WP calls <a href=\"https://developer.wordpress.org/reference/functions/get_default_post_to_edit/\" rel=\"nofollow noreferrer\">get_default_post_to_edit()</a>, which actually creates an \"empty\" post (with <code>'post_status' =&gt; 'auto-draft'</code>) and then calls <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow noreferrer\">wp_insert_post()</a>. This is what is causing your <code>save_datasheet_meta()</code> function to be called before you think it should.</p>\n\n<p>Hence, generally you should add some additional sanity checks to the beginning of any func you hook into <code>save_post</code>, ala:</p>\n\n<pre><code>function\nsave_datasheet_meta ($post_id, $post)\n{\n if ('auto-draft' == $post-&gt;post_status) {\n // bail, because your nonce will not be set at this point\n return ;\n }\n\n // post{,-new}.php enqueue some JS which periodically saves the post_content,\n // but NOT any post_meta\n // so, a `save_post` hook func that only cares about updating post_meta should\n // bail when DOING_AUTOSAVE is true\n if (defined ('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) {\n return ;\n }\n\n $nonce = wp_verify_nonce ( plugin_basename(__FILE__), 'datasheet_meta_nonce');\n\n if (!$nonce) {\n die (\"Security check failed\");\n }\n\n // save post_meta's here\n\n return ;\n}\n</code></pre>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/259041", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94289/" ]
I'm registering a custom post type named Datasheet. When registering it, I register the callback for meta boxes ``` 'register_meta_box_cb' => [ $this, "add_metaboxes" ] ``` This is my callback ``` function add_metaboxes ( $post ) { wp_nonce_field ( plugin_basename(__FILE__), 'datasheet_meta_nonce'); add_meta_box( ....... ``` Also I registered this hook ``` add_action ('save_post_datasheet', [ $this, 'save_datasheet_meta' ], 10, 2); ``` This is the callback ``` function save_datasheet_meta ( $post_id, $post ) { $nonce = wp_verify_nonce ( plugin_basename(__FILE__), 'datasheet_meta_nonce'); if (!$nonce) { die ("Security check failed"); } ``` **Expected/dsidered:** I was expecting that this last callback is fired *when creating and or updating* but *ONLY IN THESE CASES*; so I can check the nonces. **Actual behaviour** If I simply start to create a new Datasheet, I got nothing else than ``` Security check failed ``` This happens simply opening `domain.tld/wp-admin/post-new.php?post_type=datasheet` from side admin menu So I cannot understand WHY this action is fired just entering the page... causing my nonce check to fail.
When you choose "Your CPT > Add New", WP calls [get\_default\_post\_to\_edit()](https://developer.wordpress.org/reference/functions/get_default_post_to_edit/), which actually creates an "empty" post (with `'post_status' => 'auto-draft'`) and then calls [wp\_insert\_post()](https://developer.wordpress.org/reference/functions/wp_insert_post/). This is what is causing your `save_datasheet_meta()` function to be called before you think it should. Hence, generally you should add some additional sanity checks to the beginning of any func you hook into `save_post`, ala: ``` function save_datasheet_meta ($post_id, $post) { if ('auto-draft' == $post->post_status) { // bail, because your nonce will not be set at this point return ; } // post{,-new}.php enqueue some JS which periodically saves the post_content, // but NOT any post_meta // so, a `save_post` hook func that only cares about updating post_meta should // bail when DOING_AUTOSAVE is true if (defined ('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return ; } $nonce = wp_verify_nonce ( plugin_basename(__FILE__), 'datasheet_meta_nonce'); if (!$nonce) { die ("Security check failed"); } // save post_meta's here return ; } ```
259,083
<p>I am trying to use the customiser to set the background image of each 'post-block' to be that of any image I choose to upload. Here is my code so far.</p> <pre><code>function jhwdblog_customize_register( $wp_customize ) { $wp_customize-&gt;add_section( 'post_box_image_section' , array( 'title' =&gt; __( 'Post Box Background', 'jhwdblog' ), 'description' =&gt; 'Upload a logo to replace the post box background image', 'priority' =&gt; 30, )); $wp_customize-&gt;add_setting( 'post_box_image'); $wp_customize-&gt;add_control( new WP_Customize_Image_Control( $wp_customize, 'post_box_image', array( 'label' =&gt; __( 'Post Box Image', 'jhwdblog' ), 'section' =&gt; 'post_box_image_section', 'settings' =&gt; 'post_box_image', ))); } add_action( 'customize_register', 'jhwdblog_customize_register' ); </code></pre> <p>and in my page i'm trying to add it to the style inline like so </p> <pre><code>&lt;div class="post-block" style="background-image:url('&lt;?php echo esc_url(get_theme_mod( 'post-box-image' )); ?&gt; ');"&gt; </code></pre> <p>However all i get when i check the inspector is background-image: url((unknown)). What am i missing here?</p>
[ { "answer_id": 259050, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>Why have WP_Query() when you can just use WPDB?</p>\n\n<p>The idea is that these functions make it easier and quicker to pull data based on keywords instead of writing out SQL queries. The functions themselves will generate the necessary SQL to pull the desired data which in turn makes the development faster.</p>\n\n<p>The referenced question regarding <a href=\"https://wordpress.stackexchange.com/questions/258786/what-are-the-limitations-of-wp-update-post\"><code>wp_update_post()</code> and predefined fields</a> talks about 2 fields that are <strong>not</strong> part of a default WordPress installation which are <code>group_access</code> and <code>tag_list</code>. The <code>wp_update_post()</code> function will hit all the <strong>built-in</strong> fields just fine.</p>\n\n<p>Downsides of <code>$wpdb</code> are that you do need to know SQL and you need to be conscious of normal data sanitization and when to use <code>prepare()</code> and what functions already prepare your statement which are hardly downsides at all. The <code>$wpdb</code> Class is by nature more powerful than any of the default WordPress functions because <em>you</em> have access to <em>all</em> the data, custom or not, assuming you know the proper SQL to get, modify, or remove it.</p>\n\n<p><strong>TL;DR</strong> <code>$wpdb</code> is more powerful but less friendly and forgiving.</p>\n" }, { "answer_id": 259057, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>Most API functions have either/both actions and filters attached to them. Other plugins or themes might have code attached to these actions that won't trigger when you add/update tables directly.</p>\n\n<p>For example- a cache plugin serves pages from cache, and only refreshes the cache when a post is updated. You update the post data directly, and the cache continues to serve the old version because nothing triggered the action to refresh.</p>\n" }, { "answer_id": 259102, "author": "Scott", "author_id": 111485, "author_profile": "https://wordpress.stackexchange.com/users/111485", "pm_score": 3, "selected": true, "text": "<ol>\n<li><p><a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L3534\" rel=\"nofollow noreferrer\"><code>wp_update_post()</code></a> calls some hooks that <code>$wpdb</code> doesn't on it's own. You'll have to do it on your own to make it compatible with other plugins.</p></li>\n<li><p><code>wp_update_post()</code> calls some functions related to database entry sanitation, thumbnails, attachments, time (format, zone etc.), comment, taxonomy, meta, cache etc. So if you use <code>$wpdb</code>, make sure you handle all of them as appropriate.</p></li>\n<li><p>WordPress will update <code>wp_update_post()</code> to always keep it compatible with the current state of Database, core CODE, plugin support etc. Even if you do everything right, future updates will be difficult for you with <code>$wpdb</code>.</p></li>\n</ol>\n\n<p>So if something can be done with <code>wp_update_post()</code>, then always use it, only use <code>$wpdb</code> if your desired action related to updating post can't be done with it.</p>\n" } ]
2017/03/06
[ "https://wordpress.stackexchange.com/questions/259083", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105658/" ]
I am trying to use the customiser to set the background image of each 'post-block' to be that of any image I choose to upload. Here is my code so far. ``` function jhwdblog_customize_register( $wp_customize ) { $wp_customize->add_section( 'post_box_image_section' , array( 'title' => __( 'Post Box Background', 'jhwdblog' ), 'description' => 'Upload a logo to replace the post box background image', 'priority' => 30, )); $wp_customize->add_setting( 'post_box_image'); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'post_box_image', array( 'label' => __( 'Post Box Image', 'jhwdblog' ), 'section' => 'post_box_image_section', 'settings' => 'post_box_image', ))); } add_action( 'customize_register', 'jhwdblog_customize_register' ); ``` and in my page i'm trying to add it to the style inline like so ``` <div class="post-block" style="background-image:url('<?php echo esc_url(get_theme_mod( 'post-box-image' )); ?> ');"> ``` However all i get when i check the inspector is background-image: url((unknown)). What am i missing here?
1. [`wp_update_post()`](https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/post.php#L3534) calls some hooks that `$wpdb` doesn't on it's own. You'll have to do it on your own to make it compatible with other plugins. 2. `wp_update_post()` calls some functions related to database entry sanitation, thumbnails, attachments, time (format, zone etc.), comment, taxonomy, meta, cache etc. So if you use `$wpdb`, make sure you handle all of them as appropriate. 3. WordPress will update `wp_update_post()` to always keep it compatible with the current state of Database, core CODE, plugin support etc. Even if you do everything right, future updates will be difficult for you with `$wpdb`. So if something can be done with `wp_update_post()`, then always use it, only use `$wpdb` if your desired action related to updating post can't be done with it.
259,110
<p>Does anyone know how to programatically change link from:</p> <pre><code>&lt;a href="some_url"&gt;click&lt;/a&gt; </code></pre> <p>to:</p> <pre><code>&lt;a onclick="window.open('some_url','_blank', 'location=no')"&gt;click&lt;/a&gt; </code></pre> <p>so that all links created in the wordpress visual editor be opened via inappbrowser in a cordova app.</p> <p>this is the closest that i can get, but still doesn't work, the <code>'%link%'</code> variable doesn't change to the actual link url :</p> <pre><code>add_filter('the_content', 'changeToOnclick'); function changeToOnclick($content) { return preg_replace('/&lt;a [^&gt;]*&gt;/', "&lt;a onclick=\"window.open('%link%', '_blank', 'location=no')\"&gt;", $content); } </code></pre> <p>any help will be appreciated :)</p>
[ { "answer_id": 259114, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>There are several plugins that will do that automatically. One is \"Open External Links in New Window\" (found here <a href=\"https://wordpress.org/plugins/open-external-links-in-a-new-window/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/open-external-links-in-a-new-window/</a> ). You can probably find others if you search plugins for 'external links'.</p>\n\n<p>I use this on several sites, works well.</p>\n\n<p>If you want to roll your own, just look at the code that they use, since all plugins are (usually) open source. But, why reinvent the wheel....?</p>\n" }, { "answer_id": 259260, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 3, "selected": true, "text": "<p>Parsing HTML with regular expressions is not ideal. A better alternative is to use <code>DOMDocument</code> and <code>DOMXpath</code>;</p>\n\n<p>This code uses <code>DOMDocument</code> and <code>DOMXpath</code> to parse and modify the HTML without relying on regular expressions. Each link in the content will have the <code>onclick</code> attribute added along with the appropriate <code>window.open()</code> code using the URL pulled from the value of the <code>href</code> attribute. The <code>href</code> attribute is then removed from the link.</p>\n\n<pre><code>add_filter( 'the_content', 'wpse_cordova_links', 10, 1 );\nfunction wpse_cordova_links( $content ) {\n // Create an instance of DOMDocument.\n $dom = new \\DOMDocument();\n\n // Suppress errors due to malformed HTML.\n // See http://stackoverflow.com/a/17559716/3059883\n $libxml_previous_state = libxml_use_internal_errors( true );\n\n // Populate $dom with $content, making sure to handle UTF-8, otherwise\n // problems will occur with UTF-8 characters.\n $dom-&gt;loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) );\n\n // Restore previous state of libxml_use_internal_errors() now that we're done.\n // Again, see http://stackoverflow.com/a/17559716/3059883\n libxml_use_internal_errors( $libxml_previous_state );\n\n // Create an instance of DOMXpath.\n $xpath = new \\DOMXpath( $dom );\n\n // Query all links within our content.\n $links = $xpath-&gt;query( '//a' );\n\n // Iterate over the $links.\n foreach ( $links as $link ) {\n if ( $link-&gt;hasAttributes() ) {\n // Get the value of the href attribute\n $link_href = $link-&gt;getAttribute( 'href' );\n\n // Create an onlick attribute and set the value\n $link_onclick = $dom-&gt;createAttribute( 'onclick' );\n $link_onclick-&gt;value = \"window.open( '\" . $link_href . \"', '_blank', 'location=no' );\";\n $link-&gt;appendChild( $link_onclick );\n\n // Remove the href attribute\n $link-&gt;removeAttribute( 'href' );\n }\n }\n\n // Save the updated HTML\n $content = $dom-&gt;saveHTML(); \n\n return $content;\n}\n</code></pre>\n\n<p><strong>Example HTML before processing</strong></p>\n\n<pre><code>&lt;p&gt;&lt;a href=\"http://example.com/\"&gt;click&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis&lt;br&gt;\n&lt;a class=\"test-class test-other-class\" href=\"http://example.com/1/\"&gt;click me too&lt;/a&gt; aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum in fuerat eum est in, quoque sed quod ait est in fuerat.&lt;/p&gt;\n\n&lt;p&gt;&lt;a data-test=\"55\" href=\"http://example.com/2/\"&gt;click me as well&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum&lt;br&gt;\n&lt;a id=\"test-id\" class=\"test-class\" href=\"http://example.com/3/\"&gt;clicky&lt;/a&gt; in fuerat eum est in, quoque sed quod ait est in &lt;a&gt;This link has no href attribute&lt;/a&gt; fuerat.&lt;/p&gt;\n</code></pre>\n\n<p><strong>Example HTML after processing</strong></p>\n\n<pre><code>&lt;p&gt;&lt;a onclick=\"window.open( 'http://example.com/', '_blank', 'location=no' );\"&gt;click&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis&lt;br&gt;\n&lt;a class=\"test-class test-other-class\" onclick=\"window.open( 'http://example.com/1/', '_blank', 'location=no' );\"&gt;click me too&lt;/a&gt; aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum in fuerat eum est in, quoque sed quod ait est in fuerat.&lt;/p&gt;\n\n&lt;p&gt;&lt;a data-test=\"55\" onclick=\"window.open( 'http://example.com/2/', '_blank', 'location=no' );\"&gt;click me as well&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum&lt;br&gt;\n&lt;a id=\"test-id\" class=\"test-class\" onclick=\"window.open( 'http://example.com/3/', '_blank', 'location=no' );\"&gt;clicky&lt;/a&gt; in fuerat eum est in, quoque sed quod ait est in &lt;a&gt;This link has no href attribute&lt;/a&gt; fuerat.&lt;/p&gt;\n</code></pre>\n" } ]
2017/03/07
[ "https://wordpress.stackexchange.com/questions/259110", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114875/" ]
Does anyone know how to programatically change link from: ``` <a href="some_url">click</a> ``` to: ``` <a onclick="window.open('some_url','_blank', 'location=no')">click</a> ``` so that all links created in the wordpress visual editor be opened via inappbrowser in a cordova app. this is the closest that i can get, but still doesn't work, the `'%link%'` variable doesn't change to the actual link url : ``` add_filter('the_content', 'changeToOnclick'); function changeToOnclick($content) { return preg_replace('/<a [^>]*>/', "<a onclick=\"window.open('%link%', '_blank', 'location=no')\">", $content); } ``` any help will be appreciated :)
Parsing HTML with regular expressions is not ideal. A better alternative is to use `DOMDocument` and `DOMXpath`; This code uses `DOMDocument` and `DOMXpath` to parse and modify the HTML without relying on regular expressions. Each link in the content will have the `onclick` attribute added along with the appropriate `window.open()` code using the URL pulled from the value of the `href` attribute. The `href` attribute is then removed from the link. ``` add_filter( 'the_content', 'wpse_cordova_links', 10, 1 ); function wpse_cordova_links( $content ) { // Create an instance of DOMDocument. $dom = new \DOMDocument(); // Suppress errors due to malformed HTML. // See http://stackoverflow.com/a/17559716/3059883 $libxml_previous_state = libxml_use_internal_errors( true ); // Populate $dom with $content, making sure to handle UTF-8, otherwise // problems will occur with UTF-8 characters. $dom->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) ); // Restore previous state of libxml_use_internal_errors() now that we're done. // Again, see http://stackoverflow.com/a/17559716/3059883 libxml_use_internal_errors( $libxml_previous_state ); // Create an instance of DOMXpath. $xpath = new \DOMXpath( $dom ); // Query all links within our content. $links = $xpath->query( '//a' ); // Iterate over the $links. foreach ( $links as $link ) { if ( $link->hasAttributes() ) { // Get the value of the href attribute $link_href = $link->getAttribute( 'href' ); // Create an onlick attribute and set the value $link_onclick = $dom->createAttribute( 'onclick' ); $link_onclick->value = "window.open( '" . $link_href . "', '_blank', 'location=no' );"; $link->appendChild( $link_onclick ); // Remove the href attribute $link->removeAttribute( 'href' ); } } // Save the updated HTML $content = $dom->saveHTML(); return $content; } ``` **Example HTML before processing** ``` <p><a href="http://example.com/">click</a></p> <p>Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis<br> <a class="test-class test-other-class" href="http://example.com/1/">click me too</a> aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum in fuerat eum est in, quoque sed quod ait est in fuerat.</p> <p><a data-test="55" href="http://example.com/2/">click me as well</a></p> <p>Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum<br> <a id="test-id" class="test-class" href="http://example.com/3/">clicky</a> in fuerat eum est in, quoque sed quod ait est in <a>This link has no href attribute</a> fuerat.</p> ``` **Example HTML after processing** ``` <p><a onclick="window.open( 'http://example.com/', '_blank', 'location=no' );">click</a></p> <p>Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis<br> <a class="test-class test-other-class" onclick="window.open( 'http://example.com/1/', '_blank', 'location=no' );">click me too</a> aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum in fuerat eum est in, quoque sed quod ait est in fuerat.</p> <p><a data-test="55" onclick="window.open( 'http://example.com/2/', '_blank', 'location=no' );">click me as well</a></p> <p>Lorem ipsum dolor sit amet, ecclesiam mittam est amet constanter approximavit te. Introivit gubernum defunctam vivum eum ego esse ait mea Christianis aedificatur ergo accipiet duxit ad te. Ascendi in modo invenit ubi diu requievit agi coepit. Apollonii appropinquat tation ulterius quod ait mea Christianis aedificatur ergo accipiet si mihi esse deprecor cum. Equidem deceptum<br> <a id="test-id" class="test-class" onclick="window.open( 'http://example.com/3/', '_blank', 'location=no' );">clicky</a> in fuerat eum est in, quoque sed quod ait est in <a>This link has no href attribute</a> fuerat.</p> ```
259,119
<p>My goal is to add to WooCommerce <code>/my-account</code> page a select input type. The options of the select field will be controlled by ACF repeater in ACF options page, and will be inserted to <code>wp_usermeta</code> table.</p> <p>I palce d this code in functions.php file.</p> <pre><code> while ( have_rows('group_email') ) : the_row(); ?&gt; &lt;option&gt; &lt;?php echo the_sub_field('email_group_id'); ?&gt; &lt;/option&gt; &lt;?php endwhile; </code></pre> <p>For some reason i get no results. If I manually write options I can see them and it works great. I am using ACF version 4.4.11 The repeater is not empty.</p> <p>What can be the problem?</p>
[ { "answer_id": 259122, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 0, "selected": false, "text": "<p>When You're not in <code>The Loop</code> you have to pass page ID as parameter to ACF functions.</p>\n\n<pre><code>while ( have_rows('group_email', $id) ) : the_row(); \n?&gt; \n &lt;option&gt;\n&lt;?php\n echo the_sub_field('email_group_id', $id); \n?&gt;\n &lt;/option&gt;\n&lt;?php\n\nendwhile;\n</code></pre>\n\n<p>See documentation: <a href=\"https://www.advancedcustomfields.com/resources/have_rows/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/have_rows/</a></p>\n" }, { "answer_id": 259124, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 2, "selected": true, "text": "<p>The functions.php file doesn't know where you want that code to be shown on the front end. You need to put the code into a template page (ie the woocommerce account page) or attach it to that page with a woocommerce hook to the template. </p>\n\n<p>You'll need to add it into a function to properly work if you decide it's better to leave it in your functions.php. In either case you may want to surround the while statement in an if statement in case there are no rows. Otherwise you'll get errors.</p>\n\n<p>Lastly since you're echoing the field you should use </p>\n\n<pre><code>echo get_sub_field('email_group_id'); \n</code></pre>\n\n<p>if you actually have more code than what you provided, and it's in the options page i would add the \"option\" argument to the field as well:</p>\n\n<pre><code>while ( have_rows('group_email' , 'option') ) : the_row(); \n?&gt; \n &lt;option&gt;\n&lt;?php\n echo get_sub_field('email_group_id', 'option'); \n?&gt;\n &lt;/option&gt;\n&lt;?php\n\nendwhile;\n</code></pre>\n\n<p>It may be worth trying that first.</p>\n" } ]
2017/03/07
[ "https://wordpress.stackexchange.com/questions/259119", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88244/" ]
My goal is to add to WooCommerce `/my-account` page a select input type. The options of the select field will be controlled by ACF repeater in ACF options page, and will be inserted to `wp_usermeta` table. I palce d this code in functions.php file. ``` while ( have_rows('group_email') ) : the_row(); ?> <option> <?php echo the_sub_field('email_group_id'); ?> </option> <?php endwhile; ``` For some reason i get no results. If I manually write options I can see them and it works great. I am using ACF version 4.4.11 The repeater is not empty. What can be the problem?
The functions.php file doesn't know where you want that code to be shown on the front end. You need to put the code into a template page (ie the woocommerce account page) or attach it to that page with a woocommerce hook to the template. You'll need to add it into a function to properly work if you decide it's better to leave it in your functions.php. In either case you may want to surround the while statement in an if statement in case there are no rows. Otherwise you'll get errors. Lastly since you're echoing the field you should use ``` echo get_sub_field('email_group_id'); ``` if you actually have more code than what you provided, and it's in the options page i would add the "option" argument to the field as well: ``` while ( have_rows('group_email' , 'option') ) : the_row(); ?> <option> <?php echo get_sub_field('email_group_id', 'option'); ?> </option> <?php endwhile; ``` It may be worth trying that first.
259,128
<p>Didn't thought I would have to ask this question. But yes, it's true. It seems you can't have a separate child menu in Wordpress?</p> <p>I'm absolutely not a beginner on Wordpress. Have worked and developed in it for years.</p> <p>However, it might be possible to do a big walkaround to get the separate child/sub menu. But what I would like to get an answer of here is more like; </p> <p><strong>Is it really true there's no simple built-in solution?</strong></p> <p>I have really searched on this site and other sites for answers but struggled to find an answer. It seems to be all about drop downs. I'm soooo tired of drop downs now!</p> <p>Can say I'm running Woocommerce as well. But no, there was no answer in their's documentation either. A lot about "secondary menus". But that's not the same. I need the parent child relationship.</p> <p><h2>EDIT:</h2><strong>Following code example and output example has been added/changed to work as an example of a case scenario:</strong></p> <p>Here is my code:</p> <pre><code> &lt;nav class="parent"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'container_class' =&gt; 'primary-navigation', ) ); ?&gt; &lt;/nav&gt;&lt;!-- #parent --&gt; // Following menu should only be shown if the selected menu item from the above menu has child items. Show them here below. How do I make these two menus to have a connection to each other? &lt;nav class="child"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'container_class' =&gt; 'primary-child-navigation', ) ); ?&gt; &lt;/nav&gt;&lt;!-- #child --&gt; </code></pre> <p><br> <br> <strong>The output</strong> result would be something like this:</p> <hr> <p>Home | <strong>Bags</strong> | Shoes | Hats</p> <p>Backpacks | <strong>Weekend Bags</strong> | Travel Cases | Handhelds <br> <br> <br> <br> <i>And now we are on the Weekend Bag page!</i> <br> <br> <br> <br> <hr> Simple as that!<br> <br></p> <h2>Edit 2:</h2> <p>First problem is that <code>depth</code> attribute doesn't seems to work for <code>wp_nav_menu()</code>. Can't have just top level?</p>
[ { "answer_id": 259140, "author": "Svartbaard", "author_id": 112928, "author_profile": "https://wordpress.stackexchange.com/users/112928", "pm_score": 1, "selected": false, "text": "<p>What exactly do you mean by separate child menu? Could you provide a use case?</p>\n\n<p>The way I understand your question at this point is that you want to inject a separate menu into your main menu without the items being added as child items in the back-end.</p>\n\n<p>I have done something similar a few years back if I understand your question correctly, so it's most likely possible. There is a way to add a menu in combination with the main menu, you would need to reconstruct the menu though.</p>\n\n<p>See the following:</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/Walker</a></p>\n" }, { "answer_id": 259237, "author": "Peter Westerlund", "author_id": 3216, "author_profile": "https://wordpress.stackexchange.com/users/3216", "pm_score": 3, "selected": true, "text": "<p>Found <a href=\"https://christianvarga.com/how-to-get-submenu-items-from-a-wordpress-menu-based-on-parent-or-sibling/\" rel=\"nofollow noreferrer\">the solution</a>. Put this in your <strong>function.php</strong> file:</p>\n\n<pre><code>// add hook\nadd_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );\n// filter_hook function to react on sub_menu flag\nfunction my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {\n if ( isset( $args-&gt;sub_menu ) ) {\n $root_id = 0;\n\n // find the current menu item\n foreach ( $sorted_menu_items as $menu_item ) {\n if ( $menu_item-&gt;current ) {\n // set the root id based on whether the current menu item has a parent or not\n $root_id = ( $menu_item-&gt;menu_item_parent ) ? $menu_item-&gt;menu_item_parent : $menu_item-&gt;ID;\n break;\n }\n }\n\n // find the top level parent\n if ( ! isset( $args-&gt;direct_parent ) ) {\n $prev_root_id = $root_id;\n while ( $prev_root_id != 0 ) {\n foreach ( $sorted_menu_items as $menu_item ) {\n if ( $menu_item-&gt;ID == $prev_root_id ) {\n $prev_root_id = $menu_item-&gt;menu_item_parent;\n // don't set the root_id to 0 if we've reached the top of the menu\n if ( $prev_root_id != 0 ) $root_id = $menu_item-&gt;menu_item_parent;\n break;\n } \n }\n }\n }\n $menu_item_parents = array();\n foreach ( $sorted_menu_items as $key =&gt; $item ) {\n // init menu_item_parents\n if ( $item-&gt;ID == $root_id ) $menu_item_parents[] = $item-&gt;ID;\n if ( in_array( $item-&gt;menu_item_parent, $menu_item_parents ) ) {\n // part of sub-tree: keep!\n $menu_item_parents[] = $item-&gt;ID;\n } else if ( ! ( isset( $args-&gt;show_parent ) &amp;&amp; in_array( $item-&gt;ID, $menu_item_parents ) ) ) {\n // not part of sub-tree: away with it!\n unset( $sorted_menu_items[$key] );\n }\n }\n\n return $sorted_menu_items;\n } else {\n return $sorted_menu_items;\n }\n}\n</code></pre>\n\n<p>Then use it this way:</p>\n\n<pre><code>&lt;?php\nwp_nav_menu(\n array(\n 'theme_location' =&gt; 'primary',\n 'container_class' =&gt; 'primary-navigation',\n 'depth' =&gt; 1\n\n )\n);\nwp_nav_menu(\n array(\n 'theme_location' =&gt; 'primary',\n 'container_class' =&gt; 'primary-child-navigation',\n 'sub_menu' =&gt; true\n\n )\n);\n?&gt;\n</code></pre>\n" }, { "answer_id": 264244, "author": "Freize", "author_id": 116119, "author_profile": "https://wordpress.stackexchange.com/users/116119", "pm_score": 1, "selected": false, "text": "<p>I had a similar problem, and was equally surprised that WP doesn't make this easy. I tried various 'functions scripts' but all had issues. Peter - I thought your script <a href=\"https://wordpress.stackexchange.com/questions/28515/how-to-show-only-parents-subpages-of-current-page-item-in-vertical-menu/28604#28604\">here</a> was what I needed but it seemed to ignore the 'order' option WP offers for every page.</p>\n\n<p>I ended doing most of it with CSS, with just a small piece of PHP in page.php</p>\n\n<pre><code>&lt;?php if(!$post-&gt;post_parent){\n$children = wp_list_pages(\"title_li=&amp;child_of=\".$post-&gt;ID.\"&amp;echo=0\");\n}else{\nif($post-&gt;ancestors)\n{\n$ancestors = end($post-&gt;ancestors);\n$children = wp_list_pages(\"title_li=&amp;child_of=\".$ancestors.\"&amp;echo=0\");\n}\n}\nif ($children) {\n?&gt;\n&lt;ul&gt; &lt;?php echo $children; ?&gt;&lt;/ul&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>This is based on a post made by <a href=\"http://www.focus97.com/blog/web-design-and-development/wordpress-nav-solved-how-to-list-child-pages-only-for-current-parent-page/\" rel=\"nofollow noreferrer\">Mike Lee</a> . Very simple and works perfectly for me.</p>\n" }, { "answer_id": 330977, "author": "Otkelbay Akberdi", "author_id": 162702, "author_profile": "https://wordpress.stackexchange.com/users/162702", "pm_score": 2, "selected": false, "text": "<p>Hello i have two functions for you:</p>\n\n<p>1) Using this function you can get navigation menu children by post id:</p>\n\n<pre><code>function get_the_nav_menu_children_by_post_id($post_id)\n{\n global $wpdb;\n $results = $wpdb-&gt;get_results(\"SELECT post_id FROM `wp_posts` p join wp_postmeta m ON p.ID = m.post_id WHERE post_type = 'nav_menu_item' and meta_key = '_menu_item_object_id' and meta_value = $post_id\");\n\n if (count($results)) {\n $result = $results[0];\n if($result-&gt;post_id){\n $menu_id = $result-&gt;post_id;\n $items = $wpdb-&gt;get_results(\"select * from wp_posts where ID in (SELECT meta_value FROM `wp_posts` p join wp_postmeta m on p.ID = m.post_id WHERE p.ID in (SELECT post_id from wp_postmeta where meta_key = '_menu_item_menu_item_parent' and meta_value = $menu_id) and meta_key = '_menu_item_object_id')\");\n return $items;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>2) Or by menu_id of item in navigation:</p>\n\n<pre><code>function get_the_nav_children($menu_id){\n global $wpdb;\n $items = $wpdb-&gt;get_results(\"select * from wp_posts where ID in (SELECT meta_value FROM `wp_posts` p join wp_postmeta m on p.ID = m.post_id WHERE p.ID in (SELECT post_id from wp_postmeta where meta_key = '_menu_item_menu_item_parent' and meta_value = $menu_id) and meta_key = '_menu_item_object_id')\");\n return $items;\n}\n</code></pre>\n" } ]
2017/03/07
[ "https://wordpress.stackexchange.com/questions/259128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3216/" ]
Didn't thought I would have to ask this question. But yes, it's true. It seems you can't have a separate child menu in Wordpress? I'm absolutely not a beginner on Wordpress. Have worked and developed in it for years. However, it might be possible to do a big walkaround to get the separate child/sub menu. But what I would like to get an answer of here is more like; **Is it really true there's no simple built-in solution?** I have really searched on this site and other sites for answers but struggled to find an answer. It seems to be all about drop downs. I'm soooo tired of drop downs now! Can say I'm running Woocommerce as well. But no, there was no answer in their's documentation either. A lot about "secondary menus". But that's not the same. I need the parent child relationship. EDIT: ----- **Following code example and output example has been added/changed to work as an example of a case scenario:** Here is my code: ``` <nav class="parent"> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container_class' => 'primary-navigation', ) ); ?> </nav><!-- #parent --> // Following menu should only be shown if the selected menu item from the above menu has child items. Show them here below. How do I make these two menus to have a connection to each other? <nav class="child"> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container_class' => 'primary-child-navigation', ) ); ?> </nav><!-- #child --> ``` **The output** result would be something like this: --- Home | **Bags** | Shoes | Hats Backpacks | **Weekend Bags** | Travel Cases | Handhelds *And now we are on the Weekend Bag page!* --- Simple as that! Edit 2: ------- First problem is that `depth` attribute doesn't seems to work for `wp_nav_menu()`. Can't have just top level?
Found [the solution](https://christianvarga.com/how-to-get-submenu-items-from-a-wordpress-menu-based-on-parent-or-sibling/). Put this in your **function.php** file: ``` // add hook add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 ); // filter_hook function to react on sub_menu flag function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) { if ( isset( $args->sub_menu ) ) { $root_id = 0; // find the current menu item foreach ( $sorted_menu_items as $menu_item ) { if ( $menu_item->current ) { // set the root id based on whether the current menu item has a parent or not $root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID; break; } } // find the top level parent if ( ! isset( $args->direct_parent ) ) { $prev_root_id = $root_id; while ( $prev_root_id != 0 ) { foreach ( $sorted_menu_items as $menu_item ) { if ( $menu_item->ID == $prev_root_id ) { $prev_root_id = $menu_item->menu_item_parent; // don't set the root_id to 0 if we've reached the top of the menu if ( $prev_root_id != 0 ) $root_id = $menu_item->menu_item_parent; break; } } } } $menu_item_parents = array(); foreach ( $sorted_menu_items as $key => $item ) { // init menu_item_parents if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID; if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) { // part of sub-tree: keep! $menu_item_parents[] = $item->ID; } else if ( ! ( isset( $args->show_parent ) && in_array( $item->ID, $menu_item_parents ) ) ) { // not part of sub-tree: away with it! unset( $sorted_menu_items[$key] ); } } return $sorted_menu_items; } else { return $sorted_menu_items; } } ``` Then use it this way: ``` <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container_class' => 'primary-navigation', 'depth' => 1 ) ); wp_nav_menu( array( 'theme_location' => 'primary', 'container_class' => 'primary-child-navigation', 'sub_menu' => true ) ); ?> ```
259,176
<p>I'm encountering a 301 problem from my pre-production site which is automatically redirected to my production site. I know the problem comes from WP because I already launched a curl in order to see responses either :</p> <p>1) targeting the <strong>WP pre-production-site</strong> :</p> <pre><code>&gt; GET / HTTP/1.1 &gt; Host: www.pre-production-site.com &gt; User-Agent: curl/7.53.1 &gt; Accept: */* &gt; &lt; HTTP/1.1 301 Moved Permanently &lt; Date: Tue, 07 Mar 2017 11:51:19 GMT &lt; Server: Apache/2.2.22 &lt; Location: http://www.production-site.com/ &lt; X-Content-Type-Options: nosniff &lt; X-XSS-Protection: 1; mode=block &lt; X-Frame-Options: sameorigin &lt; Vary: Accept-Encoding &lt; Content-Length: 0 &lt; Content-Type: text/html; charset=UTF-8 &lt; * Connection #0 to host www.pre-production-site.com left intact </code></pre> <p>2) targeting my own <strong>.php file uploaded on the pre-production-site</strong> :</p> <pre><code>&gt; GET /up.php HTTP/1.1 &gt; Host: www.pre-production-site.com &gt; User-Agent: curl/7.53.1 &gt; Accept: */* &gt; &lt; HTTP/1.1 200 OK &lt; Date: Tue, 07 Mar 2017 11:54:29 GMT &lt; Server: Apache/2.2.22 &lt; X-Content-Type-Options: nosniff &lt; X-XSS-Protection: 1; mode=block &lt; X-Frame-Options: sameorigin &lt; Vary: Accept-Encoding &lt; Content-Length: 2 &lt; Content-Type: text/html; charset=UTF-8 &lt; 42* Connection #0 to host www.pre-production-site.com left intact </code></pre> <p>I don't understand because I've already checked : </p> <ul> <li>.htaccess file : doesn't contain any kind of redirection</li> <li>Apache configuration files : seems OK too</li> <li>source code (if a plugin would sets a Location: header) with a recursive grep : didn't find anything</li> </ul> <p>Where is set this 301 ? I'm not sure if I left all informations that you need so feel free to ask me !</p> <p>Thank you very much for your help !</p>
[ { "answer_id": 259266, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Did you check the 'options' table in your WP databasse for the two instances of the domain name (something like '<a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> ' ). </p>\n\n<p>Not clear if your pre-production site is hosted on a local machine, or networked server. Might be some firewall redirection rules causing issues.</p>\n" }, { "answer_id": 333948, "author": "Kryten", "author_id": 164792, "author_profile": "https://wordpress.stackexchange.com/users/164792", "pm_score": 0, "selected": false, "text": "<p>Just a little clarification of @RickHellewell's answer:</p>\n\n<p>To prevent Wordpress from redirecting to my live site when I copied the database to my local machine for development work, I updated two rows in the database with the following query:</p>\n\n<pre><code>UPDATE wp_options SET option_value='http://localhost' WHERE option_value='http://mylivesite.com';\n</code></pre>\n\n<p>This allowed me to load (and work on) my site locally by visiting <a href=\"http://localhost\" rel=\"nofollow noreferrer\">http://localhost</a> and <a href=\"http://localhost/wp-admin\" rel=\"nofollow noreferrer\">http://localhost/wp-admin</a></p>\n" } ]
2017/03/07
[ "https://wordpress.stackexchange.com/questions/259176", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114899/" ]
I'm encountering a 301 problem from my pre-production site which is automatically redirected to my production site. I know the problem comes from WP because I already launched a curl in order to see responses either : 1) targeting the **WP pre-production-site** : ``` > GET / HTTP/1.1 > Host: www.pre-production-site.com > User-Agent: curl/7.53.1 > Accept: */* > < HTTP/1.1 301 Moved Permanently < Date: Tue, 07 Mar 2017 11:51:19 GMT < Server: Apache/2.2.22 < Location: http://www.production-site.com/ < X-Content-Type-Options: nosniff < X-XSS-Protection: 1; mode=block < X-Frame-Options: sameorigin < Vary: Accept-Encoding < Content-Length: 0 < Content-Type: text/html; charset=UTF-8 < * Connection #0 to host www.pre-production-site.com left intact ``` 2) targeting my own **.php file uploaded on the pre-production-site** : ``` > GET /up.php HTTP/1.1 > Host: www.pre-production-site.com > User-Agent: curl/7.53.1 > Accept: */* > < HTTP/1.1 200 OK < Date: Tue, 07 Mar 2017 11:54:29 GMT < Server: Apache/2.2.22 < X-Content-Type-Options: nosniff < X-XSS-Protection: 1; mode=block < X-Frame-Options: sameorigin < Vary: Accept-Encoding < Content-Length: 2 < Content-Type: text/html; charset=UTF-8 < 42* Connection #0 to host www.pre-production-site.com left intact ``` I don't understand because I've already checked : * .htaccess file : doesn't contain any kind of redirection * Apache configuration files : seems OK too * source code (if a plugin would sets a Location: header) with a recursive grep : didn't find anything Where is set this 301 ? I'm not sure if I left all informations that you need so feel free to ask me ! Thank you very much for your help !
Did you check the 'options' table in your WP databasse for the two instances of the domain name (something like '<http://www.example.com> ' ). Not clear if your pre-production site is hosted on a local machine, or networked server. Might be some firewall redirection rules causing issues.
259,195
<p>I have some very basic data that I am posting to a proprietary lead capturing system. Whenever I submit my form data to their system the body of the request is an error 500 page.</p> <p>I am trying to debug the problem with their developer, it clearly doesn't like something in my query string, and he would like to be able to test it on his end.</p> <p>However, I've scoured through Google results and the WordPress codex and I cannot find a way to pull the query string that is generated from something like:</p> <blockquote> <p>$result = wp_remote_get( 'thirdparty.com', array( 'body' => array( 'foo' => 'bar' ) ) );</p> </blockquote> <p>I would expect the query string to look something like:</p> <pre><code>thirdparty.com?foo=bar </code></pre> <p>Anyone have any tip on how to get this generated URL/query string?</p>
[ { "answer_id": 259201, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 0, "selected": false, "text": "<p>You can have a look into the classes inside <a href=\"https://core.svn.wordpress.org/tags/4.7.3/wp-includes/class-http.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-http</code></a> that handle the actual request. There are various hooks like <code>http_api_curl</code> you could hook into to see what is actually requested.</p>\n" }, { "answer_id": 333045, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 0, "selected": false, "text": "<p>This is a task for <strong>Xdebug</strong>. I'd recommend to use it together with PHPStorm.</p>\n\n<p>Then you'll need to set a breakpoint exactly at the moment you build the query or when you post the request. Then you can inspect what exactly is going on.</p>\n\n<p>Following is a sample chain I used to post something successfully, which results in a query that simply looks like the following which then get appended to the <code>$url</code> below. I found it important to format the query with <code>PHP_QUERY_RFC3986</code> using PHP's <a href=\"https://www.php.net/manual/en/function.http-build-query.php\" rel=\"nofollow noreferrer\"><code>http_build_query()</code></a> so it gets encoded properly.</p>\n\n<p>The query:</p>\n\n<pre><code>foo=foovalue&amp;bar=barvalue\n</code></pre>\n\n<p>The complete sample:</p>\n\n<pre><code>// Build the URL query to be append to the POST request URL.\n$data = [\n 'foo' =&gt; $foo,\n 'bar' =&gt; $bar,\n];\n\n$query = http_build_query($data, NULL, '&amp;', PHP_QUERY_RFC3986);\n\n// The POST request URL.\n$url = 'https://example.com/index.php/fooBar/save2?' . $query;\n\n$args = [\n 'headers' =&gt; ['Content-Type' =&gt; 'application/x-www-form-urlencoded'],\n 'method' =&gt; 'POST',\n];\n\n// Post the request.\n$response = wp_remote_request($url, $args);\n\n//Check for success\nif (!is_wp_error($response) &amp;&amp; ($response['response']['code'] === 200 || $response['response']['code'] === 201)) {\n return $response['body'];\n}\n</code></pre>\n" }, { "answer_id": 356579, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>While the other answers are pretty good in providing an answer to your question (how to get the generated url), i will answer what i guess you really want to know (how do i get it to call thirdparty.com?foo=bar with wp_remote_get)</p>\n\n<p>The Answer is: the $args array you use to transmit the url parameters won't work like this. If you have to transmit a POST request with wp_remote_post, you would use the body argument like your example. However, to wp_remote_get thirdparty.com?foo=bar, you simply do </p>\n\n<pre><code>wp_remote_get('http://thirdparty.com?foo=bar');\n</code></pre>\n\n<p>if you want to get fancy and use an array, you can also do this:</p>\n\n<pre><code>$url = \"http://thirdparty.com\";\n$data = array('foo' =&gt; 'bar');\n$query_url = $url.'?'.http_build_query($data);\n$response = wp_remote_get($query_url);\n</code></pre>\n\n<p>Happy Coding!</p>\n" } ]
2017/03/07
[ "https://wordpress.stackexchange.com/questions/259195", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14064/" ]
I have some very basic data that I am posting to a proprietary lead capturing system. Whenever I submit my form data to their system the body of the request is an error 500 page. I am trying to debug the problem with their developer, it clearly doesn't like something in my query string, and he would like to be able to test it on his end. However, I've scoured through Google results and the WordPress codex and I cannot find a way to pull the query string that is generated from something like: > > $result = wp\_remote\_get( 'thirdparty.com', array( 'body' => array( > 'foo' => 'bar' ) ) ); > > > I would expect the query string to look something like: ``` thirdparty.com?foo=bar ``` Anyone have any tip on how to get this generated URL/query string?
While the other answers are pretty good in providing an answer to your question (how to get the generated url), i will answer what i guess you really want to know (how do i get it to call thirdparty.com?foo=bar with wp\_remote\_get) The Answer is: the $args array you use to transmit the url parameters won't work like this. If you have to transmit a POST request with wp\_remote\_post, you would use the body argument like your example. However, to wp\_remote\_get thirdparty.com?foo=bar, you simply do ``` wp_remote_get('http://thirdparty.com?foo=bar'); ``` if you want to get fancy and use an array, you can also do this: ``` $url = "http://thirdparty.com"; $data = array('foo' => 'bar'); $query_url = $url.'?'.http_build_query($data); $response = wp_remote_get($query_url); ``` Happy Coding!
259,250
<p>The code below is meant to simply loop through posts, give the opportunity to add html formatting to them, then return them to the shortcode position. I have conditional logic which defines formatting based on the passed in "category"(term). I need to output it twice on the same page, but I only see code that I've added outside of the loop.</p> <pre><code>add_shortcode('my_shortcode','generate_my_shortcode_content'); function generate_my_shortcode_content($atts){ $a = shortcode_atts( array( 'post-count' =&gt; 3, 'category' =&gt; 'default-cat' ), $atts ); $post_count = (int)$a['post-count']; $post_category = explode(',', $a['category']); $args = array( 'post_type' =&gt; 'my-type', 'posts_per_page' =&gt; $post_count, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'my-taxonomy', 'field' =&gt; 'slug', 'terms' =&gt; $post_category ) ) ); $test = "&lt;h1&gt;"; $query = new WP_Query( $args ); if($query-&gt;have_posts()):while($query-&gt;have_posts()):$query-&gt;the_post(); $post_id = get_the_ID(); $post_title = get_the_title($post_id); $post_content = get_the_content($post_id); $posts .= $post_id . $post_title . $post_content; $test .= "this is a test"; endwhile;wp_reset_postdata();endif; $test .= "&lt;/h1&gt;"; return $posts . $test; } </code></pre> <p>This function will return <code>{Post ID}{Post Title}{Post Content}&lt;h1&gt;this is a test&lt;/h1&gt;</code> on the first execution, but will only return <code>&lt;h1&gt;&lt;/h1&gt;</code> on the second. Why is this?</p>
[ { "answer_id": 259201, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 0, "selected": false, "text": "<p>You can have a look into the classes inside <a href=\"https://core.svn.wordpress.org/tags/4.7.3/wp-includes/class-http.php\" rel=\"nofollow noreferrer\"><code>wp-includes/class-http</code></a> that handle the actual request. There are various hooks like <code>http_api_curl</code> you could hook into to see what is actually requested.</p>\n" }, { "answer_id": 333045, "author": "leymannx", "author_id": 30597, "author_profile": "https://wordpress.stackexchange.com/users/30597", "pm_score": 0, "selected": false, "text": "<p>This is a task for <strong>Xdebug</strong>. I'd recommend to use it together with PHPStorm.</p>\n\n<p>Then you'll need to set a breakpoint exactly at the moment you build the query or when you post the request. Then you can inspect what exactly is going on.</p>\n\n<p>Following is a sample chain I used to post something successfully, which results in a query that simply looks like the following which then get appended to the <code>$url</code> below. I found it important to format the query with <code>PHP_QUERY_RFC3986</code> using PHP's <a href=\"https://www.php.net/manual/en/function.http-build-query.php\" rel=\"nofollow noreferrer\"><code>http_build_query()</code></a> so it gets encoded properly.</p>\n\n<p>The query:</p>\n\n<pre><code>foo=foovalue&amp;bar=barvalue\n</code></pre>\n\n<p>The complete sample:</p>\n\n<pre><code>// Build the URL query to be append to the POST request URL.\n$data = [\n 'foo' =&gt; $foo,\n 'bar' =&gt; $bar,\n];\n\n$query = http_build_query($data, NULL, '&amp;', PHP_QUERY_RFC3986);\n\n// The POST request URL.\n$url = 'https://example.com/index.php/fooBar/save2?' . $query;\n\n$args = [\n 'headers' =&gt; ['Content-Type' =&gt; 'application/x-www-form-urlencoded'],\n 'method' =&gt; 'POST',\n];\n\n// Post the request.\n$response = wp_remote_request($url, $args);\n\n//Check for success\nif (!is_wp_error($response) &amp;&amp; ($response['response']['code'] === 200 || $response['response']['code'] === 201)) {\n return $response['body'];\n}\n</code></pre>\n" }, { "answer_id": 356579, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 2, "selected": false, "text": "<p>While the other answers are pretty good in providing an answer to your question (how to get the generated url), i will answer what i guess you really want to know (how do i get it to call thirdparty.com?foo=bar with wp_remote_get)</p>\n\n<p>The Answer is: the $args array you use to transmit the url parameters won't work like this. If you have to transmit a POST request with wp_remote_post, you would use the body argument like your example. However, to wp_remote_get thirdparty.com?foo=bar, you simply do </p>\n\n<pre><code>wp_remote_get('http://thirdparty.com?foo=bar');\n</code></pre>\n\n<p>if you want to get fancy and use an array, you can also do this:</p>\n\n<pre><code>$url = \"http://thirdparty.com\";\n$data = array('foo' =&gt; 'bar');\n$query_url = $url.'?'.http_build_query($data);\n$response = wp_remote_get($query_url);\n</code></pre>\n\n<p>Happy Coding!</p>\n" } ]
2017/03/07
[ "https://wordpress.stackexchange.com/questions/259250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64943/" ]
The code below is meant to simply loop through posts, give the opportunity to add html formatting to them, then return them to the shortcode position. I have conditional logic which defines formatting based on the passed in "category"(term). I need to output it twice on the same page, but I only see code that I've added outside of the loop. ``` add_shortcode('my_shortcode','generate_my_shortcode_content'); function generate_my_shortcode_content($atts){ $a = shortcode_atts( array( 'post-count' => 3, 'category' => 'default-cat' ), $atts ); $post_count = (int)$a['post-count']; $post_category = explode(',', $a['category']); $args = array( 'post_type' => 'my-type', 'posts_per_page' => $post_count, 'tax_query' => array( array( 'taxonomy' => 'my-taxonomy', 'field' => 'slug', 'terms' => $post_category ) ) ); $test = "<h1>"; $query = new WP_Query( $args ); if($query->have_posts()):while($query->have_posts()):$query->the_post(); $post_id = get_the_ID(); $post_title = get_the_title($post_id); $post_content = get_the_content($post_id); $posts .= $post_id . $post_title . $post_content; $test .= "this is a test"; endwhile;wp_reset_postdata();endif; $test .= "</h1>"; return $posts . $test; } ``` This function will return `{Post ID}{Post Title}{Post Content}<h1>this is a test</h1>` on the first execution, but will only return `<h1></h1>` on the second. Why is this?
While the other answers are pretty good in providing an answer to your question (how to get the generated url), i will answer what i guess you really want to know (how do i get it to call thirdparty.com?foo=bar with wp\_remote\_get) The Answer is: the $args array you use to transmit the url parameters won't work like this. If you have to transmit a POST request with wp\_remote\_post, you would use the body argument like your example. However, to wp\_remote\_get thirdparty.com?foo=bar, you simply do ``` wp_remote_get('http://thirdparty.com?foo=bar'); ``` if you want to get fancy and use an array, you can also do this: ``` $url = "http://thirdparty.com"; $data = array('foo' => 'bar'); $query_url = $url.'?'.http_build_query($data); $response = wp_remote_get($query_url); ``` Happy Coding!
259,255
<p>I am using Advanced Custom Fields and trying to build a navigation menu where the current item has an extra class on it to let them know where they are.</p> <p><strong>The entire structure in question. It's using ACF repeater fields:</strong></p> <pre><code>&lt;?php if(get_field('main_nav', 53)): ?&gt; &lt;?php while(has_sub_field('main_nav', 53)): ?&gt; &lt;li&gt;&lt;a &lt;?php $link1 = the_permalink(); $link2 = the_sub_field('link_url'); if ( $link1 == $link2 ) {?&gt; class="s4-secondary-nav-current" &lt;?php } ?&gt; href="&lt;?php the_sub_field('link_url'); ?&gt;"&gt;&lt;?php the_sub_field('link_text'); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; </code></pre> <p><strong>Specific conditional:</strong></p> <pre><code>&lt;?php $link1 = the_permalink(); $link2 = the_sub_field('link_url'); if ( $link1 == $link2 ) { echo 'class="s4-secondary-nav-current"'; } else {} ?&gt; </code></pre> <p>What seems to be happening is that $link1 and $link2 just get printed in the HTML.</p> <p><strong>Was also trying to do something like this that gets same results as above:</strong></p> <pre><code>&lt;?php if ( the_permalink() == the_sub_field('link_url') ) {?&gt; class="s4-secondary-nav-current" &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 259257, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>the_permalink</code> doesn't do what you think it does.</p>\n\n<p>For example, this:</p>\n\n<pre><code>if ( the_permalink() == 'test' ) {\n</code></pre>\n\n<p>Is the same as:</p>\n\n<pre><code>echo get_the_permalink();\nif ( '' == 'test' ) {\n</code></pre>\n\n<p><code>the_permalink</code> doesn't return a value, and outputs it directly. Use <code>get_the_permalink</code> instead, and check what functions do before using them.</p>\n" }, { "answer_id": 259259, "author": "Bryan Hoffman", "author_id": 21168, "author_profile": "https://wordpress.stackexchange.com/users/21168", "pm_score": 2, "selected": false, "text": "<p>Both <code>the_permalink()</code> and <code>the_sub_field()</code> are functions that do more than output a string or URL. </p>\n\n<p>Try using<code>get_permalink()</code> and <code>get_sub_field</code> instead:</p>\n\n<pre><code>$link1 = get_permalink();\n$link2 = get_sub_field('link_url');\n</code></pre>\n" } ]
2017/03/07
[ "https://wordpress.stackexchange.com/questions/259255", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114953/" ]
I am using Advanced Custom Fields and trying to build a navigation menu where the current item has an extra class on it to let them know where they are. **The entire structure in question. It's using ACF repeater fields:** ``` <?php if(get_field('main_nav', 53)): ?> <?php while(has_sub_field('main_nav', 53)): ?> <li><a <?php $link1 = the_permalink(); $link2 = the_sub_field('link_url'); if ( $link1 == $link2 ) {?> class="s4-secondary-nav-current" <?php } ?> href="<?php the_sub_field('link_url'); ?>"><?php the_sub_field('link_text'); ?></a></li> <?php endwhile; ?> <?php endif; ?> ``` **Specific conditional:** ``` <?php $link1 = the_permalink(); $link2 = the_sub_field('link_url'); if ( $link1 == $link2 ) { echo 'class="s4-secondary-nav-current"'; } else {} ?> ``` What seems to be happening is that $link1 and $link2 just get printed in the HTML. **Was also trying to do something like this that gets same results as above:** ``` <?php if ( the_permalink() == the_sub_field('link_url') ) {?> class="s4-secondary-nav-current" <?php } ?> ```
Both `the_permalink()` and `the_sub_field()` are functions that do more than output a string or URL. Try using`get_permalink()` and `get_sub_field` instead: ``` $link1 = get_permalink(); $link2 = get_sub_field('link_url'); ```
259,334
<p>Out setup is multiple Front Ends (replicated) and 2 Backend MYSQL servers (Master-Master replication).</p> <p>We're looking to achieve HA automatic failover for wordpress. We've got the front ends covered through replication and a load balancer. </p> <p>Any ideas on how to achieve <strong>AUTOMATIC</strong> MySQL failover?</p> <p>Thanks in advance.</p>
[ { "answer_id": 259257, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p><code>the_permalink</code> doesn't do what you think it does.</p>\n\n<p>For example, this:</p>\n\n<pre><code>if ( the_permalink() == 'test' ) {\n</code></pre>\n\n<p>Is the same as:</p>\n\n<pre><code>echo get_the_permalink();\nif ( '' == 'test' ) {\n</code></pre>\n\n<p><code>the_permalink</code> doesn't return a value, and outputs it directly. Use <code>get_the_permalink</code> instead, and check what functions do before using them.</p>\n" }, { "answer_id": 259259, "author": "Bryan Hoffman", "author_id": 21168, "author_profile": "https://wordpress.stackexchange.com/users/21168", "pm_score": 2, "selected": false, "text": "<p>Both <code>the_permalink()</code> and <code>the_sub_field()</code> are functions that do more than output a string or URL. </p>\n\n<p>Try using<code>get_permalink()</code> and <code>get_sub_field</code> instead:</p>\n\n<pre><code>$link1 = get_permalink();\n$link2 = get_sub_field('link_url');\n</code></pre>\n" } ]
2017/03/08
[ "https://wordpress.stackexchange.com/questions/259334", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78065/" ]
Out setup is multiple Front Ends (replicated) and 2 Backend MYSQL servers (Master-Master replication). We're looking to achieve HA automatic failover for wordpress. We've got the front ends covered through replication and a load balancer. Any ideas on how to achieve **AUTOMATIC** MySQL failover? Thanks in advance.
Both `the_permalink()` and `the_sub_field()` are functions that do more than output a string or URL. Try using`get_permalink()` and `get_sub_field` instead: ``` $link1 = get_permalink(); $link2 = get_sub_field('link_url'); ```
259,352
<p>I am trying to create a custom meta box that lets you add rows dynamically. Following code snippet works fine and and saves data in my edit page section. However, I can't get it to display the data on the actual page:</p> <pre><code> add_action( 'add_meta_boxes', 'dynamic_add_custom_box' ); /* Do something with the data entered */ add_action( 'save_post', 'dynamic_save_postdata' ); /* Adds a box to the main column on the Post and Page edit screens */ function dynamic_add_custom_box() { add_meta_box( 'dynamic_sectionid', __( 'My Tracks', 'myplugin_textdomain' ), 'dynamic_inner_custom_box', 'page'); } /* Prints the box content */ function dynamic_inner_custom_box() { global $post; // Use nonce for verification wp_nonce_field( plugin_basename( __FILE__ ), 'dynamicMeta_noncename' ); ?&gt; &lt;div id="meta_inner"&gt; &lt;?php //get the saved meta as an arry $songs = get_post_meta($post-&gt;ID,'songs',true); $c = 0; if ( count( $songs ) &gt; 0 ) { foreach( $songs as $track ) { if ( isset( $track['title'] ) || isset( $track['track'] ) ) { printf( '&lt;p&gt;Song Title &lt;input type="text" name="songs[%1$s][title]" value="%2$s" /&gt; -- Track number : &lt;input type="text" name="songs[%1$s][track]" value="%3$s" /&gt;&lt;span class="remove"&gt;%4$s&lt;/span&gt;&lt;/p&gt;', $c, $track['title'], $track['track'], __( 'Remove Track' ) ); $c = $c +1; } } } ?&gt; &lt;span id="here"&gt;&lt;/span&gt; &lt;span class="add"&gt;&lt;?php _e('Add Tracks'); ?&gt;&lt;/span&gt; &lt;script&gt; var $ =jQuery.noConflict(); $(document).ready(function() { var count = &lt;?php echo $c; ?&gt;; $(".add").click(function() { count = count + 1; $('#here').append('&lt;p&gt; Song Title &lt;input type="text" name="songs['+count+'][title]" value="" /&gt; -- Track number : &lt;input type="text" name="songs['+count+'][track]" value="" /&gt;&lt;span class="remove"&gt;Remove Track&lt;/span&gt;&lt;/p&gt;' ); return false; }); $(".remove").live('click', function() { $(this).parent().remove(); }); }); &lt;/script&gt; &lt;/div&gt;&lt;?php } /* When the post is saved, saves our custom data */ function dynamic_save_postdata( $post_id ) { // verify if this is an auto save routine. // If it is our form has not been submitted, so we dont want to do anything if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return; // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times if ( !isset( $_POST['dynamicMeta_noncename'] ) ) return; if ( !wp_verify_nonce( $_POST['dynamicMeta_noncename'], plugin_basename( __FILE__ ) ) ) return; // OK, we're authenticated: we need to find and save the data $songs = $_POST['songs']; update_post_meta($post_id,'songs',$songs); } </code></pre> <p>As you can see, 'page' is referring to page where I want to post to. Now when I loop for the results on the page template nothing shows up.</p> <pre><code> &lt;?php $args = array( 'post_type' =&gt; 'page', ); $repeat_loop = new WP_Query( $args ); if ( $repeat_loop-&gt;have_posts() ) : while ( $repeat_loop-&gt;have_posts() ) : $repeat_loop-&gt;the_post(); $meta = get_post_meta( $post-&gt;ID, 'songs', true ); ?&gt; &lt;?php echo $meta['title']; ?&gt;&lt;?php echo $meta['track']; ?&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; </code></pre> <p>I do get results when I use the 'var_dump($posts);'. I just can't get it to display in the page. </p>
[ { "answer_id": 259356, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 2, "selected": true, "text": "<p>Try changing <code>$meta['title']</code> to <code>$meta['title'][0]</code> &amp; the same thing for <code>$meta['track']</code> . change it to <code>$meta['track'][0]</code></p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>I looked at the code more deeply and you basically need a foreach loop.\nHere's the final code should look like:</p>\n\n<pre><code>&lt;?php\n$args = array(\n 'post_type' =&gt; 'page'\n); \n$repeat_loop = new WP_Query( $args ); if ( $repeat_loop-&gt;have_posts() ) : while ( $repeat_loop-&gt;have_posts() ) : $repeat_loop-&gt;the_post();\n$meta = get_post_meta( $post-&gt;ID, 'songs', true ); ?&gt; \n\n&lt;?php\nforeach ($meta as $key =&gt; $value) {\n echo $value['title']; ?&gt;&lt;?php echo $value['track'];\n}\n?&gt;\n&lt;?php endwhile; \n endif;\n wp_reset_postdata(); \n?&gt;\n</code></pre>\n\n<p>Thanks</p>\n" }, { "answer_id": 259362, "author": "user3645783", "author_id": 115021, "author_profile": "https://wordpress.stackexchange.com/users/115021", "pm_score": 0, "selected": false, "text": "<p>Ok, I solved it thanks to the hint from Abdul! I need to loop through my array so I implemented a simple for loop: </p>\n\n<pre><code> &lt;?php for( $i= 0 ; $i &lt;= 10 ; $i++ ) echo '&lt;p&gt;' .$meta[$i]['title']. '&lt;/p&gt;';?&gt;\n</code></pre>\n\n<p>Thanks a lot for the help! </p>\n" } ]
2017/03/08
[ "https://wordpress.stackexchange.com/questions/259352", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115021/" ]
I am trying to create a custom meta box that lets you add rows dynamically. Following code snippet works fine and and saves data in my edit page section. However, I can't get it to display the data on the actual page: ``` add_action( 'add_meta_boxes', 'dynamic_add_custom_box' ); /* Do something with the data entered */ add_action( 'save_post', 'dynamic_save_postdata' ); /* Adds a box to the main column on the Post and Page edit screens */ function dynamic_add_custom_box() { add_meta_box( 'dynamic_sectionid', __( 'My Tracks', 'myplugin_textdomain' ), 'dynamic_inner_custom_box', 'page'); } /* Prints the box content */ function dynamic_inner_custom_box() { global $post; // Use nonce for verification wp_nonce_field( plugin_basename( __FILE__ ), 'dynamicMeta_noncename' ); ?> <div id="meta_inner"> <?php //get the saved meta as an arry $songs = get_post_meta($post->ID,'songs',true); $c = 0; if ( count( $songs ) > 0 ) { foreach( $songs as $track ) { if ( isset( $track['title'] ) || isset( $track['track'] ) ) { printf( '<p>Song Title <input type="text" name="songs[%1$s][title]" value="%2$s" /> -- Track number : <input type="text" name="songs[%1$s][track]" value="%3$s" /><span class="remove">%4$s</span></p>', $c, $track['title'], $track['track'], __( 'Remove Track' ) ); $c = $c +1; } } } ?> <span id="here"></span> <span class="add"><?php _e('Add Tracks'); ?></span> <script> var $ =jQuery.noConflict(); $(document).ready(function() { var count = <?php echo $c; ?>; $(".add").click(function() { count = count + 1; $('#here').append('<p> Song Title <input type="text" name="songs['+count+'][title]" value="" /> -- Track number : <input type="text" name="songs['+count+'][track]" value="" /><span class="remove">Remove Track</span></p>' ); return false; }); $(".remove").live('click', function() { $(this).parent().remove(); }); }); </script> </div><?php } /* When the post is saved, saves our custom data */ function dynamic_save_postdata( $post_id ) { // verify if this is an auto save routine. // If it is our form has not been submitted, so we dont want to do anything if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times if ( !isset( $_POST['dynamicMeta_noncename'] ) ) return; if ( !wp_verify_nonce( $_POST['dynamicMeta_noncename'], plugin_basename( __FILE__ ) ) ) return; // OK, we're authenticated: we need to find and save the data $songs = $_POST['songs']; update_post_meta($post_id,'songs',$songs); } ``` As you can see, 'page' is referring to page where I want to post to. Now when I loop for the results on the page template nothing shows up. ``` <?php $args = array( 'post_type' => 'page', ); $repeat_loop = new WP_Query( $args ); if ( $repeat_loop->have_posts() ) : while ( $repeat_loop->have_posts() ) : $repeat_loop->the_post(); $meta = get_post_meta( $post->ID, 'songs', true ); ?> <?php echo $meta['title']; ?><?php echo $meta['track']; ?> <?php endwhile; endif; wp_reset_postdata(); ?> ``` I do get results when I use the 'var\_dump($posts);'. I just can't get it to display in the page.
Try changing `$meta['title']` to `$meta['title'][0]` & the same thing for `$meta['track']` . change it to `$meta['track'][0]` **UPDATE:** I looked at the code more deeply and you basically need a foreach loop. Here's the final code should look like: ``` <?php $args = array( 'post_type' => 'page' ); $repeat_loop = new WP_Query( $args ); if ( $repeat_loop->have_posts() ) : while ( $repeat_loop->have_posts() ) : $repeat_loop->the_post(); $meta = get_post_meta( $post->ID, 'songs', true ); ?> <?php foreach ($meta as $key => $value) { echo $value['title']; ?><?php echo $value['track']; } ?> <?php endwhile; endif; wp_reset_postdata(); ?> ``` Thanks
259,396
<p>I'm building my child theme, but including materialize css that I want to use, breaks the entire site when enqueued in <strong>functions.php</strong>. How do I change that?</p> <pre><code>function bla_enqueue_child_theme_styles() { wp_enqueue_style('cookie-font', 'http://fonts.googleapis.com/css?family=Cookie'); //wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css'); wp_enqueue_style('materialize-css', 'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css', 0); wp_enqueue_style('cake-child-style', get_stylesheet_directory_uri().'/style.css', '', 1, 'all'); wp_enqueue_script('new-jquery', 'https://code.jquery.com/jquery-3.1.1.min.js'); wp_enqueue_script('materialize-js', 'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js'); //wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js'); wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/custom.js'); } add_action( 'wp_enqueue_scripts', 'bla_enqueue_child_theme_styles', -20); </code></pre>
[ { "answer_id": 259406, "author": "tillinberlin", "author_id": 26059, "author_profile": "https://wordpress.stackexchange.com/users/26059", "pm_score": 1, "selected": false, "text": "<p>You could first <strong>dequeue</strong> the <em>parent stylesheet</em>, then <strong>enqueue</strong> the <em>child stylesheet</em> and finally <strong>enqueue</strong> the <em>parent stylesheet</em>. </p>\n\n<p><strong>Dequeueing</strong> the <em>parent stylesheet</em> should work like this: </p>\n\n<pre><code>function PREFIX_remove_scripts() {\n\n wp_dequeue_style( 'screen' );\n wp_deregister_style( 'screen' );\n\n wp_dequeue_script( 'site' ); // optional \n wp_deregister_script( 'site' ); // optional\n\n // Now register your styles and scripts here \n\n}\n\nadd_action( 'wp_enqueue_scripts', 'PREFIX_remove_scripts', 20 );\n</code></pre>\n\n<p>…as described in the answer to this question: \"<a href=\"https://wordpress.stackexchange.com/questions/65523/how-do-i-dequeue-a-parent-themes-css-file\">How do I dequeue a parent theme's CSS file?</a>\"</p>\n" }, { "answer_id": 259407, "author": "Willington Vega", "author_id": 52, "author_profile": "https://wordpress.stackexchange.com/users/52", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>How do I load it before the parent theme?</p>\n</blockquote>\n\n<p>I think you are doing it right. If the parent theme is attaching the function responsible for enqueueing its styles to the <code>wp_enqueue_scripts</code> hook, then your <code>bla_enqueue_child_theme_styles()</code> function must be being executed first (because you passed <code>-20</code> as priority) and your styles should be being included first in the page's source code.</p>\n\n<p>The fact that Materialize's CSS rules are overriding the parent theme's may not be related to the order in which the stylesheets are being included, but to the specificity of the selectors being used in those stylesheets.</p>\n\n<p>Cake is likely to be using some kind of CSS framework as well, either one developed by a third party or a custom one. In that case, is very likely that both Cake and Materialize are trying to solve the same problems, but using different methods, creating conflicts in the process.</p>\n" } ]
2017/03/08
[ "https://wordpress.stackexchange.com/questions/259396", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99302/" ]
I'm building my child theme, but including materialize css that I want to use, breaks the entire site when enqueued in **functions.php**. How do I change that? ``` function bla_enqueue_child_theme_styles() { wp_enqueue_style('cookie-font', 'http://fonts.googleapis.com/css?family=Cookie'); //wp_enqueue_style('datatables-css', 'https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css'); wp_enqueue_style('materialize-css', 'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css', 0); wp_enqueue_style('cake-child-style', get_stylesheet_directory_uri().'/style.css', '', 1, 'all'); wp_enqueue_script('new-jquery', 'https://code.jquery.com/jquery-3.1.1.min.js'); wp_enqueue_script('materialize-js', 'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js'); //wp_enqueue_script('datatables-js', 'https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js'); wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/custom.js'); } add_action( 'wp_enqueue_scripts', 'bla_enqueue_child_theme_styles', -20); ```
> > How do I load it before the parent theme? > > > I think you are doing it right. If the parent theme is attaching the function responsible for enqueueing its styles to the `wp_enqueue_scripts` hook, then your `bla_enqueue_child_theme_styles()` function must be being executed first (because you passed `-20` as priority) and your styles should be being included first in the page's source code. The fact that Materialize's CSS rules are overriding the parent theme's may not be related to the order in which the stylesheets are being included, but to the specificity of the selectors being used in those stylesheets. Cake is likely to be using some kind of CSS framework as well, either one developed by a third party or a custom one. In that case, is very likely that both Cake and Materialize are trying to solve the same problems, but using different methods, creating conflicts in the process.
259,410
<p>Wordpress renders a meta description tag with the content of the blog post as the value for the description.</p> <p>I already generated in the <code>header.php</code> what I want the description to be, no matter what. However, the old one is still in there. I checked <code>single-post.php</code> and <code>header.php</code> and there is nothing rendering the meta description. So it HAS to be the <code>wp_head()</code> function.</p> <p>Is there anyway I can put something in my <code>functions.php</code> or something to ensure that on certain pages the meta description is removed from <code>wp_head()</code>?</p>
[ { "answer_id": 259467, "author": "hcheung", "author_id": 111577, "author_profile": "https://wordpress.stackexchange.com/users/111577", "pm_score": 0, "selected": false, "text": "<p>If you want to remote <code>&lt;meta name=\"description\" content=\"\" /&gt;</code> in html head, Add </p>\n\n<pre><code>remove_action('wp_head', 'description');\n</code></pre>\n\n<p>into your function.php. </p>\n" }, { "answer_id": 259582, "author": "hcheung", "author_id": 111577, "author_profile": "https://wordpress.stackexchange.com/users/111577", "pm_score": 0, "selected": false, "text": "<p>For change the content of the meta description:</p>\n\n<pre><code>&lt;?php \n$description = '';\nif( is_single() or is_page() ){\n global $post;\n $description = get_post_meta( $post-&gt;ID, $this-&gt;meta_key, true );\n} ?&gt;\n&lt;?php if( $description ): ?&gt;\n &lt;meta name=\"description\" content=\"&lt;?php print $description; ?&gt;\"\n&lt;?php endif ?&gt;\n</code></pre>\n" }, { "answer_id": 286133, "author": "MarkPraschan", "author_id": 129862, "author_profile": "https://wordpress.stackexchange.com/users/129862", "pm_score": 1, "selected": false, "text": "<p>You should be able to remove the existing description tag with the following code:</p>\n\n<pre><code>remove_action( 'wp_head', '_wp_render_title_tag', 1 );\n</code></pre>\n\n<p>Put the above snippet inside the same function you are using to conditionally add a new tag so there is always only a single description tag at a time.</p>\n" } ]
2017/03/08
[ "https://wordpress.stackexchange.com/questions/259410", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114799/" ]
Wordpress renders a meta description tag with the content of the blog post as the value for the description. I already generated in the `header.php` what I want the description to be, no matter what. However, the old one is still in there. I checked `single-post.php` and `header.php` and there is nothing rendering the meta description. So it HAS to be the `wp_head()` function. Is there anyway I can put something in my `functions.php` or something to ensure that on certain pages the meta description is removed from `wp_head()`?
You should be able to remove the existing description tag with the following code: ``` remove_action( 'wp_head', '_wp_render_title_tag', 1 ); ``` Put the above snippet inside the same function you are using to conditionally add a new tag so there is always only a single description tag at a time.
259,416
<p>I have a custom post template on which I want to show a list of other children of this post's parent. I already have the parent post ID in a variable ($parent_artist_id), which is being used elsewhere on the page. Here is my code:</p> <pre><code> $pastshowargs = array( 'post_parent' =&gt; $parent_artist_id, 'post_type' =&gt; 'shows', 'numberposts' =&gt; -1, 'order' =&gt; 'ASC', 'orderby' =&gt; 'title' ); $child_posts = get_posts($pastshowargs); if ( !empty($child_posts) ) { echo "&lt;ul&gt;"; foreach ($child_posts as $child_post) { $showname = get_the_title($child_post-&gt;ID); $parentartistid = wpcf_pr_post_get_belongs($child_post-&gt;ID, 'artist'); echo "&lt;li&gt;" . $showname . " (". $parentartistid . ")&lt;/li&gt;"; } echo "&lt;/ul&gt;"; } else { echo "empty"; } </code></pre> <p>The problem is that this produces nothing if I supply an ID for 'post_parent'. If I manually set the ID as '0' or remove that parameter altogether, I get a list of all the 'shows' posts, but putting any number in the post_parent parameter gets me nothing.</p> <p>Any idea what I've done wrong?</p>
[ { "answer_id": 259467, "author": "hcheung", "author_id": 111577, "author_profile": "https://wordpress.stackexchange.com/users/111577", "pm_score": 0, "selected": false, "text": "<p>If you want to remote <code>&lt;meta name=\"description\" content=\"\" /&gt;</code> in html head, Add </p>\n\n<pre><code>remove_action('wp_head', 'description');\n</code></pre>\n\n<p>into your function.php. </p>\n" }, { "answer_id": 259582, "author": "hcheung", "author_id": 111577, "author_profile": "https://wordpress.stackexchange.com/users/111577", "pm_score": 0, "selected": false, "text": "<p>For change the content of the meta description:</p>\n\n<pre><code>&lt;?php \n$description = '';\nif( is_single() or is_page() ){\n global $post;\n $description = get_post_meta( $post-&gt;ID, $this-&gt;meta_key, true );\n} ?&gt;\n&lt;?php if( $description ): ?&gt;\n &lt;meta name=\"description\" content=\"&lt;?php print $description; ?&gt;\"\n&lt;?php endif ?&gt;\n</code></pre>\n" }, { "answer_id": 286133, "author": "MarkPraschan", "author_id": 129862, "author_profile": "https://wordpress.stackexchange.com/users/129862", "pm_score": 1, "selected": false, "text": "<p>You should be able to remove the existing description tag with the following code:</p>\n\n<pre><code>remove_action( 'wp_head', '_wp_render_title_tag', 1 );\n</code></pre>\n\n<p>Put the above snippet inside the same function you are using to conditionally add a new tag so there is always only a single description tag at a time.</p>\n" } ]
2017/03/08
[ "https://wordpress.stackexchange.com/questions/259416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31013/" ]
I have a custom post template on which I want to show a list of other children of this post's parent. I already have the parent post ID in a variable ($parent\_artist\_id), which is being used elsewhere on the page. Here is my code: ``` $pastshowargs = array( 'post_parent' => $parent_artist_id, 'post_type' => 'shows', 'numberposts' => -1, 'order' => 'ASC', 'orderby' => 'title' ); $child_posts = get_posts($pastshowargs); if ( !empty($child_posts) ) { echo "<ul>"; foreach ($child_posts as $child_post) { $showname = get_the_title($child_post->ID); $parentartistid = wpcf_pr_post_get_belongs($child_post->ID, 'artist'); echo "<li>" . $showname . " (". $parentartistid . ")</li>"; } echo "</ul>"; } else { echo "empty"; } ``` The problem is that this produces nothing if I supply an ID for 'post\_parent'. If I manually set the ID as '0' or remove that parameter altogether, I get a list of all the 'shows' posts, but putting any number in the post\_parent parameter gets me nothing. Any idea what I've done wrong?
You should be able to remove the existing description tag with the following code: ``` remove_action( 'wp_head', '_wp_render_title_tag', 1 ); ``` Put the above snippet inside the same function you are using to conditionally add a new tag so there is always only a single description tag at a time.
259,420
<p>I am doing a post in wordpress, but I want to put a video as part of the post. I mean, I have a paragraph but after the paragraph I want to put a video. I did put it as media, but it just shows a link and if I clic on the link it downloads the file, and I just want to play the video, not to download it. What can I do? Thanks!</p>
[ { "answer_id": 259467, "author": "hcheung", "author_id": 111577, "author_profile": "https://wordpress.stackexchange.com/users/111577", "pm_score": 0, "selected": false, "text": "<p>If you want to remote <code>&lt;meta name=\"description\" content=\"\" /&gt;</code> in html head, Add </p>\n\n<pre><code>remove_action('wp_head', 'description');\n</code></pre>\n\n<p>into your function.php. </p>\n" }, { "answer_id": 259582, "author": "hcheung", "author_id": 111577, "author_profile": "https://wordpress.stackexchange.com/users/111577", "pm_score": 0, "selected": false, "text": "<p>For change the content of the meta description:</p>\n\n<pre><code>&lt;?php \n$description = '';\nif( is_single() or is_page() ){\n global $post;\n $description = get_post_meta( $post-&gt;ID, $this-&gt;meta_key, true );\n} ?&gt;\n&lt;?php if( $description ): ?&gt;\n &lt;meta name=\"description\" content=\"&lt;?php print $description; ?&gt;\"\n&lt;?php endif ?&gt;\n</code></pre>\n" }, { "answer_id": 286133, "author": "MarkPraschan", "author_id": 129862, "author_profile": "https://wordpress.stackexchange.com/users/129862", "pm_score": 1, "selected": false, "text": "<p>You should be able to remove the existing description tag with the following code:</p>\n\n<pre><code>remove_action( 'wp_head', '_wp_render_title_tag', 1 );\n</code></pre>\n\n<p>Put the above snippet inside the same function you are using to conditionally add a new tag so there is always only a single description tag at a time.</p>\n" } ]
2017/03/08
[ "https://wordpress.stackexchange.com/questions/259420", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114684/" ]
I am doing a post in wordpress, but I want to put a video as part of the post. I mean, I have a paragraph but after the paragraph I want to put a video. I did put it as media, but it just shows a link and if I clic on the link it downloads the file, and I just want to play the video, not to download it. What can I do? Thanks!
You should be able to remove the existing description tag with the following code: ``` remove_action( 'wp_head', '_wp_render_title_tag', 1 ); ``` Put the above snippet inside the same function you are using to conditionally add a new tag so there is always only a single description tag at a time.
259,441
<p>I wanted to add a search form inside a div using the code bellow:</p> <p><code>printf( '&lt;div class="entry"&gt;&lt;p&gt;%s&lt;/p&gt;%s&lt;/div&gt;', apply_filters( 'genesis_noposts_text', __( 'Try again below.', 'genesis' ) ), get_search_form() );</code></p> <p>But every time I add the <code>get_search_form()</code> it's generated before the div, like the following:</p> <pre><code>&lt;form&gt;&lt;/form&gt; &lt;div class="entry"&gt;&lt;/div&gt; </code></pre> <p>The workaround I found was to split the code, but I wanted to know if there is a better solution that works properly.</p> <pre><code>remove_action( 'genesis_loop_else', 'genesis_do_noposts' ); add_action( 'genesis_loop_else', 'mytheme_do_noposts' ); function mytheme_do_noposts() { printf( '&lt;div class="entry"&gt;&lt;p&gt;%s&lt;/p&gt;', apply_filters( 'genesis_noposts_text', __( 'Try again below.', 'genesis' ) ) ); printf( '%s&lt;/div&gt;', get_search_form() ); } </code></pre> <hr> <p><a href="https://developer.wordpress.org/reference/functions/get_search_form/" rel="nofollow noreferrer">get_search_form</a></p>
[ { "answer_id": 259443, "author": "Christina", "author_id": 64742, "author_profile": "https://wordpress.stackexchange.com/users/64742", "pm_score": 3, "selected": true, "text": "<p>The <code>get_search_form()</code> echos so it will always show up before returns. Use:</p>\n\n<pre><code>get_search_form( false )\n</code></pre>\n" }, { "answer_id": 259711, "author": "Zelda", "author_id": 115077, "author_profile": "https://wordpress.stackexchange.com/users/115077", "pm_score": 2, "selected": false, "text": "<p>The solution is to use <code>get_search_form( false )</code>.</p>\n\n<p><code>get_search_form()</code> will output the <code>search form</code>. Since you are trying to use the result in a string context, you need the function to return the <code>html</code> in form of a string, which you are passing through <code>printf</code>.</p>\n\n<p>The only parameter for <code>get_search_form</code> controls that behavior. By default it prints, but if you pass <code>false</code>, it will return the string that you need.</p>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259441", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115018/" ]
I wanted to add a search form inside a div using the code bellow: `printf( '<div class="entry"><p>%s</p>%s</div>', apply_filters( 'genesis_noposts_text', __( 'Try again below.', 'genesis' ) ), get_search_form() );` But every time I add the `get_search_form()` it's generated before the div, like the following: ``` <form></form> <div class="entry"></div> ``` The workaround I found was to split the code, but I wanted to know if there is a better solution that works properly. ``` remove_action( 'genesis_loop_else', 'genesis_do_noposts' ); add_action( 'genesis_loop_else', 'mytheme_do_noposts' ); function mytheme_do_noposts() { printf( '<div class="entry"><p>%s</p>', apply_filters( 'genesis_noposts_text', __( 'Try again below.', 'genesis' ) ) ); printf( '%s</div>', get_search_form() ); } ``` --- [get\_search\_form](https://developer.wordpress.org/reference/functions/get_search_form/)
The `get_search_form()` echos so it will always show up before returns. Use: ``` get_search_form( false ) ```
259,447
<p>I wanted to know if there were any ways to easily hide a selected user's user page. I've yet to find any code that does so. I've only found code to remove all user pages.</p> <p>Thanks</p>
[ { "answer_id": 259448, "author": "Faysal Mahamud", "author_id": 83752, "author_profile": "https://wordpress.stackexchange.com/users/83752", "pm_score": 0, "selected": false, "text": "<p>If you want to hide the user in user list page. The following working for you.</p>\n\n<p>//yousiteurl/wp-admin/users.php</p>\n\n<p>Here is the code which hides specific user. It is tested and working fine.</p>\n\n<p>Add this in functions.php in your theme.</p>\n\n<p><strong>functions.php</strong></p>\n\n<p>//change user-14 to your user id.</p>\n\n<pre><code>&lt;?php \n add_action('admin_head' , 'ft_hide_administrator_user');\n function ft_hide_administrator_user(){\n global $pagenow;\n if ( 'users.php' == $pagenow ){\n wp_enqueue_script('jquery');\n }\n ?&gt;\n &lt;style&gt;\n #user-14{display:none;}\n &lt;/style&gt;\n &lt;script type='text/javascript' &gt;\n jQuery(document).ready(function(){\n //jQuery('#user-14').remove(); // to remove users.php list page html\n jQuery('#user-14').hide(); // to hide users.php list page html\n var total_count = jQuery(\".users-php .subsubsub li.all .count\").text();\n total_count = total_count.substring(1, total_count.length - 1) - 1;\n jQuery('.users-php .subsubsub li.all .count').text('('+total_count+')');\n\n\n var total_count = jQuery(\".users-php .subsubsub li.administrator .count\").text();\n total_count = total_count.substring(1, total_count.length - 1) - 1;\n jQuery('.users-php .subsubsub li.administrator .count').text('('+total_count+')');\n\n });\n &lt;/script&gt;\n &lt;?php\n }\n</code></pre>\n" }, { "answer_id": 259449, "author": "ricotheque", "author_id": 34238, "author_profile": "https://wordpress.stackexchange.com/users/34238", "pm_score": 1, "selected": false, "text": "<p>I'm assuming you want to hide the author page on the site itself (and not in <code>wp-admin</code>).</p>\n\n<p>To do that, just create a new template file called <code>author-{$id}.php</code>, where <code>{$id}</code> is replaced by the ID of the author you want to hide. So if the author ID is <code>6</code>, the template file should be called <code>author-6.php</code>.</p>\n\n<p>Inside the new file, put this in:</p>\n\n<pre><code>&lt;?php\nheader( \"HTTP/1.1 301 Moved Permanently\" );\nwp_redirect( get_home_url() );\nexit;\n?&gt;\n</code></pre>\n\n<p>Now when you try to load the author's page, it will just redirect to the site visitor to your home page.</p>\n\n<p>(<a href=\"http://blog.futtta.be/2015/03/03/quick-tip-disabling-wordpress-author-pages/\" rel=\"nofollow noreferrer\">Source</a>)</p>\n" }, { "answer_id": 281864, "author": "Eng Ahmed Bltagy", "author_id": 70029, "author_profile": "https://wordpress.stackexchange.com/users/70029", "pm_score": 0, "selected": false, "text": "<p>I think we can use <a href=\"https://developer.wordpress.org/reference/hooks/pre_user_query/\" rel=\"nofollow noreferrer\"><code>pre_user_query</code></a> filter and modify or adjust the <code>where</code> query.\nSomething like the following code:</p>\n\n<pre><code>add_action( 'pre_user_query', function( $uqi ) {\n global $wpdb;\n $uqi-&gt;query_where .= ' AND id != 1';\n});\n</code></pre>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96587/" ]
I wanted to know if there were any ways to easily hide a selected user's user page. I've yet to find any code that does so. I've only found code to remove all user pages. Thanks
I'm assuming you want to hide the author page on the site itself (and not in `wp-admin`). To do that, just create a new template file called `author-{$id}.php`, where `{$id}` is replaced by the ID of the author you want to hide. So if the author ID is `6`, the template file should be called `author-6.php`. Inside the new file, put this in: ``` <?php header( "HTTP/1.1 301 Moved Permanently" ); wp_redirect( get_home_url() ); exit; ?> ``` Now when you try to load the author's page, it will just redirect to the site visitor to your home page. ([Source](http://blog.futtta.be/2015/03/03/quick-tip-disabling-wordpress-author-pages/))
259,485
<p>My head is clearly not working here. The logic is simple but I can't seem to get it right. </p> <p>I have a tv schedule post type and I want to display: </p> <p><code>2016-12-01 2017-04-01 2017-05-17</code></p> <p>Instead of: <code>2016-12-01 2017-03-01 2017-03-01 2017-03-01 2017-03-01 2017-03-01</code></p> <p>At the moment I am stuck with repeating times. I want to only show one time if it already exists as in the first case. </p> <p>This is my code: </p> <pre><code>`&lt;?php $args = array( 'post_type' =&gt; 'tv-schedule', 'posts_per_page' =&gt; -1, 'orderby' =&gt; 'date', 'order' =&gt; 'ASC', 'post_status' =&gt; array('publish', 'future'), ); $posts_array = query_posts($args); foreach ($posts_array as $post_array) { $date = $post_array-&gt;post_date_gmt; $new_date = date ('Y-m-01', strtotime($date) ); echo $new_date . '&lt;br /&gt;'; /* if(!in_array($new_date, $post_array-&gt;post_date_gmt)){ //$a[]=$value; echo "test"; } */ }` </code></pre>
[ { "answer_id": 259525, "author": "Industrial Themes", "author_id": 274, "author_profile": "https://wordpress.stackexchange.com/users/274", "pm_score": 1, "selected": false, "text": "<p>Just set a flag to check for a new value, and only display the date if the new value does not match the flag, like so:</p>\n\n<pre><code>&lt;?php \n$args = array(\n 'post_type' =&gt; 'tv-schedule',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC',\n 'post_status' =&gt; array('publish', 'future'),\n);\n$posts_array = query_posts($args); \n\n$flag = ''; // set an initial value that won't match the first date\n\nforeach ($posts_array as $post_array) {\n $date = $post_array-&gt;post_date_gmt;\n $new_date = date ('Y-m-01', strtotime($date) );\n if($new_date != $flag) {\n echo $new_date . '&lt;br /&gt;';\n $flag = $new_date; // $flag only changes when we actually display a new date\n }\n\n /*\n if(!in_array($new_date, $post_array-&gt;post_date_gmt)){\n //$a[]=$value;\n echo \"test\";\n }\n */\n\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Changed !== to != so that it would work.</p>\n" }, { "answer_id": 259587, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": true, "text": "<p>I finally got it right... I knew my big head was not working: </p>\n\n<pre><code>&lt;?php \n$args = array(\n 'post_type' =&gt; 'tv-schedule',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC',\n 'post_status' =&gt; array('publish', 'future'),\n);\n$posts_array = query_posts($args); \n\n$lastdate = \"\"; \n\nforeach ($posts_array as $post_array) {\n\n $date = $post_array-&gt;post_date_gmt;\n $new_date = date ('Y-m-01', strtotime($date) );\n\n if ($newdate != $lastdate) {\n echo $newdate;\n }\n\n $lastdate = $newdate;\n\n}\n?&gt;\n</code></pre>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
My head is clearly not working here. The logic is simple but I can't seem to get it right. I have a tv schedule post type and I want to display: `2016-12-01 2017-04-01 2017-05-17` Instead of: `2016-12-01 2017-03-01 2017-03-01 2017-03-01 2017-03-01 2017-03-01` At the moment I am stuck with repeating times. I want to only show one time if it already exists as in the first case. This is my code: ``` `<?php $args = array( 'post_type' => 'tv-schedule', 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'ASC', 'post_status' => array('publish', 'future'), ); $posts_array = query_posts($args); foreach ($posts_array as $post_array) { $date = $post_array->post_date_gmt; $new_date = date ('Y-m-01', strtotime($date) ); echo $new_date . '<br />'; /* if(!in_array($new_date, $post_array->post_date_gmt)){ //$a[]=$value; echo "test"; } */ }` ```
I finally got it right... I knew my big head was not working: ``` <?php $args = array( 'post_type' => 'tv-schedule', 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'ASC', 'post_status' => array('publish', 'future'), ); $posts_array = query_posts($args); $lastdate = ""; foreach ($posts_array as $post_array) { $date = $post_array->post_date_gmt; $new_date = date ('Y-m-01', strtotime($date) ); if ($newdate != $lastdate) { echo $newdate; } $lastdate = $newdate; } ?> ```
259,493
<p>How to send user data in json format to another server when user register on wordpress site in PHP. I have a server url is like (<a href="http://1.2.3.4:49005/SingleMethodName=DomainManagementStripeService___DomainRegistration" rel="nofollow noreferrer">http://1.2.3.4:49005/SingleMethodName=DomainManagementStripeService___DomainRegistration</a>)</p> <p>when user register on wordpress site i want to send their name, email, custom fields data to my server in json format. Thanks</p> <p>Edited----- I am using mu-plugins for this purpose and bellow is the code i am using it for</p> <pre><code>&lt;?php add_action('init', 's2_payment_notification'); function s2_payment_notification() { if( isset($_POST['user_id'], $_POST['subscr_id'], $_POST['user_ip'],$_POST['user_piva'])) { $user_id = (integer)$_POST['user_id']; $subscr_id = (string)$_POST['subscr_id']; $user_ip = (string)$_POST['user_ip']; $user_piva = (integer)$_POST['user_piva']; $s2member_subscr_id = get_user_option('s2member_subscr_id', $user_id); $s2member_registration_ip = get_user_option('s2member_registration_ip', $user_id); $s2member_p_iva_fisc = get_user_option('p_iva_fisc', $user_id); $user_piva = wp_json_encode($s2member_p_iva_fisc); $user_ip = wp_json_encode($s2member_registration_ip); $subscr_id = wp_json_encode($s2member_subscr_id); wp_remote_post('http://1.2.3.123:49005/SingleMethodName=DomainManagementStripeService___DomainRegistration', [ 'headers' =&gt; ['content-type' =&gt; 'application/json'], 'body' =&gt; array( 'User_Id' =&gt; '$user_id', 'subscr_id' =&gt; '$subscr_id', 'user_ip' =&gt; '$user_ip', 'user_piva' =&gt; '$user_piva' ), ]); } else { wp_remote_post('http://1.2.3.123:49005/SingleMethodName=DomainManagementStripeService___DomainRegistration', [ 'headers' =&gt; ['content-type' =&gt; 'application/json'], 'body' =&gt; 'Everything is empty', ]); } } </code></pre>
[ { "answer_id": 259525, "author": "Industrial Themes", "author_id": 274, "author_profile": "https://wordpress.stackexchange.com/users/274", "pm_score": 1, "selected": false, "text": "<p>Just set a flag to check for a new value, and only display the date if the new value does not match the flag, like so:</p>\n\n<pre><code>&lt;?php \n$args = array(\n 'post_type' =&gt; 'tv-schedule',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC',\n 'post_status' =&gt; array('publish', 'future'),\n);\n$posts_array = query_posts($args); \n\n$flag = ''; // set an initial value that won't match the first date\n\nforeach ($posts_array as $post_array) {\n $date = $post_array-&gt;post_date_gmt;\n $new_date = date ('Y-m-01', strtotime($date) );\n if($new_date != $flag) {\n echo $new_date . '&lt;br /&gt;';\n $flag = $new_date; // $flag only changes when we actually display a new date\n }\n\n /*\n if(!in_array($new_date, $post_array-&gt;post_date_gmt)){\n //$a[]=$value;\n echo \"test\";\n }\n */\n\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Changed !== to != so that it would work.</p>\n" }, { "answer_id": 259587, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": true, "text": "<p>I finally got it right... I knew my big head was not working: </p>\n\n<pre><code>&lt;?php \n$args = array(\n 'post_type' =&gt; 'tv-schedule',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC',\n 'post_status' =&gt; array('publish', 'future'),\n);\n$posts_array = query_posts($args); \n\n$lastdate = \"\"; \n\nforeach ($posts_array as $post_array) {\n\n $date = $post_array-&gt;post_date_gmt;\n $new_date = date ('Y-m-01', strtotime($date) );\n\n if ($newdate != $lastdate) {\n echo $newdate;\n }\n\n $lastdate = $newdate;\n\n}\n?&gt;\n</code></pre>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259493", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108076/" ]
How to send user data in json format to another server when user register on wordpress site in PHP. I have a server url is like (<http://1.2.3.4:49005/SingleMethodName=DomainManagementStripeService___DomainRegistration>) when user register on wordpress site i want to send their name, email, custom fields data to my server in json format. Thanks Edited----- I am using mu-plugins for this purpose and bellow is the code i am using it for ``` <?php add_action('init', 's2_payment_notification'); function s2_payment_notification() { if( isset($_POST['user_id'], $_POST['subscr_id'], $_POST['user_ip'],$_POST['user_piva'])) { $user_id = (integer)$_POST['user_id']; $subscr_id = (string)$_POST['subscr_id']; $user_ip = (string)$_POST['user_ip']; $user_piva = (integer)$_POST['user_piva']; $s2member_subscr_id = get_user_option('s2member_subscr_id', $user_id); $s2member_registration_ip = get_user_option('s2member_registration_ip', $user_id); $s2member_p_iva_fisc = get_user_option('p_iva_fisc', $user_id); $user_piva = wp_json_encode($s2member_p_iva_fisc); $user_ip = wp_json_encode($s2member_registration_ip); $subscr_id = wp_json_encode($s2member_subscr_id); wp_remote_post('http://1.2.3.123:49005/SingleMethodName=DomainManagementStripeService___DomainRegistration', [ 'headers' => ['content-type' => 'application/json'], 'body' => array( 'User_Id' => '$user_id', 'subscr_id' => '$subscr_id', 'user_ip' => '$user_ip', 'user_piva' => '$user_piva' ), ]); } else { wp_remote_post('http://1.2.3.123:49005/SingleMethodName=DomainManagementStripeService___DomainRegistration', [ 'headers' => ['content-type' => 'application/json'], 'body' => 'Everything is empty', ]); } } ```
I finally got it right... I knew my big head was not working: ``` <?php $args = array( 'post_type' => 'tv-schedule', 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'ASC', 'post_status' => array('publish', 'future'), ); $posts_array = query_posts($args); $lastdate = ""; foreach ($posts_array as $post_array) { $date = $post_array->post_date_gmt; $new_date = date ('Y-m-01', strtotime($date) ); if ($newdate != $lastdate) { echo $newdate; } $lastdate = $newdate; } ?> ```
259,499
<p>There is the following hierarchical taxonomy structure of a specific post:</p> <ul> <li>Term A <ul> <li>SubTerm A.1</li> <li>SubTerm A.2 <ul> <li>SubTerm A.2.1</li> </ul></li> </ul></li> <li>Term B <ul> <li>SubTerm B.1 <ul> <li>SubTerm B.1.1</li> <li>SubTerm B.1.2</li> </ul></li> </ul></li> </ul> <p>How to display</p> <ol> <li>all parent terms (result: A, B) </li> <li>all second level terms (result: A.1, A.2, B.1) </li> <li>all third level terms (result: A.2.1, B.1.1, B.1.2)</li> </ol>
[ { "answer_id": 259502, "author": "Ben Casey", "author_id": 114997, "author_profile": "https://wordpress.stackexchange.com/users/114997", "pm_score": 1, "selected": false, "text": "<p>I love a good challenge!</p>\n\n<p>The function here:</p>\n\n<pre><code>function get_post_categories_sorted ( $post_id ){\n\n $terms = wp_get_post_terms( $post_id, 'category' );\n\n $sorted_terms = [];\n\n foreach( $terms as $term ){\n\n $depth = count( get_ancestors( $term-&gt;term_id, 'category' ) );\n\n if( ! array_key_exists( $depth, $sorted_terms ) ){\n $sorted_terms[$depth] = [];\n }\n\n $sorted_terms[$depth][] = $term;\n\n }\n\n return $sorted_terms;\n\n}\n</code></pre>\n\n<p>will give you an array with the structure in the following image. <code>$sorted_terms[0]</code> contains the top level terms, <code>$sorted_terms[1]</code> all the second level term and so on.</p>\n\n<p><a href=\"https://i.stack.imgur.com/7bXgI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7bXgI.png\" alt=\"Sorted Terms for a given post\"></a></p>\n\n<p>It would definitely be worth using a cache or the transients API to store the data as it could get expensive with a lot of terms to sort through as the call to get_ancestors involves a call back to the database for each level it has to traverse back up the chain.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>You can use this something like the following:</p>\n\n<pre><code>$sorted_terms = get_post_categories_sorted( get_the_ID() );\n\nforeach( $sorted_terms as $key =&gt; $level_items ){\n\n $number = $key + 1;\n\n echo sprintf( '&lt;p&gt;Level %s Categories&lt;/p&gt;', $number );\n\n echo '&lt;ul&gt;';\n\n foreach( $level_items as $term ){\n echo sprintf( '&lt;li&gt;%s&lt;/li&gt;', $term-&gt;name );\n }\n\n echo '&lt;/ul&gt;';\n\n}\n</code></pre>\n\n<p><strong>EDIT 2</strong></p>\n\n<p>To just use a specific level, you can simplify the code above like this:</p>\n\n<pre><code>$sorted_terms = get_post_categories_sorted( get_the_ID() );\n\necho '&lt;p&gt;Level 1 Categories&lt;/p&gt;';\n\necho '&lt;ul&gt;';\n //Change the 0 here to whatever level you need, \n //just remember is is 0 based; IE the first level is 0, 2nd level is 1 etc.\n //If the number doesn't exist, PHP will throw an undefined index error.\n\n foreach( $sorted_items[0] as $term ){ \n echo sprintf( '&lt;li&gt;%s&lt;/li&gt;', $term-&gt;name );\n }\n\necho '&lt;/ul&gt;';\n</code></pre>\n" }, { "answer_id": 259536, "author": "Traveler", "author_id": 51307, "author_profile": "https://wordpress.stackexchange.com/users/51307", "pm_score": 0, "selected": false, "text": "<p>This <a href=\"https://wordpress.stackexchange.com/questions/244577/hierarchical-display-of-custom-taxonomy\">code</a> is partially working, in this example displaying the terms of third level with <code>'depth' =&gt; 3</code>. Unfortunately the parent terms are listed too, how is it possible to exclude the parent terms?</p>\n\n<pre><code>&lt;?php function wpse244577_list_terms( $taxonomy, $separator = ', ' ) { \n // Get the term IDs assigned to post.\n $post_terms = wp_get_object_terms( get_the_ID(), $taxonomy, [ 'fields' =&gt; 'ids' ] );\n if ( ! empty( $post_terms ) &amp;&amp; ! is_wp_error( $post_terms ) ) {\n $terms = wp_list_categories( [\n 'title_li' =&gt; '',\n 'style' =&gt; 'none',\n 'echo' =&gt; false,\n 'taxonomy' =&gt; $taxonomy,\n 'include' =&gt; $post_terms,\n 'separator' =&gt; $separator,\n 'depth' =&gt; 3,\n ] );\n $terms = rtrim( trim( str_replace( $separator, $separator, $terms ) ), ', ' );\n $terms = explode( $separator, $terms );\n $terms = array_reverse( $terms );\n $terms = implode( $separator, $terms );\n echo $terms;\n }\n} wpse244577_list_terms( 'custom_taxonomy' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 259884, "author": "Willington Vega", "author_id": 52, "author_profile": "https://wordpress.stackexchange.com/users/52", "pm_score": 0, "selected": false, "text": "<p>Here is an alternative solution. The following function takes an array of arguments, with two possible keys:</p>\n\n<ul>\n<li><code>taxonomy</code>: A string. The name of the Taxonomy. </li>\n<li><code>level</code>: An int. Use 0 for the root elements, 1 for the children of the root elements, and so on.</li>\n</ul>\n\n<p>It returns an array of <code>WP_Term</code> objects.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function wpse_259499_get_subterms( $args = array() ) {\n $args = wp_parse_args( $args, array( 'taxonomy' =&gt; 'category', 'level' =&gt; 0 ) );\n\n $subterms = get_transient( 'taxonomy-subterms-' . $args['taxonomy'] . '-' . $args['level'] );\n $terms_ids = array();\n\n if ( is_array( $subterms ) ) {\n return $subterms;\n }\n\n if ( 0 == $args['level'] ) {\n $terms = get_terms( array(\n 'taxonomy' =&gt; $args['taxonomy'],\n 'get' =&gt; 'all',\n 'orderby' =&gt; 'id',\n 'fields' =&gt; 'id=&gt;parent',\n ) );\n\n foreach ( $terms as $term_id =&gt; $parent ) {\n if ( ! $parent ) {\n $terms_ids[] = $term_id;\n }\n }\n } else if ( $hierarchy = _get_term_hierarchy( $args['taxonomy'] ) ) {\n $subterms_args = array( 'taxonomy' =&gt; $args['taxonomy'], 'level' =&gt; $args['level'] - 1 );\n\n foreach ( wpse_259499_get_subterms( $subterms_args ) as $term ) {\n if ( isset( $hierarchy[ $term-&gt;term_id ] ) ) {\n $terms_ids = array_merge( $terms_ids, $hierarchy[ $term-&gt;term_id ] );\n }\n }\n }\n\n if ( $terms_ids ) {\n $subterms = get_terms( array(\n 'taxonomy' =&gt; $args['taxonomy'],\n 'get' =&gt; 'all',\n 'include' =&gt; $terms_ids,\n ) );\n } else {\n $subterms = array();\n }\n\n set_transient( 'taxonomy-subterms-' . $args['taxonomy'] . '-' . $args['level'], $subterms, HOUR_IN_SECONDS );\n\n return $subterms;\n}\n</code></pre>\n\n<p><strong>Note 1:</strong> If you decide to rename the function, please note that the function is calling itself, so you need to change the name in the recursive call as well.</p>\n\n<p><strong>Note 2:</strong> The results are being stored in a transient for an hour. In order to get fresh results during development, you can add the following line at the beginning of the function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>delete_transient( 'taxonomy-subterms-' . $args['taxonomy'] . '-' . $args['level'] );\n</code></pre>\n\n<p>You may also need to delete those transients every time a category in the taxonomy of interest is added, deleted or modified, if you want to have accurate results all the time.</p>\n\n<h2>Example</h2>\n\n<p>The following code can be used in a template, to generate an unordered list of links to all terms in the selected level:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;ul&gt;\n&lt;?php foreach ( wpse_259499_get_subterms( array( 'taxonomy' =&gt; 'category', 'level' =&gt; 0 ) ) as $term ): ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php echo esc_attr( get_term_link( $term ) ); ?&gt;\"&gt;&lt;?php echo esc_html( $term-&gt;name ); ?&gt;&lt;/a&gt;&lt;/li&gt;\n&lt;?php endforeach; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 260222, "author": "Traveler", "author_id": 51307, "author_profile": "https://wordpress.stackexchange.com/users/51307", "pm_score": 1, "selected": false, "text": "<p>Found the easiest solution with the <a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">get_the_terms() | Function</a>. I really do not have a clue why the figures of level 2 (<code>$terms[2]</code>) and 3 (<code>$terms[1]</code>) are not in the correct order, but at least it is realized with a Wordpress function.</p>\n\n<p>Level 1:</p>\n\n<pre><code>&lt;?php\n$terms = get_the_terms( $post-&gt;ID, 'custom_taxonomy' );\necho $terms[0]-&gt;name;\n?&gt; \n</code></pre>\n\n<p>Level 2:</p>\n\n<pre><code>&lt;?php\n$terms = get_the_terms( $post-&gt;ID, 'custom_taxonomy' );\necho $terms[2]-&gt;name;\n?&gt; \n</code></pre>\n\n<p>Level3:</p>\n\n<pre><code>&lt;?php\n$terms = get_the_terms( $post-&gt;ID, 'custom_taxonomy' );\necho $terms[1]-&gt;name;\n?&gt; \n</code></pre>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259499", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51307/" ]
There is the following hierarchical taxonomy structure of a specific post: * Term A + SubTerm A.1 + SubTerm A.2 - SubTerm A.2.1 * Term B + SubTerm B.1 - SubTerm B.1.1 - SubTerm B.1.2 How to display 1. all parent terms (result: A, B) 2. all second level terms (result: A.1, A.2, B.1) 3. all third level terms (result: A.2.1, B.1.1, B.1.2)
I love a good challenge! The function here: ``` function get_post_categories_sorted ( $post_id ){ $terms = wp_get_post_terms( $post_id, 'category' ); $sorted_terms = []; foreach( $terms as $term ){ $depth = count( get_ancestors( $term->term_id, 'category' ) ); if( ! array_key_exists( $depth, $sorted_terms ) ){ $sorted_terms[$depth] = []; } $sorted_terms[$depth][] = $term; } return $sorted_terms; } ``` will give you an array with the structure in the following image. `$sorted_terms[0]` contains the top level terms, `$sorted_terms[1]` all the second level term and so on. [![Sorted Terms for a given post](https://i.stack.imgur.com/7bXgI.png)](https://i.stack.imgur.com/7bXgI.png) It would definitely be worth using a cache or the transients API to store the data as it could get expensive with a lot of terms to sort through as the call to get\_ancestors involves a call back to the database for each level it has to traverse back up the chain. **EDIT** You can use this something like the following: ``` $sorted_terms = get_post_categories_sorted( get_the_ID() ); foreach( $sorted_terms as $key => $level_items ){ $number = $key + 1; echo sprintf( '<p>Level %s Categories</p>', $number ); echo '<ul>'; foreach( $level_items as $term ){ echo sprintf( '<li>%s</li>', $term->name ); } echo '</ul>'; } ``` **EDIT 2** To just use a specific level, you can simplify the code above like this: ``` $sorted_terms = get_post_categories_sorted( get_the_ID() ); echo '<p>Level 1 Categories</p>'; echo '<ul>'; //Change the 0 here to whatever level you need, //just remember is is 0 based; IE the first level is 0, 2nd level is 1 etc. //If the number doesn't exist, PHP will throw an undefined index error. foreach( $sorted_items[0] as $term ){ echo sprintf( '<li>%s</li>', $term->name ); } echo '</ul>'; ```
259,501
<p>On a site where I filter custom taxonomy terms with FacetWP I'm trying to have the taxonomy term links go back to the homepage with the filters, instead of linking to the taxonomy term archives.</p> <p>I am not sure how to go about this, <code>term_link()</code> filter or rewrite rule. Of the filter there is little info available and my own knowledge of rewrite rules is lacking.</p> <p>Here is the single custom post type "site" on the staging site: <a href="https://sandbox-online.com/awidev/site/casa-azores/" rel="nofollow noreferrer">https://sandbox-online.com/awidev/site/casa-azores/</a></p> <p>the taxonomy terms are added manually to the single-site template, to showcase the differences:</p> <pre><code>echo '&lt;p&gt;taxonomy terms with links, rewrite set to &lt;em&gt;false&lt;/em&gt; '; the_terms( $post-&gt;ID, 'industry', ': ', ' / ' ); echo '&lt;/p&gt;'; $terms = get_the_term_list( $post-&gt;ID, 'industry', ': ', ' / ' ); $terms = strip_tags( $terms ); print '&lt;p&gt;taxonomy terms without links' . $terms . '&lt;/p&gt;'; print '&lt;p&gt;hardcoded link to homepage with correct facet &lt;a href="' . home_url() . '?fwp_industries_dropdown=holiday-rental"&gt;holiday rental&lt;/a&gt;&lt;/p&gt;'; </code></pre> <p>So basically I would like to be able to change <code>?industry=</code> into <code>?fwp_industries_dropdown=</code>.</p> <p>Is this possible with a <code>term_link()</code> filter and if so, how? Or would this be easier with a rewrite rule and then again how would I do that?</p> <p>Any help appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 259514, "author": "Laxmana", "author_id": 40948, "author_profile": "https://wordpress.stackexchange.com/users/40948", "pm_score": 2, "selected": true, "text": "<p>I know I am not answering exactly your question but in my opinion it is best to do it manually without messing with rewrite rules and filters. That way you keep also the default URL structure for terms templates, other plugins etc.</p>\n\n<pre><code>$terms = get_the_terms( $post-&gt;ID, 'industry');\n\nif($terms &amp;&amp; !is_wp_error($terms)){\n\n echo '&lt;ul&gt;';\n\n foreach ( $terms as $term ) {\n\n $url = home_url() . '?fwp_industries_dropdown=' . $term-&gt;slug;\n\n echo '&lt;li&gt;';\n echo '&lt;a href=\"' . $url . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;';\n echo '&lt;/li&gt;';\n\n }\n\n echo '&lt;/ul&gt;';\n}\n</code></pre>\n" }, { "answer_id": 259852, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In case someone is looking to do it with the term_link() filter, FacetWP has come with a suggestion too:</p>\n\n<pre><code>// add the code below to your child theme's functions.php file.\nfunction fwps_term_link_filter( $url, $term, $taxonomy ) {\n // change the industry to the name of your taxonomy\n if ( 'industry' === $taxonomy ) {\n $url = home_url() . '?fwp_industries_dropdown=' . $term-&gt;slug;\n }\n return $url;\n}\nadd_filter( 'term_link', 'fwps_term_link_filter', 10, 3 );\n</code></pre>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259501", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
On a site where I filter custom taxonomy terms with FacetWP I'm trying to have the taxonomy term links go back to the homepage with the filters, instead of linking to the taxonomy term archives. I am not sure how to go about this, `term_link()` filter or rewrite rule. Of the filter there is little info available and my own knowledge of rewrite rules is lacking. Here is the single custom post type "site" on the staging site: <https://sandbox-online.com/awidev/site/casa-azores/> the taxonomy terms are added manually to the single-site template, to showcase the differences: ``` echo '<p>taxonomy terms with links, rewrite set to <em>false</em> '; the_terms( $post->ID, 'industry', ': ', ' / ' ); echo '</p>'; $terms = get_the_term_list( $post->ID, 'industry', ': ', ' / ' ); $terms = strip_tags( $terms ); print '<p>taxonomy terms without links' . $terms . '</p>'; print '<p>hardcoded link to homepage with correct facet <a href="' . home_url() . '?fwp_industries_dropdown=holiday-rental">holiday rental</a></p>'; ``` So basically I would like to be able to change `?industry=` into `?fwp_industries_dropdown=`. Is this possible with a `term_link()` filter and if so, how? Or would this be easier with a rewrite rule and then again how would I do that? Any help appreciated. Thanks.
I know I am not answering exactly your question but in my opinion it is best to do it manually without messing with rewrite rules and filters. That way you keep also the default URL structure for terms templates, other plugins etc. ``` $terms = get_the_terms( $post->ID, 'industry'); if($terms && !is_wp_error($terms)){ echo '<ul>'; foreach ( $terms as $term ) { $url = home_url() . '?fwp_industries_dropdown=' . $term->slug; echo '<li>'; echo '<a href="' . $url . '">' . $term->name . '</a>'; echo '</li>'; } echo '</ul>'; } ```
259,544
<p>I am creating my own theme and was wondering if there is a way to remove <code>get_template_part()</code> when you're on a specific page? For example:</p> <pre><code>&lt;?php if ( is_page('blog') ) { [Remove]get_template_part('the', 'blog'); } ?&gt; </code></pre>
[ { "answer_id": 259548, "author": "nibnut", "author_id": 111316, "author_profile": "https://wordpress.stackexchange.com/users/111316", "pm_score": 0, "selected": false, "text": "<p>So I can think of a couple of ways at least:</p>\n\n<ol>\n<li>You could make a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/#creating-custom-page-templates-for-global-use\" rel=\"nofollow noreferrer\">new template</a> in your theme, that doesn't use <code>get_template_part</code>, and assign that template to pages you create in WP. (solution for multiple pages of the same type)</li>\n<li>You could create a <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#single-page\" rel=\"nofollow noreferrer\">single-use template</a> for just this page, (based on its slug) so that just this page has a special template that doesn't use <code>get_template_part</code></li>\n</ol>\n\n<p>Does that answer your question?</p>\n" }, { "answer_id": 259552, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 1, "selected": false, "text": "<p>you could do it the opposite way:</p>\n\n<pre><code>&lt;?php\nif ( !is_page('blog') ) {\n get_template_part('the', 'blog');\n}\n?&gt;\n</code></pre>\n\n<p>this would make it show up on all pages but the blog.</p>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259544", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106262/" ]
I am creating my own theme and was wondering if there is a way to remove `get_template_part()` when you're on a specific page? For example: ``` <?php if ( is_page('blog') ) { [Remove]get_template_part('the', 'blog'); } ?> ```
you could do it the opposite way: ``` <?php if ( !is_page('blog') ) { get_template_part('the', 'blog'); } ?> ``` this would make it show up on all pages but the blog.
259,557
<p>I have tried out a few things to remove the <code>&lt;br&gt;</code> being created in between shortcodes, I found one in another thread, it looked promising, but it didn't work out:</p> <pre><code>function the_content_filter($content) { $block = join("|",array("category_product_list", "category_products")); $rep = preg_replace("/(&lt;p&gt;)?\[($block)(\s[^\]]+)?\](&lt;\/p&gt;|&lt;br \/&gt;)?/","[$2$3]",$content); $rep = preg_replace("/(&lt;p&gt;)?\[\/($block)](&lt;\/p&gt;|&lt;br \/&gt;)?/","[/$2]",$rep); return $rep; } add_filter("the_content", "the_content_filter"); </code></pre> <p>I was reading that wpautop could do the trick but nothing is working for me. Do I need to modify my actual shortcode somehow?</p> <p>Here's one of the shortcodes I'm working with:</p> <pre><code>function category_product_list( $atts ) { extract(shortcode_atts(array( 'category' =&gt; '', 'per_page' =&gt; -1, 'orderby' =&gt; 'title', 'order' =&gt; 'asc' ), $atts)); $meta_query = WC()-&gt;query-&gt;get_meta_query(); $tax_query = WC()-&gt;query-&gt;get_tax_query(); $tax_query[] = array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'slug', 'terms' =&gt; array( esc_attr($category) ), 'operator' =&gt; 'IN', ); $args = array( 'post_type' =&gt; 'product', 'post_status' =&gt; 'publish', 'ignore_sticky_posts' =&gt; 1, 'posts_per_page' =&gt; $per_page, 'orderby' =&gt; $orderby, 'order' =&gt; $order, 'meta_query' =&gt; $meta_query, 'tax_query' =&gt; $tax_query ); $products = new WP_Query( $args ); if ( $products-&gt;have_posts() ) : $term_list = wp_get_post_terms($products-&gt;post-&gt;ID, 'product_cat', array("fields" =&gt; "all")); $first_term = $term_list[0]; $first_term_name = $first_term-&gt;name; $url = get_permalink(); $id = $products-&gt;post-&gt;ID; // $html_out = '&lt;h2&gt;Courses&lt;/h2&gt;'; $html_out = '&lt;ul class="simple-sitemap-courses"&gt;'; $html_out .= '&lt;li class="page-item page-item-' . $id . '"&gt;&lt;a href="' . $url . '"&gt;' . $first_term_name . '&lt;/a&gt;'; $html_out .= '&lt;ul class="children"&gt;'; while ($products-&gt;have_posts()) : $products-&gt;the_post(); $product = get_product( $products-&gt;post-&gt;ID ); $course_title = get_the_title(); $url = get_permalink(); $id = $products-&gt;post-&gt;ID; // Output product information here $html_out .= '&lt;li class="page-item page-item-' . $id . '"&gt;&lt;a href="' . $url . '"&gt;' . $course_title . '&lt;/a&gt;&lt;/li&gt;'; endwhile; $html_out .= '&lt;/ul&gt;'; $html_out .= '&lt;/li&gt;'; $html_out .= '&lt;/ul&gt;'; else : // No results $html_out = "No Courses Found."; endif; wp_reset_postdata(); return $html_out; } add_shortcode( 'category_product_list', 'category_product_list' ); </code></pre>
[ { "answer_id": 259620, "author": "LWS-Mo", "author_id": 88895, "author_profile": "https://wordpress.stackexchange.com/users/88895", "pm_score": 1, "selected": false, "text": "<p>I created a simple shortcode and added it two times to a page like so:</p>\n\n<pre><code>[my-shortcode]something[/my-shortcode]\n[my-shortcode]else[/my-shortcode]\n</code></pre>\n\n<p>As you can see, I added a line break (<code>&lt;br /&gt;</code>) after the first shortcode. So in the frontend it is also shown like this:</p>\n\n<pre><code>something\nelse\n</code></pre>\n\n<p>And in the HTML:</p>\n\n<pre><code>&lt;span&gt;something&lt;/span&gt;\n&lt;br /&gt;\n&lt;span&gt;else&lt;/span&gt;\n</code></pre>\n\n<p>Than I also used the <code>the_content</code> filter but with <code>strtr()</code> like this:</p>\n\n<pre><code> function remove_br_from_shortcodes($content){\n\n // look for the string \"]&lt;br /&gt;\" and replace it just with \"]\"\n $replace = array (\n ']&lt;br /&gt;' =&gt; ']'\n );\n $content = strtr($content, $replace);\n\n return $content;\n\n }\n add_filter('the_content', 'remove_br_from_shortcodes');\n</code></pre>\n\n<p>After refreshing the page, the frontend now shows:</p>\n\n<pre><code>something else\n</code></pre>\n\n<p>In the HTML:</p>\n\n<pre><code>&lt;span&gt;something&lt;/span&gt;\n&lt;span&gt;else&lt;/span&gt;\n</code></pre>\n\n<p>As the name of <code>the_content</code> filter already suggests, it is a filter for the <em>normal post/page content</em>, not, for example text-widgets or excerpts.</p>\n\n<p>If you also want to remove paragraphs (<code>&lt;p&gt;</code>) than please try adding this in the <code>$replace</code> array: (watch your comma´s!)</p>\n\n<pre><code>'&lt;p&gt;[' =&gt; '[',\n']&lt;/p&gt;' =&gt; ']',\n</code></pre>\n\n<p>With the PHP <code>strtr()</code> function, you can replace certain characters in a string. <a href=\"https://www.w3schools.com/php/func_string_strtr.asp\" rel=\"nofollow noreferrer\">More to read here.</a></p>\n" }, { "answer_id": 259635, "author": "H21", "author_id": 103994, "author_profile": "https://wordpress.stackexchange.com/users/103994", "pm_score": 0, "selected": false, "text": "<p>Try wrapping the shortcodes in <code>&lt;div&gt;</code> or <code>&lt;span&gt;</code> tags, if that's an option.</p>\n" } ]
2017/03/09
[ "https://wordpress.stackexchange.com/questions/259557", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96257/" ]
I have tried out a few things to remove the `<br>` being created in between shortcodes, I found one in another thread, it looked promising, but it didn't work out: ``` function the_content_filter($content) { $block = join("|",array("category_product_list", "category_products")); $rep = preg_replace("/(<p>)?\[($block)(\s[^\]]+)?\](<\/p>|<br \/>)?/","[$2$3]",$content); $rep = preg_replace("/(<p>)?\[\/($block)](<\/p>|<br \/>)?/","[/$2]",$rep); return $rep; } add_filter("the_content", "the_content_filter"); ``` I was reading that wpautop could do the trick but nothing is working for me. Do I need to modify my actual shortcode somehow? Here's one of the shortcodes I'm working with: ``` function category_product_list( $atts ) { extract(shortcode_atts(array( 'category' => '', 'per_page' => -1, 'orderby' => 'title', 'order' => 'asc' ), $atts)); $meta_query = WC()->query->get_meta_query(); $tax_query = WC()->query->get_tax_query(); $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array( esc_attr($category) ), 'operator' => 'IN', ); $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'ignore_sticky_posts' => 1, 'posts_per_page' => $per_page, 'orderby' => $orderby, 'order' => $order, 'meta_query' => $meta_query, 'tax_query' => $tax_query ); $products = new WP_Query( $args ); if ( $products->have_posts() ) : $term_list = wp_get_post_terms($products->post->ID, 'product_cat', array("fields" => "all")); $first_term = $term_list[0]; $first_term_name = $first_term->name; $url = get_permalink(); $id = $products->post->ID; // $html_out = '<h2>Courses</h2>'; $html_out = '<ul class="simple-sitemap-courses">'; $html_out .= '<li class="page-item page-item-' . $id . '"><a href="' . $url . '">' . $first_term_name . '</a>'; $html_out .= '<ul class="children">'; while ($products->have_posts()) : $products->the_post(); $product = get_product( $products->post->ID ); $course_title = get_the_title(); $url = get_permalink(); $id = $products->post->ID; // Output product information here $html_out .= '<li class="page-item page-item-' . $id . '"><a href="' . $url . '">' . $course_title . '</a></li>'; endwhile; $html_out .= '</ul>'; $html_out .= '</li>'; $html_out .= '</ul>'; else : // No results $html_out = "No Courses Found."; endif; wp_reset_postdata(); return $html_out; } add_shortcode( 'category_product_list', 'category_product_list' ); ```
I created a simple shortcode and added it two times to a page like so: ``` [my-shortcode]something[/my-shortcode] [my-shortcode]else[/my-shortcode] ``` As you can see, I added a line break (`<br />`) after the first shortcode. So in the frontend it is also shown like this: ``` something else ``` And in the HTML: ``` <span>something</span> <br /> <span>else</span> ``` Than I also used the `the_content` filter but with `strtr()` like this: ``` function remove_br_from_shortcodes($content){ // look for the string "]<br />" and replace it just with "]" $replace = array ( ']<br />' => ']' ); $content = strtr($content, $replace); return $content; } add_filter('the_content', 'remove_br_from_shortcodes'); ``` After refreshing the page, the frontend now shows: ``` something else ``` In the HTML: ``` <span>something</span> <span>else</span> ``` As the name of `the_content` filter already suggests, it is a filter for the *normal post/page content*, not, for example text-widgets or excerpts. If you also want to remove paragraphs (`<p>`) than please try adding this in the `$replace` array: (watch your comma´s!) ``` '<p>[' => '[', ']</p>' => ']', ``` With the PHP `strtr()` function, you can replace certain characters in a string. [More to read here.](https://www.w3schools.com/php/func_string_strtr.asp)
259,567
<p>I'm trying to figure out how to retrieve a user's roles from the API, but I haven't been able to sort it. Is this information not accessible by default?</p> <p>Can anyone point me in the right direction?</p>
[ { "answer_id": 259816, "author": "Shane Piscine", "author_id": 115129, "author_profile": "https://wordpress.stackexchange.com/users/115129", "pm_score": 1, "selected": false, "text": "<p>It seems that the short answer is you can't get there from here. While it's possible create users with a given role, there's no mechanism (via this interface) to retrieve a user's roles. If desired, one could extend the API to create a custom endpoint, but I will likely pursue a different route.</p>\n" }, { "answer_id": 286397, "author": "Fanalea", "author_id": 113748, "author_profile": "https://wordpress.stackexchange.com/users/113748", "pm_score": 0, "selected": false, "text": "<p>I tried to figure it out and it looks like you can get a list of capabilities and user's role by adding <strong>edit context</strong> to your request. It's also possible to receive list of users by specifying <strong>roles</strong> in request.</p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 316010, "author": "Zachary", "author_id": 151867, "author_profile": "https://wordpress.stackexchange.com/users/151867", "pm_score": 4, "selected": true, "text": "<p>This is totally possible by registering your own rest field into the response.</p>\n\n<p>Here's some documentation on modifying response data. \n<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/\" rel=\"noreferrer\">https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/</a></p>\n\n<p>Here's how to add roles to the endpoint:</p>\n\n<pre><code>function get_user_roles($object, $field_name, $request) {\n return get_userdata($object['id'])-&gt;roles;\n}\n\nadd_action('rest_api_init', function() {\n register_rest_field('user', 'roles', array(\n 'get_callback' =&gt; 'get_user_roles',\n 'update_callback' =&gt; null,\n 'schema' =&gt; array(\n 'type' =&gt; 'array'\n )\n ));\n});\n</code></pre>\n\n<p>Specifically, what I'm doing is creating a function called <code>get_user_roles</code> that retrieves the user roles, then registering a 'roles' field in the response, and tell it that the data comes from that function.</p>\n\n<p>I also ran into an issue of it not playing nice when the data returned an <code>array</code>, so I told the schema to expect it in the <code>schema</code> property of the array passed in <code>register_rest_field</code></p>\n" }, { "answer_id": 339794, "author": "frank.m", "author_id": 169545, "author_profile": "https://wordpress.stackexchange.com/users/169545", "pm_score": 3, "selected": false, "text": "<p>You just need to pass the context parameter with a value of <code>edit</code> in your url:</p>\n<pre><code>http://demo.wp-api.org/wp-json/wp/v2/users/1?context=edit\n</code></pre>\n<p>According to the <a href=\"https://developer.wordpress.org/rest-api/reference/users/#schema-roles\" rel=\"nofollow noreferrer\">WordPress REST API Handbook</a>, you have to pass the context=edit to make this attribute appear in the response. If you do not include <code>?context=edit</code> the <code>roles</code> attribute will not be shown.</p>\n" } ]
2017/03/10
[ "https://wordpress.stackexchange.com/questions/259567", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115129/" ]
I'm trying to figure out how to retrieve a user's roles from the API, but I haven't been able to sort it. Is this information not accessible by default? Can anyone point me in the right direction?
This is totally possible by registering your own rest field into the response. Here's some documentation on modifying response data. <https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/> Here's how to add roles to the endpoint: ``` function get_user_roles($object, $field_name, $request) { return get_userdata($object['id'])->roles; } add_action('rest_api_init', function() { register_rest_field('user', 'roles', array( 'get_callback' => 'get_user_roles', 'update_callback' => null, 'schema' => array( 'type' => 'array' ) )); }); ``` Specifically, what I'm doing is creating a function called `get_user_roles` that retrieves the user roles, then registering a 'roles' field in the response, and tell it that the data comes from that function. I also ran into an issue of it not playing nice when the data returned an `array`, so I told the schema to expect it in the `schema` property of the array passed in `register_rest_field`
259,586
<p>I'm extending Wordpress REST API with a custom plugin, and I'm in the need of adding a new field to the user response.</p> <p>The problem is that this field has to appear only in base of the user role.</p> <p>For example I want a field <code>custom_field</code> appear in the response only if the user is <code>administrator</code> and not <code>contributor</code>.</p> <p>At the moment I'm using the <code>register_rest_field()</code> function, but it allows me to chose only the type of object.</p> <p>Do you know if there is a workaround to this issue? Or do you know better ways to reach the same result?</p> <p>P.S. I'm using WP 4.7.3</p>
[ { "answer_id": 259592, "author": "Ben Casey", "author_id": 114997, "author_profile": "https://wordpress.stackexchange.com/users/114997", "pm_score": 0, "selected": false, "text": "<p>You can use the filter <code>rest_prepare_user</code></p>\n\n<p>Something like this should do the trick I think.</p>\n\n<pre><code>function my_rest_prepare_user( WP_REST_Response $response, WP_User $user, WP_REST_Request $request ){\n\n if( in_array( 'administrator', $user-&gt;roles ) ){\n\n $data = $response-&gt;get_data();\n\n $data['custom_field'] = get_user_meta( $user-&gt;ID, 'custom_field', true );\n\n $response-&gt;set_data( $data );\n\n }\n\n return $response;\n\n}\nadd_filter( 'rest_prepare_user', 'my_rest_prepare_user', 10, 3 );\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>If you need to update the user you can register a custom route</p>\n\n<pre><code>function yoursite_update_user( WP_REST_Request $request ){\n\n $user = get_user_by( 'id', $request-&gt;get_param( 'id' ) );\n\n if( $user &amp;&amp; in_array( 'administrator', $user-&gt;roles ) ){\n\n $value = $request-&gt;get_param( 'my_field' );\n\n update_user_meta( $request-&gt;get_param( 'id' ), 'my_field', $value );\n\n return new WP_REST_Response( [\n 'code' =&gt; 'user_updated',\n 'message' =&gt; 'User Updated'\n ], 200 );\n\n } else {\n\n return new WP_REST_Response( [\n 'code' =&gt; 'invalid_user',\n 'message' =&gt; 'Invalid user'\n ], 404 );\n\n }\n\n}\n\nregister_rest_route( 'yoursite/v1', '/users/update_my_field/(?P&lt;id&gt;\\d+)', array(\n 'methods' =&gt; WP_REST_Server::EDITABLE,\n 'callback' =&gt; 'yoursite_update_user',\n 'permission_callback' =&gt; function () {\n return current_user_can( 'edit_users' );\n },\n 'args' =&gt; array(\n 'id' =&gt; array(\n 'validate_callback' =&gt; function ( $param, $request, $key ) {\n return is_numeric( $param );\n }\n ),\n ),\n) );\n</code></pre>\n\n<p>The above route would be triggered by an authenticated <code>POST</code> request to: <code>http:://yoursite.com/wp-json/yoursite/v1/users/update_my_field/{USER_ID}</code> with a post field of <code>my_field</code></p>\n" }, { "answer_id": 259700, "author": "Michele Fortunato", "author_id": 109855, "author_profile": "https://wordpress.stackexchange.com/users/109855", "pm_score": 3, "selected": true, "text": "<p>I found a better workaround using the same filter suggested by @ben-casey in <a href=\"https://wordpress.stackexchange.com/a/259592/109855\">his answer</a>.</p>\n\n<p>Firstly I registered throuhg <code>register_rest_field</code> all the custom fields of all the user types I have in the database.</p>\n\n<p>Then in <code>rest_prepare_user</code>, insted adding the wanted fields, I removed the unwanted ones. In this way I can still use the same endpoint to update the field.</p>\n\n<p>Below an example of the JSON clean up.</p>\n\n<pre><code>function my_rest_prepare_user( WP_REST_Response $response, WP_User $user, WP_REST_Request $request ){\n\n if( in_array( 'administrator', $user-&gt;roles ) ){\n\n $data = $response-&gt;get_data();\n\n unset($data['custom_field']);\n\n $response-&gt;set_data( $data );\n\n }\n\n return $response;\n\n}\nadd_filter( 'rest_prepare_user', 'my_rest_prepare_user', 10, 3 );\n</code></pre>\n" } ]
2017/03/10
[ "https://wordpress.stackexchange.com/questions/259586", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109855/" ]
I'm extending Wordpress REST API with a custom plugin, and I'm in the need of adding a new field to the user response. The problem is that this field has to appear only in base of the user role. For example I want a field `custom_field` appear in the response only if the user is `administrator` and not `contributor`. At the moment I'm using the `register_rest_field()` function, but it allows me to chose only the type of object. Do you know if there is a workaround to this issue? Or do you know better ways to reach the same result? P.S. I'm using WP 4.7.3
I found a better workaround using the same filter suggested by @ben-casey in [his answer](https://wordpress.stackexchange.com/a/259592/109855). Firstly I registered throuhg `register_rest_field` all the custom fields of all the user types I have in the database. Then in `rest_prepare_user`, insted adding the wanted fields, I removed the unwanted ones. In this way I can still use the same endpoint to update the field. Below an example of the JSON clean up. ``` function my_rest_prepare_user( WP_REST_Response $response, WP_User $user, WP_REST_Request $request ){ if( in_array( 'administrator', $user->roles ) ){ $data = $response->get_data(); unset($data['custom_field']); $response->set_data( $data ); } return $response; } add_filter( 'rest_prepare_user', 'my_rest_prepare_user', 10, 3 ); ```
259,600
<p>I am building a wordpress theme, I reach the step of finalization.</p> <p>Right now, I am struggling to fix an error raised by Theme Check, :</p> <blockquote> <p>file_get_contents was found in the file functions.php File operations should use the WP_Filesystem methods instead of direct PHP filesystem calls.</p> </blockquote> <p>Here the code:</p> <pre><code>function theme_critical() { $critical_css = file_get_contents( get_template_directory() . '/css/critical.css'); echo '&lt;style&gt;' . $critical_css . '&lt;/style&gt;'; } </code></pre> <p>Basicaly, this code take the content of a CSS file, to print it in the header. This is a critical css.</p> <p>I searched, but I could not find a way to use WP_filesystem to simply to the same thing than file_get_content does.</p> <p>Is anyone already faced this issue?</p> <p>Thanks.</p>
[ { "answer_id": 259625, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 0, "selected": false, "text": "<p>You shouldn't be echoing your CSS styles in the <code>&lt;head&gt;</code>. You should be using <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_style()</code></a></p>\n\n<p>Add something like this to your <code>functions.php</code> file:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_259600_enqueue_scripts' );\nfunction wpse_259600_enqueue_scripts() {\n wp_enqueue_style( 'mytheme-critical', get_template_directory_uri() . '/css/critical.css' );\n}\n</code></pre>\n" }, { "answer_id": 259778, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": true, "text": "<h1>To Add External Atylesheet:</h1>\n<p>Generally speaking, you should use the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_style()</code></a> function to add external stylesheet to your theme.</p>\n<pre><code>function wpse259600_add_style() {\n wp_enqueue_style( 'theme_critical', get_template_directory_uri() . '/css/critical.css', array(), '1.0.0' );\n}\nadd_action( 'wp_enqueue_scripts', 'wpse259600_add_style' );\n</code></pre>\n<hr>\n<h1>To Add Internal Stylesheet:</h1>\n<p>However, if (for whatever reason) you have to add internal stylesheet (i.e. printing the entire CSS file within the HTML <code>&lt;head&gt;</code> tag using the <code>&lt;style&gt;</code> tag), then you may use <code>inclue_once</code> like below:</p>\n<pre><code>add_action( 'wp_head', 'wpse259600_internal_css_print' );\nfunction wpse259600_internal_css_print() {\n echo '&lt;style type=&quot;text/css&quot;&gt;';\n // this will also allow you to use PHP to create dynamic css rules\n include_once get_template_directory() . '/css/critical.css';\n echo '&lt;/style&gt;';\n}\n</code></pre>\n<p>This will not generate warning in <a href=\"https://wordpress.org/plugins/theme-check/\" rel=\"nofollow noreferrer\"><code>theme check</code></a>. Although, I wouldn't recommend this. If you want to add custom CSS this way, you better save it to the database with customizer theme options and then add it with <code>wp_add_inline_style</code> function along with your theme's main CSS file.</p>\n" } ]
2017/03/10
[ "https://wordpress.stackexchange.com/questions/259600", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104277/" ]
I am building a wordpress theme, I reach the step of finalization. Right now, I am struggling to fix an error raised by Theme Check, : > > file\_get\_contents was found in the file functions.php File operations > should use the WP\_Filesystem methods instead of direct PHP filesystem > calls. > > > Here the code: ``` function theme_critical() { $critical_css = file_get_contents( get_template_directory() . '/css/critical.css'); echo '<style>' . $critical_css . '</style>'; } ``` Basicaly, this code take the content of a CSS file, to print it in the header. This is a critical css. I searched, but I could not find a way to use WP\_filesystem to simply to the same thing than file\_get\_content does. Is anyone already faced this issue? Thanks.
To Add External Atylesheet: =========================== Generally speaking, you should use the [`wp_enqueue_style()`](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) function to add external stylesheet to your theme. ``` function wpse259600_add_style() { wp_enqueue_style( 'theme_critical', get_template_directory_uri() . '/css/critical.css', array(), '1.0.0' ); } add_action( 'wp_enqueue_scripts', 'wpse259600_add_style' ); ``` --- To Add Internal Stylesheet: =========================== However, if (for whatever reason) you have to add internal stylesheet (i.e. printing the entire CSS file within the HTML `<head>` tag using the `<style>` tag), then you may use `inclue_once` like below: ``` add_action( 'wp_head', 'wpse259600_internal_css_print' ); function wpse259600_internal_css_print() { echo '<style type="text/css">'; // this will also allow you to use PHP to create dynamic css rules include_once get_template_directory() . '/css/critical.css'; echo '</style>'; } ``` This will not generate warning in [`theme check`](https://wordpress.org/plugins/theme-check/). Although, I wouldn't recommend this. If you want to add custom CSS this way, you better save it to the database with customizer theme options and then add it with `wp_add_inline_style` function along with your theme's main CSS file.
259,624
<p>I currently have:</p> <blockquote> <p>mywebsite.com/custom-post-type-1/postname</p> <p>mywebsite.com/custom-post-type-2/postname</p> </blockquote> <p>I want to achieve:</p> <blockquote> <p>mywebsite.com/my-base-slug/custom-post-type-1/postname</p> <p>mywebsite.com/my-base-slug/custom-post-type-2/postname</p> </blockquote> <p>I do not want <code>"my-base-slug"</code> to appear for anything other than those specified post-types.</p> <p>Is that possible and how?</p>
[ { "answer_id": 259629, "author": "geraldo", "author_id": 38096, "author_profile": "https://wordpress.stackexchange.com/users/38096", "pm_score": 0, "selected": false, "text": "<p>If you are fine with using a plugin, just have a look at <a href=\"https://wordpress.org/plugins/custom-post-type-permalinks/\" rel=\"nofollow noreferrer\">Custom Post Type Permalinks</a> or <a href=\"https://wordpress.org/plugins/permalinks-customizer/\" rel=\"nofollow noreferrer\">Permalinks Customizer</a>.</p>\n" }, { "answer_id": 259648, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You can achieve this with the <code>slug</code> argument when you <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">register your post type</a>.</p>\n\n<pre><code>$args = array(\n 'rewrite' =&gt; array( 'slug' =&gt; 'my-base-slug/custom-post-type-1' ),\n // your other args...\n);\nregister_post_type( 'mycpt', $args );\n</code></pre>\n" } ]
2017/03/10
[ "https://wordpress.stackexchange.com/questions/259624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115167/" ]
I currently have: > > mywebsite.com/custom-post-type-1/postname > > > mywebsite.com/custom-post-type-2/postname > > > I want to achieve: > > mywebsite.com/my-base-slug/custom-post-type-1/postname > > > mywebsite.com/my-base-slug/custom-post-type-2/postname > > > I do not want `"my-base-slug"` to appear for anything other than those specified post-types. Is that possible and how?
You can achieve this with the `slug` argument when you [register your post type](https://codex.wordpress.org/Function_Reference/register_post_type). ``` $args = array( 'rewrite' => array( 'slug' => 'my-base-slug/custom-post-type-1' ), // your other args... ); register_post_type( 'mycpt', $args ); ```
259,639
<p>I mention "full website" because I don't need the number of attachments on one post (as answered in many questions). I basically need a function that returns the number of uploaded images (attached and unattached) on the website, excluding non-image files.</p> <p>I've done some research, but there isn’t any direct function that counts only the images. What is the most simple way to do this? </p>
[ { "answer_id": 259642, "author": "Paul 'Sparrow Hawk' Biron", "author_id": 113496, "author_profile": "https://wordpress.stackexchange.com/users/113496", "pm_score": 2, "selected": false, "text": "<p>The simplest way I know is:</p>\n\n<pre><code>global $wpdb ;\n\n$sql = \"SELECT COUNT(*) FROM $wpdb-&gt;posts WHERE post_type = 'attachment'\" ;\n\n$count = (int) $wpdb-&gt;get_var ($sql) ;\n</code></pre>\n\n<p>You could also use WP_Query, altho doing so is more expensive:</p>\n\n<pre><code>$args = array (\n 'post_type' =&gt; 'attachment',\n 'post_status' =&gt; 'inherit',\n 'posts_per_page' =&gt; 0,\n ) ;\n$attatchments = new WP_Query ($args) ;\n\n$count = $attatchments-&gt;found_posts ;\n</code></pre>\n\n<p><strong>note:</strong> setting <code>'posts_per_page' =&gt; 0</code> and reading <code>found_posts</code> is an optimization when using WP_Query in cases like this that I just learned from the answer to another question here on WPSE a few days ago...I don't remember which question it was, otherwise I'd credit the author for the tip.</p>\n" }, { "answer_id": 259644, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>There's a handy <a href=\"https://developer.wordpress.org/reference/functions/wp_count_attachments/\" rel=\"noreferrer\">built-in function</a>, namely <code>wp_count_attachments()</code>.</p>\n\n<p>We can filter out images with <code>wp_count_attachments( $mime_type = 'image' )</code> that returns an object like:</p>\n\n<pre><code>stdClass Object\n(\n [image/gif] =&gt; 9\n [image/jpeg] =&gt; 121\n [image/png] =&gt; 20\n [image/x-icon] =&gt; 6\n [trash] =&gt; 0\n)\n</code></pre>\n\n<p>So we can use the one-liner:</p>\n\n<pre><code>$count = array_sum( (array) wp_count_attachments( $mime_type = 'image' ) );\n</code></pre>\n\n<p>for the total number of images.</p>\n" } ]
2017/03/10
[ "https://wordpress.stackexchange.com/questions/259639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115176/" ]
I mention "full website" because I don't need the number of attachments on one post (as answered in many questions). I basically need a function that returns the number of uploaded images (attached and unattached) on the website, excluding non-image files. I've done some research, but there isn’t any direct function that counts only the images. What is the most simple way to do this?
There's a handy [built-in function](https://developer.wordpress.org/reference/functions/wp_count_attachments/), namely `wp_count_attachments()`. We can filter out images with `wp_count_attachments( $mime_type = 'image' )` that returns an object like: ``` stdClass Object ( [image/gif] => 9 [image/jpeg] => 121 [image/png] => 20 [image/x-icon] => 6 [trash] => 0 ) ``` So we can use the one-liner: ``` $count = array_sum( (array) wp_count_attachments( $mime_type = 'image' ) ); ``` for the total number of images.
259,647
<p>I would like to disable the "+Add Category Button" under the Category metabox so that anyone creating a post has to choose only from the list of existing categories.</p> <ol> <li><p>I did check out another post, which literally has the same question, <a href="https://wordpress.stackexchange.com/questions/29140/how-to-remove-the-add-new-category-link-from-a-category-metabox">How To Remove The &quot;+ Add New Category&quot; Link From A Category Metabox</a> But the accepted answer doesn't make sense because he references Line 345-367, which are not relevant lines (maybe because of WP updates, things might have changed). So I am confused.</p></li> <li><p>I installed the 'User Role Editor' plugin and removed the 'manage_categories' capability for the 'Editor' which worked. But I would like to remove it for ALL users including admin, superadmin. So I tried changing the theme's functions.php as:</p> <pre><code>add_action( 'add_meta_boxes', 'isa_remove_categories_meta_box' ) function isa_remove_categories_meta_box() { remove_meta_box( 'categorydiv', 'post', 'side' );// remove the Categories box } </code></pre> <p>But, this makes the entire Category box disappear. Is there anything I can use to replace the 'categorydiv' to make only the '+Add New Category' disappear?</p></li> </ol> <p>Or, can someone point me out to what the accepted answer from the other post meant by lines 345-367? I can try that as well. </p>
[ { "answer_id": 259654, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 2, "selected": true, "text": "<blockquote>\n <p>I installed the 'User Role Editor' plugin and removed the 'manage_categories' capability for the 'Editor' which worked. But I would like to remove it for ALL users including admin, superadmin.</p>\n</blockquote>\n\n<p>If removing the 'manage_categories' capability from the editor role provides the functionality you want, then you can remove the 'manage_categories' capability from all user roles fairly easily either by using an existing plugin, or writing a new plugin that upon activation removes the capability from all the user roles. Here's the code that would be necessary to remove the capability from each role (actually, it explicitly sets the capability to false).</p>\n\n<pre><code>register_activation_hook( __FILE__, 'wpse_259647_remove_manage_categories_cap' );\nfunction wpse_259647_remove_manage_categories_cap() {\n $roles = wp_roles();\n foreach( $roles-&gt;role_names as $slug =&gt; $name ) {\n $role = get_role( $slug );\n $role-&gt;add_cap( 'manage_categories', false );\n }\n}\n</code></pre>\n\n<p>This won't remove the capability from \"super admins\" though since \"super admins\" technically aren't a role or a capability. </p>\n\n<p>If you want to explicitly revoke the manage_categories capability from all users, you could do that too.</p>\n\n<pre><code>register_activation_hook( __FILE__, 'wpse_259647_remove_manage_categories_cap' );\nfunction wpse_259647_remove_manage_categories_cap() {\n $users = get_users();\n foreach( $users as $user ) {\n $user-&gt;add_cap( 'manage_categories', false );\n }\n}\n</code></pre>\n\n<p>This may still not remove the capability from \"super admins\" though, because WordPress treats them differently than other users.</p>\n" }, { "answer_id": 344609, "author": "CDToad", "author_id": 82430, "author_profile": "https://wordpress.stackexchange.com/users/82430", "pm_score": 2, "selected": false, "text": "<p>If you are building your own taxonomy you can set the capabilities when registering the taxonomy. For example... </p>\n\n<pre><code>&lt;?php\n register_taxonomy(\n 'members_tax',\n 'post',\n array(\n 'label' =&gt; __( 'Members' ),\n 'hierarchical' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'members-tax' ),\n 'capabilities' =&gt; array(\n 'assign_terms' =&gt; 'manage_options',\n 'edit_terms' =&gt; 'god',\n 'manage_terms' =&gt; 'god',\n ),\n 'show_in_nav_menus' =&gt; false,\n )\n );\n</code></pre>\n\n<p>If you want only the administrator to be able to add or edit change god to administrator. It removes the \"Add New Members Category\" from the metabox on new posts page and removes the link on the menu bar under posts. </p>\n\n<p>This comes from this gist \n<a href=\"https://gist.github.com/ChrisFlannagan/4cd3bfd0e853cda3d3f7898c59428ac2\" rel=\"nofollow noreferrer\">https://gist.github.com/ChrisFlannagan/4cd3bfd0e853cda3d3f7898c59428ac2</a></p>\n" }, { "answer_id": 377731, "author": "Msea", "author_id": 190987, "author_profile": "https://wordpress.stackexchange.com/users/190987", "pm_score": 0, "selected": false, "text": "<p>The Category's metabox is set when the category is registered with <a href=\"https://developer.wordpress.org/reference/functions/register_taxonomy/\" rel=\"nofollow noreferrer\">register_taxonomy</a> function. The default behavior of this function is to set the metabox callback (meta_box_cb) to a wordpress function called <a href=\"https://developer.wordpress.org/reference/functions/post_categories_meta_box/\" rel=\"nofollow noreferrer\">post_categories_meta_box</a>. It is this function that renders the &quot;+Add Category&quot; Button. Unfortunately, this metabox does not allow you to selectively hide this button. As other answerers pointed out, it will hide that button based on the taxonomy's edit_terms capability, so you can effectively hide it by limiting who has this capability. However, this does not work if, like me, you want to hide this button without limiting capabilities.</p>\n<p>To do this you need to supply your own meta_box_cb. I did this by simply copying post_categories_meta_box and deleting that button.</p>\n<p><strong>My custom function:</strong></p>\n<pre><code>function custom_post_categories_meta_box_without_add_new( $post, $box ) {\n $defaults = array( 'taxonomy' =&gt; 'category' );\n if ( ! isset( $box['args'] ) || ! is_array( $box['args'] ) ) {\n $args = array();\n } else {\n $args = $box['args'];\n }\n $parsed_args = wp_parse_args( $args, $defaults );\n $tax_name = esc_attr( $parsed_args['taxonomy'] );\n $taxonomy = get_taxonomy( $parsed_args['taxonomy'] );\n ?&gt;\n &lt;div id=&quot;taxonomy-&lt;?php echo $tax_name; ?&gt;&quot; class=&quot;categorydiv&quot;&gt;\n &lt;ul id=&quot;&lt;?php echo $tax_name; ?&gt;-tabs&quot; class=&quot;category-tabs&quot;&gt;\n &lt;li class=&quot;tabs&quot;&gt;&lt;a href=&quot;#&lt;?php echo $tax_name; ?&gt;-all&quot;&gt;&lt;?php echo $taxonomy-&gt;labels-&gt;all_items; ?&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;li class=&quot;hide-if-no-js&quot;&gt;&lt;a href=&quot;#&lt;?php echo $tax_name; ?&gt;-pop&quot;&gt;&lt;?php echo esc_html( $taxonomy-&gt;labels-&gt;most_used ); ?&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n \n &lt;div id=&quot;&lt;?php echo $tax_name; ?&gt;-pop&quot; class=&quot;tabs-panel&quot; style=&quot;display: none;&quot;&gt;\n &lt;ul id=&quot;&lt;?php echo $tax_name; ?&gt;checklist-pop&quot; class=&quot;categorychecklist form-no-clear&quot; &gt;\n &lt;?php $popular_ids = wp_popular_terms_checklist( $tax_name ); ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n \n &lt;div id=&quot;&lt;?php echo $tax_name; ?&gt;-all&quot; class=&quot;tabs-panel&quot;&gt;\n &lt;?php\n $name = ( 'category' === $tax_name ) ? 'post_category' : 'tax_input[' . $tax_name . ']';\n // Allows for an empty term set to be sent. 0 is an invalid term ID and will be ignored by empty() checks.\n echo &quot;&lt;input type='hidden' name='{$name}[]' value='0' /&gt;&quot;;\n ?&gt;\n &lt;ul id=&quot;&lt;?php echo $tax_name; ?&gt;checklist&quot; data-wp-lists=&quot;list:&lt;?php echo $tax_name; ?&gt;&quot; class=&quot;categorychecklist form-no-clear&quot;&gt;\n &lt;?php\n wp_terms_checklist(\n $post-&gt;ID,\n array(\n 'taxonomy' =&gt; $tax_name,\n 'popular_cats' =&gt; $popular_ids,\n )\n );\n ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php\n}\n</code></pre>\n<p>(I hope I can include here my custom function which as I mentioned is largely copied from wordpress. If there are legal reasons I cannot do this, please let me know.)</p>\n<p><strong>Applied to my custom taxonomy</strong></p>\n<pre><code>register_taxonomy(\n &quot;my_custom_taxonomy&quot;,\n &quot;my_custom_type&quot;,\n array(\n ...\n 'hierarchical' =&gt; true,\n 'meta_box_cb' =&gt; 'custom_post_categories_meta_box_without_add_new'\n )\n);\n</code></pre>\n<p>The downside of this is that, unlike the default, your meta_box_cb will not change if wordpress updates their styling.</p>\n<p>Note that this only works if you are registering your taxonomies manually. If you are using a plugin, it may not allow you to configure the meta_box_cb.</p>\n" } ]
2017/03/10
[ "https://wordpress.stackexchange.com/questions/259647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111154/" ]
I would like to disable the "+Add Category Button" under the Category metabox so that anyone creating a post has to choose only from the list of existing categories. 1. I did check out another post, which literally has the same question, [How To Remove The "+ Add New Category" Link From A Category Metabox](https://wordpress.stackexchange.com/questions/29140/how-to-remove-the-add-new-category-link-from-a-category-metabox) But the accepted answer doesn't make sense because he references Line 345-367, which are not relevant lines (maybe because of WP updates, things might have changed). So I am confused. 2. I installed the 'User Role Editor' plugin and removed the 'manage\_categories' capability for the 'Editor' which worked. But I would like to remove it for ALL users including admin, superadmin. So I tried changing the theme's functions.php as: ``` add_action( 'add_meta_boxes', 'isa_remove_categories_meta_box' ) function isa_remove_categories_meta_box() { remove_meta_box( 'categorydiv', 'post', 'side' );// remove the Categories box } ``` But, this makes the entire Category box disappear. Is there anything I can use to replace the 'categorydiv' to make only the '+Add New Category' disappear? Or, can someone point me out to what the accepted answer from the other post meant by lines 345-367? I can try that as well.
> > I installed the 'User Role Editor' plugin and removed the 'manage\_categories' capability for the 'Editor' which worked. But I would like to remove it for ALL users including admin, superadmin. > > > If removing the 'manage\_categories' capability from the editor role provides the functionality you want, then you can remove the 'manage\_categories' capability from all user roles fairly easily either by using an existing plugin, or writing a new plugin that upon activation removes the capability from all the user roles. Here's the code that would be necessary to remove the capability from each role (actually, it explicitly sets the capability to false). ``` register_activation_hook( __FILE__, 'wpse_259647_remove_manage_categories_cap' ); function wpse_259647_remove_manage_categories_cap() { $roles = wp_roles(); foreach( $roles->role_names as $slug => $name ) { $role = get_role( $slug ); $role->add_cap( 'manage_categories', false ); } } ``` This won't remove the capability from "super admins" though since "super admins" technically aren't a role or a capability. If you want to explicitly revoke the manage\_categories capability from all users, you could do that too. ``` register_activation_hook( __FILE__, 'wpse_259647_remove_manage_categories_cap' ); function wpse_259647_remove_manage_categories_cap() { $users = get_users(); foreach( $users as $user ) { $user->add_cap( 'manage_categories', false ); } } ``` This may still not remove the capability from "super admins" though, because WordPress treats them differently than other users.