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
189,417
<p>I want to publish a facebook post the moment I publish a new blog on my website.Please help me to get this done.</p>
[ { "answer_id": 189394, "author": "Gixty", "author_id": 14128, "author_profile": "https://wordpress.stackexchange.com/users/14128", "pm_score": 0, "selected": false, "text": "<p>I think I just found it, please corrent me if I am wrong:</p>\n\n<pre><code>$args = array(\n 'status' =&gt; 'approve', \n 'number' =&gt; '5',\n 'post_id' =&gt; 73871,\n 'parent' =&gt; 123\n\n);\n$comments = get_comments($args);\n</code></pre>\n\n<p><strong>EDIT:</strong> not quite, it seems it returns the first reply only. The rest are missing.</p>\n" }, { "answer_id": 261835, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": 0, "selected": false, "text": "<p>You're correct so far but incomplete.</p>\n\n<p>You need a foreach loop after your code. So it will be like:</p>\n\n<pre><code>$args = array(\n 'status' =&gt; 'approve', \n 'number' =&gt; '5',\n 'post_id' =&gt; 73871,\n 'parent' =&gt; 123\n);\n\n$comments = get_comments($args);\n\nforeach ($comments as $comment) {\n echo $comment-&gt;comment_content; // echo all the other fields you need\n}\n</code></pre>\n" }, { "answer_id": 261836, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": 1, "selected": false, "text": "<p>As <code>comment_ID</code> is a unique value, there is no need to include the <code>post_id</code> in the arguments.</p>\n\n<p>This works fine for me:</p>\n\n<pre><code>$args = array(\n 'status' =&gt; 'approve', \n 'number' =&gt; '5',\n 'parent' =&gt; 3194\n);\n$comments = get_comments($args);\n</code></pre>\n\n<p>This will return 5 approved comments whose parent is the comment with the <code>comment_ID</code> 3194.</p>\n\n<p>Sample output could be done with something like this:</p>\n\n<pre><code>foreach($comments as $child_comment) {\n echo $child_comment-&gt;comment_ID; \n}\n</code></pre>\n" }, { "answer_id": 269718, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>In your <code>foreach</code> loop, you need to search for each comment if it has any replies submitted.</p>\n\n<p><code>$replies = get_comments( array( 'parent' =&gt; $comment-&gt;comment_ID, 'status' =&gt; 'approve', 'order' =&gt; 'ASC' ) );</code></p>\n\n<p>please have a look at this plugin <a href=\"https://github.com/mukto90/comment-search/blob/master/cb-comment-search.php\" rel=\"nofollow noreferrer\">https://github.com/mukto90/comment-search/blob/master/cb-comment-search.php</a></p>\n\n<p>it'll help you search by a comment id and show all of its replies (and maybe their replies too).</p>\n" } ]
2015/05/26
[ "https://wordpress.stackexchange.com/questions/189417", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60922/" ]
I want to publish a facebook post the moment I publish a new blog on my website.Please help me to get this done.
As `comment_ID` is a unique value, there is no need to include the `post_id` in the arguments. This works fine for me: ``` $args = array( 'status' => 'approve', 'number' => '5', 'parent' => 3194 ); $comments = get_comments($args); ``` This will return 5 approved comments whose parent is the comment with the `comment_ID` 3194. Sample output could be done with something like this: ``` foreach($comments as $child_comment) { echo $child_comment->comment_ID; } ```
189,426
<p>Is it possible to add a sidebar to navigation menu? </p> <p>I'd like to be able to add sidebars in Appearance > Menus, like I add pages.</p> <p>I have a way of creating extra sidebars, so that's not an issue (I could also just register several dedicated sidebars if need be).</p> <p>Basically I need a way to display widgets in menu, without using any extra plugins.</p> <p>Is something like that possible? Do I need to extend <code>Walker_Nav_Menu</code>?</p> <p><strong>EDIT</strong></p> <p>My menu_walker.php looks like this:</p> <p> <pre><code>// Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); function my_plugin_wp_setup_nav_menu_item( $menu_item ) { if ( isset( $menu_item-&gt;post_type ) &amp;&amp; 'nav_menu_item' == $menu_item-&gt;post_type) { $menu_item-&gt;description = apply_filters( 'nav_menu_description', $menu_item-&gt;post_content ); } return $menu_item; } add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' ); // Menu without icons class theme_walker_nav_menu extends Walker_Nav_Menu { public function display_element($el, &amp;$children, $max_depth, $depth = 0, $args, &amp;$output){ $id = $this-&gt;db_fields['id']; if(isset($children[$el-&gt;$id])){ $el-&gt;classes[] = 'has_children'; } parent::display_element($el, $children, $max_depth, $depth, $args, $output); } // add classes to ul sub-menus function start_lvl( &amp;$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth &gt; 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'navi', ( $display_depth ==1 ? 'first' : '' ), ( $display_depth &gt;=2 ? 'navi' : '' ), 'menu-depth-' . $display_depth ); $class_names = implode( ' ', $classes ); // build html $output .= "\n" . $indent . '&lt;ul class="' . esc_attr($class_names) . '"&gt;' . "\n"; } // add main/sub classes to li's and links function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth &gt; 0 ? str_repeat( "\t", $depth ) : '' ); // code indent static $is_first; $is_first++; // depth dependent classes $depth_classes = array( ( $depth == 0 ? 'main-menu-item' : '' ), ( $depth &gt;=2 ? 'navi' : '' ), ( $is_first ==1 ? 'menu-first' : '' ), 'menu-item-depth-' . $depth ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // passed classes $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $use_desc = (strpos($class_names,'use_desc') !== false) ? true : false; $no_title = (strpos($class_names,'no_title') !== false) ? true : false; if(!$is_mega_menu){ $class_names .= ' normal_menu_item'; } // build html $output .= $indent . '&lt;li id="nav-menu-item-'. esc_attr($item-&gt;ID) . '" class="' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '"&gt;'; // link attributes $attributes = ! empty( $item-&gt;attr_title ) ? ' title="' . esc_attr( $item-&gt;attr_title ) .'"' : ''; $attributes .= ! empty( $item-&gt;target ) ? ' target="' . esc_attr( $item-&gt;target ) .'"' : ''; $attributes .= ! empty( $item-&gt;xfn ) ? ' rel="' . esc_attr( $item-&gt;xfn ) .'"' : ''; $attributes .= ! empty( $item-&gt;url ) ? ' href="' . (($item-&gt;url[0] == "#" &amp;&amp; !is_front_page()) ? home_url() : '') . esc_attr($item-&gt;url) .'"' : ''; $attributes .= ' class="menu-link '.((strpos($item-&gt;url,'#') === false) ? '' : 'scroll').' ' . ( $depth &gt; 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"'; $html_output = ($use_desc) ? '&lt;div class="description_menu_item"&gt;'.wp_kses($item-&gt;description, allowed_tags()).'&lt;/div&gt;' : ''; $item_output = (!$no_title) ? '&lt;a ' . $attributes . '&gt;&lt;span&gt;' . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . '&lt;/span&gt;&lt;/a&gt;'.$html_output : $html_output; // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'&lt;div class="sf-mega"&gt;&lt;div class="sf-mega-inner clearfix"&gt;':''); } function end_el( &amp;$output, $item, $depth = 0, $args = array() ) { $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $output .= (($is_mega_menu)?'&lt;/div&gt;&lt;/div&gt;':'') . "&lt;/li&gt;\n"; } } </code></pre> <p>I also have jquery code that will add the dropdown menu for choosing how many columns I have in megamenu:</p> <pre><code>jQuery(document).ready(function($) { "use strict"; var $depth_zero = $('#menu-to-edit').find('.menu-item-depth-0'); var $depth_one = $('#menu-to-edit').find('.menu-item-depth-1'); var i = 0; $depth_zero.find('.field-description').each(function(){ i++; $(this).before('&lt;p class="field-additional description-wide"&gt;&lt;label for="add_mega'+i+'"&gt;Menu Type&lt;br&gt;&lt;select id="add_mega'+i+'" class="additional_input add_mega"&gt;&lt;option value=""&gt;Default Standard Menu&lt;/option&gt;&lt;option value="mega1"&gt;Mega Menu - Single Column&lt;/option&gt;&lt;option value="mega2"&gt;Mega Menu - 2 Columns&lt;/option&gt;&lt;option value="mega3"&gt;Mega Menu - 3 Columns&lt;/option&gt;&lt;option value="mega4"&gt;Mega Menu - 4 Columns&lt;/option&gt;&lt;option value="mega5"&gt;Mega Menu - 5 Columns&lt;/option&gt;&lt;option value="mega6"&gt;Mega Menu - 6 Columns&lt;/option&gt;&lt;option value="mega7"&gt;Mega Menu - 7 Columns&lt;/option&gt;&lt;/select&gt;&lt;/p&gt;'); var classes = $(this).siblings('.field-css-classes').find('input').val(); var current_c; for (var c = 1; c &lt;= 7; c++) { current_c = 'mega'+c; if(classes.indexOf(current_c) &gt;= 0) { $(this).siblings('.field-additional').find('select').val(current_c); } } }); $depth_one.find('.field-description').each(function(){ i++; var use_desc_state = ($(this).siblings('.field-css-classes').find('input').val().indexOf('use_desc') &gt;= 0) ? ' checked' : ''; var no_title_state = ($(this).siblings('.field-css-classes').find('input').val().indexOf('no_title') &gt;= 0) ? ' checked' : ''; $(this).before('&lt;p class="field-additional description-wide"&gt;&lt;br&gt;&lt;label for="use_desc'+i+'"&gt;&lt;input type="checkbox" id="use_desc'+i+'" class="additional_input use_desc" value="use_desc"'+use_desc_state+'&gt;Use description field as HTML content&lt;br&gt;&lt;/label&gt;&lt;label for="no_title'+i+'"&gt;&lt;input type="checkbox" id="no_title'+i+'" class="additional_input no_title" value="no_title"'+no_title_state+'&gt;Hide title&lt;/label&gt;&lt;/p&gt;'); }); $('.additional_input, .edit-menu-item-classes').change(function() { var $parent_item = $(this).closest('.menu-item'); define_classes($parent_item); }); function define_classes($item){ var $class_field = $item.find('.field-css-classes input'); var current_class_value = $class_field.val().replace('use_desc','').replace('no_title','').replace('mega1','').replace('mega2','').replace('mega3','').replace('mega4','').replace('mega5','').replace('mega6','').replace('mega7','').replace(' ',' '); var new_class_value = []; new_class_value.push(current_class_value.trim()); if($item.find('.add_mega').length &gt; 0 &amp;&amp; $item.find('.add_mega').val() !== ''){ new_class_value.push($item.find('.add_mega').val()); } if($item.find('.use_desc').length &gt; 0 &amp;&amp; $item.find('.use_desc').is(':checked')){ new_class_value.push('use_desc'); } if($item.find('.no_title').length &gt; 0 &amp;&amp; $item.find('.no_title').is(':checked')){ new_class_value.push('no_title'); } $class_field.val(new_class_value.join(' ').trim()); } }); </code></pre> <p>I tried adding <a href="https://wordpress.stackexchange.com/questions/150010/mega-menu-walker">this code</a> to extend my memgamenu, but nothing happens. </p> <p>If I can't show sidebars here, would it be possible to just add shortcodes in my description field? How would I do this? </p> <p>When I put the shortcode in the description field, nothing happens. Any help is appereciated.</p> <p><strong>EDIT</strong></p> <p>Found a different way. I've added a metabox to Menus page that lists all my sidebars, and then I put the content of the sidebars in the descreption field (you need to disable or edit the <code>wp_kses()</code> function on the description field so that it doesn't strip everything). The function looks like this:</p> <pre><code>&lt;?php if ( !class_exists('sidebars_custom_menu')) { class sidebars_custom_menu { public function add_nav_menu_meta_boxes() { add_meta_box( 'sidebar_menu_add', esc_html__('Add Sidebar', 'theme'), array( $this, 'nav_menu_link'), 'nav-menus', 'side', 'low' ); } public function nav_menu_link() {?&gt; &lt;div id="posttype-sidebars" class="posttypediv"&gt; &lt;div id="tabs-panel-sidebars" class="tabs-panel tabs-panel-active"&gt; &lt;ul id ="sidebars-checklist" class="categorychecklist form-no-clear"&gt; &lt;?php $i = 0; ?&gt; &lt;?php foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { ?&gt; &lt;?php $i++; ob_start(); dynamic_sidebar($sidebar['id']); $sidebar_html = ob_get_contents(); ob_end_clean(); ?&gt; &lt;li&gt; &lt;label class="menu-item-title"&gt; &lt;input type="checkbox" class="menu-item-checkbox" name="menu-item[-&lt;?php echo $i; ?&gt;][menu-item-object-id]" value="&lt;?php echo $sidebar['id']; ?&gt;"&gt; &lt;?php echo ucwords( $sidebar['name'] ); ?&gt; &lt;/label&gt; &lt;input type="hidden" class="menu-item-type" name="menu-item[-&lt;?php echo $i; ?&gt;][menu-item-type]" value="custom"&gt; &lt;input type="hidden" class="menu-item-title" name="menu-item[-&lt;?php echo $i; ?&gt;][menu-item-title]" value="&lt;?php echo ucwords( $sidebar['name'] ); ?&gt;"&gt; &lt;input type="hidden" class="menu-item-url" name="menu-item[-&lt;?php echo $i; ?&gt;][menu-item-url]" value=""&gt; &lt;input type="hidden" class="menu-item-classes" name="menu-item[-&lt;?php echo $i; ?&gt;][menu-item-classes]" value="menu_sidebar use_desc"&gt; &lt;input type="hidden" class="menu-item-description" name="menu-item[-&lt;?php echo $i; ?&gt;][menu-item-description]" value="&lt;?php echo htmlentities($sidebar_html); ?&gt;"&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;p class="button-controls"&gt; &lt;span class="list-controls"&gt; &lt;a href="/wordpress/wp-admin/nav-menus.php?page-tab=all&amp;amp;selectall=1#posttype-page" class="select-all"&gt;&lt;?php esc_html_e('Select All', 'theme'); ?&gt;&lt;/a&gt; &lt;/span&gt; &lt;span class="add-to-menu"&gt; &lt;input type="submit" class="button-secondary submit-add-to-menu right" value="&lt;?php esc_html_e('Add to Menu', 'theme');?&gt;" name="add-post-type-menu-item" id="submit-posttype-sidebars"&gt; &lt;span class="spinner"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php } } } $custom_nav = new sidebars_custom_menu; add_action('admin_init', array($custom_nav, 'add_nav_menu_meta_boxes')); </code></pre> <p>Original code from <a href="http://www.johnmorrisonline.com/how-to-add-a-fully-functional-custom-meta-box-to-wordpress-navigation-menus/" rel="nofollow noreferrer">here</a></p>
[ { "answer_id": 190919, "author": "sohan", "author_id": 69017, "author_profile": "https://wordpress.stackexchange.com/users/69017", "pm_score": 1, "selected": false, "text": "<p>might it can help you for your query :</p>\n\n<blockquote>\n <p>Basically I need a way to display widgets in menu, without using any\n extra plugins.</p>\n</blockquote>\n\n<p>place the code in your theme’s <code>functions.php</code></p>\n\n<pre><code>&lt;?php\n\nregister_sidebar( array(\n 'name' =&gt; 'Page Menu',\n 'id' =&gt; 'page-menu',\n 'before_widget' =&gt; '&lt;div id=\"page-nav\"&gt;',\n 'after_widget' =&gt; '&lt;/div&gt;',\n 'before_title' =&gt; false,\n 'after_title' =&gt; false\n) );\n\nadd_filter( 'wp_page_menu', 'my_page_menu' );\n\nfunction my_page_menu( $menu ) {\n dynamic_sidebar( 'page-menu' );\n}\n\n?&gt;\n</code></pre>\n\n<p>for reference <a href=\"https://wordpress.stackexchange.com/questions/55411/placing-widget-to-menu\">Placing widget to menu</a> and</p>\n\n<p><a href=\"http://justintadlock.com/archives/2009/04/15/how-to-widgetize-your-page-menu-in-wordpress\" rel=\"nofollow noreferrer\">http://justintadlock.com/archives/2009/04/15/how-to-widgetize-your-page-menu-in-wordpress</a></p>\n" }, { "answer_id": 191350, "author": "Emin Özlem", "author_id": 74612, "author_profile": "https://wordpress.stackexchange.com/users/74612", "pm_score": -1, "selected": false, "text": "<pre><code>add_filter( 'wp_nav_menu_items', 'add_sidebar_output_to_menu998722', 10, 2 );\nfunction add_sidebar_output_to_menu998722( $items, $args ) {\n if ($args-&gt;theme_location == 'nav-location') {\n $items .= dynamic_sidebar($sidebar['id']);\n\n }\n}\n</code></pre>\n" }, { "answer_id": 191494, "author": "dingo_d", "author_id": 58895, "author_profile": "https://wordpress.stackexchange.com/users/58895", "pm_score": 2, "selected": true, "text": "<p>The solution I've wanted looks like this:</p>\n\n<pre><code>&lt;?php\n\n\n// Allow HTML descriptions in WordPress Menu\nremove_filter( 'nav_menu_description', 'strip_tags' );\n\nfunction my_plugin_wp_setup_nav_menu_item( $menu_item ) {\n if ( isset( $menu_item-&gt;post_type ) &amp;&amp; 'nav_menu_item' == $menu_item-&gt;post_type) {\n $menu_item-&gt;description = apply_filters( 'nav_menu_description', $menu_item-&gt;post_content );\n }\n\n return $menu_item;\n}\n\nadd_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' );\n\n// Menu\nclass my_theme_walker_nav_menu extends Walker_Nav_Menu {\n\n public function display_element($el, &amp;$children, $max_depth, $depth = 0, $args, &amp;$output){\n $id = $this-&gt;db_fields['id'];\n\n if(isset($children[$el-&gt;$id])){\n $el-&gt;classes[] = 'has_children';\n }\n\n parent::display_element($el, $children, $max_depth, $depth, $args, $output);\n }\n\n // add classes to ul sub-menus\n function start_lvl( &amp;$output, $depth = 0, $args = array() ) {\n // depth dependent classes\n $indent = ( $depth &gt; 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n $display_depth = ( $depth + 1); // because it counts the first submenu as 0\n $classes = array(\n 'navi',\n ( $display_depth == 1 ? 'first' : '' ),\n ( $display_depth &gt;= 2 ? 'navi' : '' ),\n 'menu-depth-' . $display_depth\n );\n $class_names = implode( ' ', $classes );\n\n // build html\n $output .= \"\\n\" . $indent . '&lt;ul class=\"' . esc_attr($class_names) . '\"&gt;' . \"\\n\";\n }\n\n // add main/sub classes to li's and links\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n global $wp_query;\n $indent = ( $depth &gt; 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n\n static $is_first;\n $is_first++;\n // depth dependent classes\n $depth_classes = array(\n ( $depth == 0 ? 'main-menu-item' : '' ),\n ( $depth &gt;= 2 ? 'navi' : '' ),\n ( $is_first == 1 ? 'menu-first' : '' ),\n 'menu-item-depth-' . $depth\n );\n $depth_class_names = esc_attr( implode( ' ', $depth_classes ) );\n // passed classes\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );\n\n $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false;\n $use_desc = (strpos($class_names,'use_desc') !== false) ? true : false;\n $is_sidebar = (strpos($class_names,'menu_sidebar') !== false) ? true : false;\n $no_title = (strpos($class_names,'no_title') !== false) ? true : false;\n\n if(!$is_mega_menu){\n $class_names .= ' normal_menu_item';\n }\n\n // build html\n $output .= $indent . '&lt;li id=\"nav-menu-item-'. esc_attr($item-&gt;ID) . '\" class=\"' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '\"&gt;';\n // link attributes\n $attributes = ! empty( $item-&gt;attr_title ) ? ' title=\"' . esc_attr( $item-&gt;attr_title ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;target ) ? ' target=\"' . esc_attr( $item-&gt;target ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;xfn ) ? ' rel=\"' . esc_attr( $item-&gt;xfn ) .'\"' : '';\n $attributes .= ! empty( $item-&gt;url ) ? ' href=\"' . (($item-&gt;url[0] == \"#\" &amp;&amp; !is_front_page()) ? home_url() : '') . esc_attr($item-&gt;url) .'\"' : '';\n\n $attributes .= ' class=\"menu-link '.((strpos($item-&gt;url,'#') === false) ? '' : 'scroll').' ' . ( $depth &gt; 0 ? 'sub-menu-link' : 'main-menu-link' ) . '\"';\n\n $html_output = ($use_desc) ? '&lt;div class=\"description_menu_item\"&gt;'.wp_kses($item-&gt;description, allowed_tags()).'&lt;/div&gt;' : '';\n\n\n\n if ($is_sidebar) {\n ob_start();\n dynamic_sidebar($item-&gt;description);\n $sidebar_html = ob_get_clean();\n\n $sidebar_output = '&lt;div class=\"sidebar_menu_item\"&gt;'.$sidebar_html.'&lt;/div&gt;';\n\n $item_output = $sidebar_output;\n\n } else{\n $item_output = (!$no_title) ? '&lt;a ' . $attributes . '&gt;&lt;span&gt;' . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . '&lt;/span&gt;&lt;/a&gt;'. $html_output : $html_output;\n }\n\n\n // build html\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'&lt;div class=\"sf-mega\"&gt;&lt;div class=\"sf-mega-inner clearfix\"&gt;':'');\n }\n\n function end_el( &amp;$output, $item, $depth = 0, $args = array() ) {\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );\n\n $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false;\n\n $output .= (($is_mega_menu)?'&lt;/div&gt;&lt;/div&gt;':'') . \"&lt;/li&gt;\\n\";\n }\n\n}\n\n//Sidebars in Menu\n\nif ( !class_exists('sidebars_custom_menu')) {\n class sidebars_custom_menu {\n public function add_nav_menu_meta_boxes() {\n add_meta_box(\n 'sidebar_menu_add',\n esc_html__('Add Sidebar', 'theme'),\n array( $this, 'nav_menu_link'),\n 'nav-menus',\n 'side',\n 'low'\n );\n }\n\n public function nav_menu_link() {?&gt;\n &lt;div id=\"posttype-sidebars\" class=\"posttypediv\"&gt;\n &lt;div id=\"tabs-panel-sidebars\" class=\"tabs-panel tabs-panel-active\"&gt;\n &lt;ul id =\"sidebars-checklist\" class=\"categorychecklist form-no-clear\"&gt;\n &lt;?php\n $i = -1;\n foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) {\n ob_start();\n dynamic_sidebar($sidebar['id']);\n $sidebar_html = ob_get_clean();\n ?&gt;\n &lt;li&gt;\n &lt;label class=\"menu-item-title\"&gt;\n &lt;input type=\"checkbox\" class=\"menu-item-checkbox\" name=\"menu-item[&lt;?php echo esc_attr($i); ?&gt;][menu-item-object-id]\" value=\"&lt;?php echo $sidebar['id']; ?&gt;\"&gt; &lt;?php echo ucwords( $sidebar['name'] ); ?&gt;\n &lt;/label&gt;\n &lt;input type=\"hidden\" class=\"menu-item-type\" name=\"menu-item[&lt;?php echo esc_attr($i); ?&gt;][menu-item-type]\" value=\"custom\"&gt;\n &lt;input type=\"hidden\" class=\"menu-item-attr-title\" name=\"menu-item[&lt;?php echo esc_attr($i); ?&gt;][menu-item-attr-title]\" value=\"&lt;?php echo ucwords( $sidebar['name'] ); ?&gt;\"&gt;\n &lt;input type=\"hidden\" class=\"menu-item-title\" name=\"menu-item[&lt;?php echo esc_attr( $i ); ?&gt;][menu-item-title]\" value=\"&amp;nbsp;\" /&gt;\n &lt;input type=\"hidden\" class=\"menu-item-url\" name=\"menu-item[&lt;?php echo esc_attr($i); ?&gt;][menu-item-url]\" value=\"\"&gt;\n &lt;input type=\"hidden\" class=\"menu-item-classes\" name=\"menu-item[&lt;?php echo esc_attr($i); ?&gt;][menu-item-classes]\" value=\"menu_sidebar\"&gt;\n &lt;input type=\"hidden\" class=\"menu-item-description\" name=\"menu-item[&lt;?php echo esc_attr($i); ?&gt;][menu-item-description]\" value=\"&lt;?php echo $sidebar['id']; ?&gt;\"&gt;\n &lt;/li&gt;\n &lt;?php\n $i --;\n }\n ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;p class=\"button-controls\"&gt;\n &lt;span class=\"list-controls\"&gt;\n &lt;a href=\"&lt;?php echo admin_url( 'nav-menus.php?page-tab=all&amp;amp;selectall=1#posttype-sidebars' ); ?&gt;\" class=\"select-all\"&gt;&lt;?php esc_html_e('Select All', 'theme'); ?&gt;&lt;/a&gt;\n &lt;/span&gt;\n &lt;span class=\"add-to-menu\"&gt;\n &lt;input type=\"submit\" class=\"button-secondary submit-add-to-menu right\" value=\"&lt;?php esc_html_e('Add to Menu', 'theme');?&gt;\" name=\"add-post-type-menu-item\" id=\"submit-posttype-sidebars\"&gt;\n &lt;span class=\"spinner\"&gt;&lt;/span&gt;\n &lt;/span&gt;\n &lt;/p&gt;\n &lt;/div&gt;\n &lt;?php }\n }\n}\n\n$custom_nav = new sidebars_custom_menu;\n\nadd_action('admin_init', array($custom_nav, 'add_nav_menu_meta_boxes'));\n</code></pre>\n\n<p>This will create a list of sidebars that you can put in the menu, and they will have a class <code>menu_sidebar</code> that you can use to style your widgets if you want.</p>\n\n<p>Hope this helps someone who wants the same.</p>\n" }, { "answer_id": 353252, "author": "aye cee", "author_id": 174773, "author_profile": "https://wordpress.stackexchange.com/users/174773", "pm_score": 1, "selected": false, "text": "<p>In response to whether it is possible to add shortcodes in the description field. This is what worked for me. Add this to functions.php and then shortcodes should work.</p>\n\n<pre><code>add_filter( 'term_description', 'do_shortcode' );\n</code></pre>\n" } ]
2015/05/26
[ "https://wordpress.stackexchange.com/questions/189426", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
Is it possible to add a sidebar to navigation menu? I'd like to be able to add sidebars in Appearance > Menus, like I add pages. I have a way of creating extra sidebars, so that's not an issue (I could also just register several dedicated sidebars if need be). Basically I need a way to display widgets in menu, without using any extra plugins. Is something like that possible? Do I need to extend `Walker_Nav_Menu`? **EDIT** My menu\_walker.php looks like this: ``` // Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); function my_plugin_wp_setup_nav_menu_item( $menu_item ) { if ( isset( $menu_item->post_type ) && 'nav_menu_item' == $menu_item->post_type) { $menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content ); } return $menu_item; } add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' ); // Menu without icons class theme_walker_nav_menu extends Walker_Nav_Menu { public function display_element($el, &$children, $max_depth, $depth = 0, $args, &$output){ $id = $this->db_fields['id']; if(isset($children[$el->$id])){ $el->classes[] = 'has_children'; } parent::display_element($el, $children, $max_depth, $depth, $args, $output); } // add classes to ul sub-menus function start_lvl( &$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'navi', ( $display_depth ==1 ? 'first' : '' ), ( $display_depth >=2 ? 'navi' : '' ), 'menu-depth-' . $display_depth ); $class_names = implode( ' ', $classes ); // build html $output .= "\n" . $indent . '<ul class="' . esc_attr($class_names) . '">' . "\n"; } // add main/sub classes to li's and links function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent static $is_first; $is_first++; // depth dependent classes $depth_classes = array( ( $depth == 0 ? 'main-menu-item' : '' ), ( $depth >=2 ? 'navi' : '' ), ( $is_first ==1 ? 'menu-first' : '' ), 'menu-item-depth-' . $depth ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // passed classes $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $use_desc = (strpos($class_names,'use_desc') !== false) ? true : false; $no_title = (strpos($class_names,'no_title') !== false) ? true : false; if(!$is_mega_menu){ $class_names .= ' normal_menu_item'; } // build html $output .= $indent . '<li id="nav-menu-item-'. esc_attr($item->ID) . '" class="' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '">'; // link attributes $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url() : '') . esc_attr($item->url) .'"' : ''; $attributes .= ' class="menu-link '.((strpos($item->url,'#') === false) ? '' : 'scroll').' ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"'; $html_output = ($use_desc) ? '<div class="description_menu_item">'.wp_kses($item->description, allowed_tags()).'</div>' : ''; $item_output = (!$no_title) ? '<a ' . $attributes . '><span>' . apply_filters( 'the_title', $item->title, $item->ID ) . '</span></a>'.$html_output : $html_output; // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'<div class="sf-mega"><div class="sf-mega-inner clearfix">':''); } function end_el( &$output, $item, $depth = 0, $args = array() ) { $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $output .= (($is_mega_menu)?'</div></div>':'') . "</li>\n"; } } ``` I also have jquery code that will add the dropdown menu for choosing how many columns I have in megamenu: ``` jQuery(document).ready(function($) { "use strict"; var $depth_zero = $('#menu-to-edit').find('.menu-item-depth-0'); var $depth_one = $('#menu-to-edit').find('.menu-item-depth-1'); var i = 0; $depth_zero.find('.field-description').each(function(){ i++; $(this).before('<p class="field-additional description-wide"><label for="add_mega'+i+'">Menu Type<br><select id="add_mega'+i+'" class="additional_input add_mega"><option value="">Default Standard Menu</option><option value="mega1">Mega Menu - Single Column</option><option value="mega2">Mega Menu - 2 Columns</option><option value="mega3">Mega Menu - 3 Columns</option><option value="mega4">Mega Menu - 4 Columns</option><option value="mega5">Mega Menu - 5 Columns</option><option value="mega6">Mega Menu - 6 Columns</option><option value="mega7">Mega Menu - 7 Columns</option></select></p>'); var classes = $(this).siblings('.field-css-classes').find('input').val(); var current_c; for (var c = 1; c <= 7; c++) { current_c = 'mega'+c; if(classes.indexOf(current_c) >= 0) { $(this).siblings('.field-additional').find('select').val(current_c); } } }); $depth_one.find('.field-description').each(function(){ i++; var use_desc_state = ($(this).siblings('.field-css-classes').find('input').val().indexOf('use_desc') >= 0) ? ' checked' : ''; var no_title_state = ($(this).siblings('.field-css-classes').find('input').val().indexOf('no_title') >= 0) ? ' checked' : ''; $(this).before('<p class="field-additional description-wide"><br><label for="use_desc'+i+'"><input type="checkbox" id="use_desc'+i+'" class="additional_input use_desc" value="use_desc"'+use_desc_state+'>Use description field as HTML content<br></label><label for="no_title'+i+'"><input type="checkbox" id="no_title'+i+'" class="additional_input no_title" value="no_title"'+no_title_state+'>Hide title</label></p>'); }); $('.additional_input, .edit-menu-item-classes').change(function() { var $parent_item = $(this).closest('.menu-item'); define_classes($parent_item); }); function define_classes($item){ var $class_field = $item.find('.field-css-classes input'); var current_class_value = $class_field.val().replace('use_desc','').replace('no_title','').replace('mega1','').replace('mega2','').replace('mega3','').replace('mega4','').replace('mega5','').replace('mega6','').replace('mega7','').replace(' ',' '); var new_class_value = []; new_class_value.push(current_class_value.trim()); if($item.find('.add_mega').length > 0 && $item.find('.add_mega').val() !== ''){ new_class_value.push($item.find('.add_mega').val()); } if($item.find('.use_desc').length > 0 && $item.find('.use_desc').is(':checked')){ new_class_value.push('use_desc'); } if($item.find('.no_title').length > 0 && $item.find('.no_title').is(':checked')){ new_class_value.push('no_title'); } $class_field.val(new_class_value.join(' ').trim()); } }); ``` I tried adding [this code](https://wordpress.stackexchange.com/questions/150010/mega-menu-walker) to extend my memgamenu, but nothing happens. If I can't show sidebars here, would it be possible to just add shortcodes in my description field? How would I do this? When I put the shortcode in the description field, nothing happens. Any help is appereciated. **EDIT** Found a different way. I've added a metabox to Menus page that lists all my sidebars, and then I put the content of the sidebars in the descreption field (you need to disable or edit the `wp_kses()` function on the description field so that it doesn't strip everything). The function looks like this: ``` <?php if ( !class_exists('sidebars_custom_menu')) { class sidebars_custom_menu { public function add_nav_menu_meta_boxes() { add_meta_box( 'sidebar_menu_add', esc_html__('Add Sidebar', 'theme'), array( $this, 'nav_menu_link'), 'nav-menus', 'side', 'low' ); } public function nav_menu_link() {?> <div id="posttype-sidebars" class="posttypediv"> <div id="tabs-panel-sidebars" class="tabs-panel tabs-panel-active"> <ul id ="sidebars-checklist" class="categorychecklist form-no-clear"> <?php $i = 0; ?> <?php foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { ?> <?php $i++; ob_start(); dynamic_sidebar($sidebar['id']); $sidebar_html = ob_get_contents(); ob_end_clean(); ?> <li> <label class="menu-item-title"> <input type="checkbox" class="menu-item-checkbox" name="menu-item[-<?php echo $i; ?>][menu-item-object-id]" value="<?php echo $sidebar['id']; ?>"> <?php echo ucwords( $sidebar['name'] ); ?> </label> <input type="hidden" class="menu-item-type" name="menu-item[-<?php echo $i; ?>][menu-item-type]" value="custom"> <input type="hidden" class="menu-item-title" name="menu-item[-<?php echo $i; ?>][menu-item-title]" value="<?php echo ucwords( $sidebar['name'] ); ?>"> <input type="hidden" class="menu-item-url" name="menu-item[-<?php echo $i; ?>][menu-item-url]" value=""> <input type="hidden" class="menu-item-classes" name="menu-item[-<?php echo $i; ?>][menu-item-classes]" value="menu_sidebar use_desc"> <input type="hidden" class="menu-item-description" name="menu-item[-<?php echo $i; ?>][menu-item-description]" value="<?php echo htmlentities($sidebar_html); ?>"> </li> <?php } ?> </ul> </div> <p class="button-controls"> <span class="list-controls"> <a href="/wordpress/wp-admin/nav-menus.php?page-tab=all&amp;selectall=1#posttype-page" class="select-all"><?php esc_html_e('Select All', 'theme'); ?></a> </span> <span class="add-to-menu"> <input type="submit" class="button-secondary submit-add-to-menu right" value="<?php esc_html_e('Add to Menu', 'theme');?>" name="add-post-type-menu-item" id="submit-posttype-sidebars"> <span class="spinner"></span> </span> </p> </div> <?php } } } $custom_nav = new sidebars_custom_menu; add_action('admin_init', array($custom_nav, 'add_nav_menu_meta_boxes')); ``` Original code from [here](http://www.johnmorrisonline.com/how-to-add-a-fully-functional-custom-meta-box-to-wordpress-navigation-menus/)
The solution I've wanted looks like this: ``` <?php // Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); function my_plugin_wp_setup_nav_menu_item( $menu_item ) { if ( isset( $menu_item->post_type ) && 'nav_menu_item' == $menu_item->post_type) { $menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content ); } return $menu_item; } add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' ); // Menu class my_theme_walker_nav_menu extends Walker_Nav_Menu { public function display_element($el, &$children, $max_depth, $depth = 0, $args, &$output){ $id = $this->db_fields['id']; if(isset($children[$el->$id])){ $el->classes[] = 'has_children'; } parent::display_element($el, $children, $max_depth, $depth, $args, $output); } // add classes to ul sub-menus function start_lvl( &$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'navi', ( $display_depth == 1 ? 'first' : '' ), ( $display_depth >= 2 ? 'navi' : '' ), 'menu-depth-' . $display_depth ); $class_names = implode( ' ', $classes ); // build html $output .= "\n" . $indent . '<ul class="' . esc_attr($class_names) . '">' . "\n"; } // add main/sub classes to li's and links function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent static $is_first; $is_first++; // depth dependent classes $depth_classes = array( ( $depth == 0 ? 'main-menu-item' : '' ), ( $depth >= 2 ? 'navi' : '' ), ( $is_first == 1 ? 'menu-first' : '' ), 'menu-item-depth-' . $depth ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // passed classes $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $use_desc = (strpos($class_names,'use_desc') !== false) ? true : false; $is_sidebar = (strpos($class_names,'menu_sidebar') !== false) ? true : false; $no_title = (strpos($class_names,'no_title') !== false) ? true : false; if(!$is_mega_menu){ $class_names .= ' normal_menu_item'; } // build html $output .= $indent . '<li id="nav-menu-item-'. esc_attr($item->ID) . '" class="' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '">'; // link attributes $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url() : '') . esc_attr($item->url) .'"' : ''; $attributes .= ' class="menu-link '.((strpos($item->url,'#') === false) ? '' : 'scroll').' ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"'; $html_output = ($use_desc) ? '<div class="description_menu_item">'.wp_kses($item->description, allowed_tags()).'</div>' : ''; if ($is_sidebar) { ob_start(); dynamic_sidebar($item->description); $sidebar_html = ob_get_clean(); $sidebar_output = '<div class="sidebar_menu_item">'.$sidebar_html.'</div>'; $item_output = $sidebar_output; } else{ $item_output = (!$no_title) ? '<a ' . $attributes . '><span>' . apply_filters( 'the_title', $item->title, $item->ID ) . '</span></a>'. $html_output : $html_output; } // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'<div class="sf-mega"><div class="sf-mega-inner clearfix">':''); } function end_el( &$output, $item, $depth = 0, $args = array() ) { $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $output .= (($is_mega_menu)?'</div></div>':'') . "</li>\n"; } } //Sidebars in Menu if ( !class_exists('sidebars_custom_menu')) { class sidebars_custom_menu { public function add_nav_menu_meta_boxes() { add_meta_box( 'sidebar_menu_add', esc_html__('Add Sidebar', 'theme'), array( $this, 'nav_menu_link'), 'nav-menus', 'side', 'low' ); } public function nav_menu_link() {?> <div id="posttype-sidebars" class="posttypediv"> <div id="tabs-panel-sidebars" class="tabs-panel tabs-panel-active"> <ul id ="sidebars-checklist" class="categorychecklist form-no-clear"> <?php $i = -1; foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { ob_start(); dynamic_sidebar($sidebar['id']); $sidebar_html = ob_get_clean(); ?> <li> <label class="menu-item-title"> <input type="checkbox" class="menu-item-checkbox" name="menu-item[<?php echo esc_attr($i); ?>][menu-item-object-id]" value="<?php echo $sidebar['id']; ?>"> <?php echo ucwords( $sidebar['name'] ); ?> </label> <input type="hidden" class="menu-item-type" name="menu-item[<?php echo esc_attr($i); ?>][menu-item-type]" value="custom"> <input type="hidden" class="menu-item-attr-title" name="menu-item[<?php echo esc_attr($i); ?>][menu-item-attr-title]" value="<?php echo ucwords( $sidebar['name'] ); ?>"> <input type="hidden" class="menu-item-title" name="menu-item[<?php echo esc_attr( $i ); ?>][menu-item-title]" value="&nbsp;" /> <input type="hidden" class="menu-item-url" name="menu-item[<?php echo esc_attr($i); ?>][menu-item-url]" value=""> <input type="hidden" class="menu-item-classes" name="menu-item[<?php echo esc_attr($i); ?>][menu-item-classes]" value="menu_sidebar"> <input type="hidden" class="menu-item-description" name="menu-item[<?php echo esc_attr($i); ?>][menu-item-description]" value="<?php echo $sidebar['id']; ?>"> </li> <?php $i --; } ?> </ul> </div> <p class="button-controls"> <span class="list-controls"> <a href="<?php echo admin_url( 'nav-menus.php?page-tab=all&amp;selectall=1#posttype-sidebars' ); ?>" class="select-all"><?php esc_html_e('Select All', 'theme'); ?></a> </span> <span class="add-to-menu"> <input type="submit" class="button-secondary submit-add-to-menu right" value="<?php esc_html_e('Add to Menu', 'theme');?>" name="add-post-type-menu-item" id="submit-posttype-sidebars"> <span class="spinner"></span> </span> </p> </div> <?php } } } $custom_nav = new sidebars_custom_menu; add_action('admin_init', array($custom_nav, 'add_nav_menu_meta_boxes')); ``` This will create a list of sidebars that you can put in the menu, and they will have a class `menu_sidebar` that you can use to style your widgets if you want. Hope this helps someone who wants the same.
189,437
<p>I have a foreach loop that prints out custom posts which uses a custom taxonomy. The user can then add whatever term/s they like to each post. This then prints out a list of terms on the custom template page; and links them all to a filter. </p> <p>My issue is that when two posts contain the same term; it outputs/prints the term out twice. How can I solve this?</p> <p>Here is a temporary example: <a href="http://website-test-lab.com/sites/zuludawn/video-archive/" rel="nofollow">http://website-test-lab.com/sites/zuludawn/video-archive/</a></p> <p>Here is my full page template code:</p> <pre><code>&lt;?php // WP_Query arguments $args = array ( 'post_type' =&gt; 'cpt-video-arc', 'posts_per_page' =&gt; '-1' ); // The Query $query = new WP_Query( $args ); ?&gt; &lt;div class="entry-content units-row group"&gt; &lt;div class="category-list category-list-video-archive"&gt; Filter by tags: &lt;button class="filter" data-filter="all"&gt;Show All&lt;/button&gt; &lt;?php $terms = array(); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); ?&gt; &lt;?php $terms_tags = wp_get_post_terms( $query-&gt;post-&gt;ID, array( 'video-arc-tags-taxonomy' ) ); ?&gt; &lt;?php foreach ( $terms_tags as $term_tag ) { ?&gt; &lt;?php $terms[$term_tag-&gt;slug] = '&lt;button class="filter" data-filter=".'.$term_tag-&gt;slug.'"&gt;'.$term_tag-&gt;name.'&lt;/button&gt;'; ?&gt; &lt;?php echo implode($terms,' '); ?&gt; &lt;?php } ?&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt;&lt;!-- .category-list --&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 189450, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 3, "selected": false, "text": "<p>What about this:</p>\n\n<pre><code>&lt;?php \n$already_used = array();\nforeach ( $terms_tags as $term_tag ) : \n if( ! in_array( $term_tag, $already_used ): ?&gt;\n &lt;button class=\"filter\" data-filter=\".&lt;?php echo $term_tag-&gt;slug; ?&gt;\"&gt;&lt;?php echo $term_tag-&gt;name; ?&gt;&lt;/button&gt;\n &lt;?php \n $already_used[] = $term_tag; \n endif;\n endforeach; \n?&gt;\n</code></pre>\n\n<p>Explanation: You create an array, where you save which terms you've already used. If the current term is in this array, it will not be printed. Otherwise it will be printed and put into the array.</p>\n\n<p>EDIT: You have to put the <code>$already_used = array();</code> before the while <code>( $query-&gt;have_posts() )</code> of course.</p>\n" }, { "answer_id": 189470, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": true, "text": "<p>I would tend to do this:</p>\n\n<pre><code>$terms = array();\n$terms_tags = wp_get_post_terms( $query-&gt;post-&gt;ID, array( 'post_tag' ) ); \nforeach ( $terms_tags as $term_tag ) {\n $terms[$term_tag-&gt;slug] = '&lt;button class=\"filter\" data-filter=\".'.$term_tag-&gt;slug.',\"&gt;'.$term_tag-&gt;name.'&lt;/button&gt;';\n}\necho implode($terms,', ');\n</code></pre>\n\n<p>It leverages the fact that PHP does not allow duplicate array keys, and thus avoids the overhead of function calls.</p>\n\n<p>In your case, it should look like this (without all of that PHP tag spam):</p>\n\n<pre><code>$query = new WP_Query( $args ); ?&gt;\n&lt;div class=\"entry-content units-row group\"&gt;\n &lt;div class=\"category-list category-list-video-archive\"&gt;\n Filter by tags:\n &lt;button class=\"filter\" data-filter=\"all\"&gt;Show All&lt;/button&gt;&lt;?php \n $terms = array(); \n while ( $query-&gt;have_posts() ) : \n $query-&gt;the_post();\n $terms_tags = wp_get_post_terms( $query-&gt;post-&gt;ID, array( 'video-arc-tags-taxonomy' ) );\n foreach ( $terms_tags as $term_tag ) { \n $terms[$term_tag-&gt;slug] = '&lt;button class=\"filter\" data-filter=\".'.$term_tag-&gt;slug.'\"&gt;'.$term_tag-&gt;name.'&lt;/button&gt;'; \n }\n endwhile; \n echo implode($terms,' '); // this goes outside the while loop ?&gt;\n &lt;/div&gt;&lt;!-- .category-list --&gt;\n&lt;/div&gt;&lt;!-- .entry-content --&gt;\n</code></pre>\n" } ]
2015/05/26
[ "https://wordpress.stackexchange.com/questions/189437", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57571/" ]
I have a foreach loop that prints out custom posts which uses a custom taxonomy. The user can then add whatever term/s they like to each post. This then prints out a list of terms on the custom template page; and links them all to a filter. My issue is that when two posts contain the same term; it outputs/prints the term out twice. How can I solve this? Here is a temporary example: <http://website-test-lab.com/sites/zuludawn/video-archive/> Here is my full page template code: ``` <?php // WP_Query arguments $args = array ( 'post_type' => 'cpt-video-arc', 'posts_per_page' => '-1' ); // The Query $query = new WP_Query( $args ); ?> <div class="entry-content units-row group"> <div class="category-list category-list-video-archive"> Filter by tags: <button class="filter" data-filter="all">Show All</button> <?php $terms = array(); ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php $terms_tags = wp_get_post_terms( $query->post->ID, array( 'video-arc-tags-taxonomy' ) ); ?> <?php foreach ( $terms_tags as $term_tag ) { ?> <?php $terms[$term_tag->slug] = '<button class="filter" data-filter=".'.$term_tag->slug.'">'.$term_tag->name.'</button>'; ?> <?php echo implode($terms,' '); ?> <?php } ?> <?php endwhile; ?> </div><!-- .category-list --> </div><!-- .entry-content --> <?php wp_reset_postdata(); ?> ```
I would tend to do this: ``` $terms = array(); $terms_tags = wp_get_post_terms( $query->post->ID, array( 'post_tag' ) ); foreach ( $terms_tags as $term_tag ) { $terms[$term_tag->slug] = '<button class="filter" data-filter=".'.$term_tag->slug.',">'.$term_tag->name.'</button>'; } echo implode($terms,', '); ``` It leverages the fact that PHP does not allow duplicate array keys, and thus avoids the overhead of function calls. In your case, it should look like this (without all of that PHP tag spam): ``` $query = new WP_Query( $args ); ?> <div class="entry-content units-row group"> <div class="category-list category-list-video-archive"> Filter by tags: <button class="filter" data-filter="all">Show All</button><?php $terms = array(); while ( $query->have_posts() ) : $query->the_post(); $terms_tags = wp_get_post_terms( $query->post->ID, array( 'video-arc-tags-taxonomy' ) ); foreach ( $terms_tags as $term_tag ) { $terms[$term_tag->slug] = '<button class="filter" data-filter=".'.$term_tag->slug.'">'.$term_tag->name.'</button>'; } endwhile; echo implode($terms,' '); // this goes outside the while loop ?> </div><!-- .category-list --> </div><!-- .entry-content --> ```
189,451
<p>I'm using some custom posts types, and, I don't wanna create specific categories for each one.</p> <p>I'd like to use the Post Category in all my Custom Post.</p> <p>Here is a example of my new custom posts type:</p> <p>I know how create new category type for my custom posts, but I don't know how use the regular categories from posts.</p> <pre><code>/* New Custom Post - Cupons /* ------------------------------------ */ add_action( 'init', 'create_post_type_cupons' ); function create_post_type_cupons() { register_post_type( 'cupom', array( 'labels' =&gt; array( 'name' =&gt; __( 'Cupons' ), 'singular_name' =&gt; __( 'Cupom' ) ), 'public' =&gt; true, ) ); } </code></pre>
[ { "answer_id": 189458, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 4, "selected": true, "text": "<p>The documentation for <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\"><code>register_post_type</code></a> mentions a <code>taxonomies</code> parameter, giving it a value of <code>array( 'category' )</code> will do what you want.</p>\n\n<p>There is also the <code>register_taxonomy_for_object_type</code> function</p>\n" }, { "answer_id": 189465, "author": "Carl Willis", "author_id": 69413, "author_profile": "https://wordpress.stackexchange.com/users/69413", "pm_score": 1, "selected": false, "text": "<p>After </p>\n\n<pre><code>'public' =&gt; true,\n</code></pre>\n\n<p>you add </p>\n\n<pre><code>'taxonomies' =&gt; array('category','post_tag'),\n</code></pre>\n\n<p>this one create category and tag for your custom post type if you want just category the delete ,'post_tag'.</p>\n" }, { "answer_id": 189473, "author": "Tiago", "author_id": 73651, "author_profile": "https://wordpress.stackexchange.com/users/73651", "pm_score": 1, "selected": false, "text": "<p>I added the function <code>register_taxonomy_for_object_type( $taxonomy, $object_type )</code> in <code>functions.php</code>.</p>\n\n<p>First: I need to choose which kind of taxonomy I want, in this case, \"category\".</p>\n\n<p>Second: I choose the object type, in this case, \"cupom\" that is my Custom Post Type.</p>\n\n<pre><code>add_action('init','add_categories_to_cupom');\nfunction add_categories_to_cupom(){\n register_taxonomy_for_object_type('category', 'cupom');\n}\n</code></pre>\n\n<p>So now, my Custom Post Type \"cupom\" uses the the Posts Category.</p>\n" } ]
2015/05/26
[ "https://wordpress.stackexchange.com/questions/189451", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73651/" ]
I'm using some custom posts types, and, I don't wanna create specific categories for each one. I'd like to use the Post Category in all my Custom Post. Here is a example of my new custom posts type: I know how create new category type for my custom posts, but I don't know how use the regular categories from posts. ``` /* New Custom Post - Cupons /* ------------------------------------ */ add_action( 'init', 'create_post_type_cupons' ); function create_post_type_cupons() { register_post_type( 'cupom', array( 'labels' => array( 'name' => __( 'Cupons' ), 'singular_name' => __( 'Cupom' ) ), 'public' => true, ) ); } ```
The documentation for [`register_post_type`](https://codex.wordpress.org/Function_Reference/register_post_type) mentions a `taxonomies` parameter, giving it a value of `array( 'category' )` will do what you want. There is also the `register_taxonomy_for_object_type` function
189,513
<p>I'm looking to register users without requiring confirmation of their emails (and even better, no password when they register). Basically, I want them to subscribe their mails using wp registration process and then redirect to a page of my choice. </p> <p>I know I can do it with CF7, or a newsletter plugin or whatever, but I actually need to use the default registration process because it connects to another plugin which uses it, and the UX flow is as follows: </p> <pre><code>user enter mails --&gt; user gets redirected to thank you page with a ref code (provided by plugin). </code></pre> <p>It's as simple as this, yet couldn't find the answer and I was searching for hours.</p> <p>Any help really appreciated!</p>
[ { "answer_id": 189458, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 4, "selected": true, "text": "<p>The documentation for <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\"><code>register_post_type</code></a> mentions a <code>taxonomies</code> parameter, giving it a value of <code>array( 'category' )</code> will do what you want.</p>\n\n<p>There is also the <code>register_taxonomy_for_object_type</code> function</p>\n" }, { "answer_id": 189465, "author": "Carl Willis", "author_id": 69413, "author_profile": "https://wordpress.stackexchange.com/users/69413", "pm_score": 1, "selected": false, "text": "<p>After </p>\n\n<pre><code>'public' =&gt; true,\n</code></pre>\n\n<p>you add </p>\n\n<pre><code>'taxonomies' =&gt; array('category','post_tag'),\n</code></pre>\n\n<p>this one create category and tag for your custom post type if you want just category the delete ,'post_tag'.</p>\n" }, { "answer_id": 189473, "author": "Tiago", "author_id": 73651, "author_profile": "https://wordpress.stackexchange.com/users/73651", "pm_score": 1, "selected": false, "text": "<p>I added the function <code>register_taxonomy_for_object_type( $taxonomy, $object_type )</code> in <code>functions.php</code>.</p>\n\n<p>First: I need to choose which kind of taxonomy I want, in this case, \"category\".</p>\n\n<p>Second: I choose the object type, in this case, \"cupom\" that is my Custom Post Type.</p>\n\n<pre><code>add_action('init','add_categories_to_cupom');\nfunction add_categories_to_cupom(){\n register_taxonomy_for_object_type('category', 'cupom');\n}\n</code></pre>\n\n<p>So now, my Custom Post Type \"cupom\" uses the the Posts Category.</p>\n" } ]
2015/05/26
[ "https://wordpress.stackexchange.com/questions/189513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73678/" ]
I'm looking to register users without requiring confirmation of their emails (and even better, no password when they register). Basically, I want them to subscribe their mails using wp registration process and then redirect to a page of my choice. I know I can do it with CF7, or a newsletter plugin or whatever, but I actually need to use the default registration process because it connects to another plugin which uses it, and the UX flow is as follows: ``` user enter mails --> user gets redirected to thank you page with a ref code (provided by plugin). ``` It's as simple as this, yet couldn't find the answer and I was searching for hours. Any help really appreciated!
The documentation for [`register_post_type`](https://codex.wordpress.org/Function_Reference/register_post_type) mentions a `taxonomies` parameter, giving it a value of `array( 'category' )` will do what you want. There is also the `register_taxonomy_for_object_type` function
189,543
<p>So, I have following <code>php</code> code:</p> <pre><code>&lt;?php global $my_profile; ?&gt; &lt;?php if (is_user_logged_in()) : ?&gt; &lt;div class="img" data-key="profile"&gt;&lt;?php echo get_avatar( get_current_user_id(), 64 ); ?&gt;&lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>It pulls the profile picture of currently logged in user. I am trying to add this to one of the menu item title, so that user profile picture is shown as a part of the menu.</p> <p>It looks like I cannot directly add this code into <code>menu</code>.</p> <p>What would be the best way to add this into one of the menu title?</p> <p>Thanks.</p> <p>Steve</p>
[ { "answer_id": 189562, "author": "mishu", "author_id": 64607, "author_profile": "https://wordpress.stackexchange.com/users/64607", "pm_score": 1, "selected": false, "text": "<p>You can try this out :</p>\n\n<blockquote>\n<pre><code>&lt;?php global $my_profile; ?&gt;\n&lt;?php if (is_user_logged_in()){\n $avatar = '&lt;div class=\"img\" data-key=\"profile\"&gt;'.get_avatar( get_current_user_id(), 64 ).'&lt;/div&gt;';\n}else{\n $avatar = ''; \n} ?&gt;\n</code></pre>\n</blockquote>\n\n<p>And your menu code should be like this</p>\n\n<pre><code>$defaults = array(\n 'theme_location' =&gt; 'location of menu in your theme',\n 'menu' =&gt; 'slug',\n 'container' =&gt; 'div',\n 'menu_class' =&gt; 'menu',\n 'echo' =&gt; true,\n 'fallback_cb' =&gt; 'wp_page_menu',\n 'items_wrap' =&gt; $avatar.'&lt;ul id=\"%1$s\" class=\"%2$s\"&gt;%3$s&lt;/ul&gt;',\n);\n\nwp_nav_menu( $defaults );\n</code></pre>\n\n<p>Fill all the parameters as per your requirement.\nFor full list of parameter check this page <a href=\"https://codex.wordpress.org/Function_Reference/wp_nav_menu\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_nav_menu</a></p>\n" }, { "answer_id": 189576, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 3, "selected": true, "text": "<p>Add to your functions file and use <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/nav-menu-template.php#L386\" rel=\"nofollow noreferrer\">wp_nav_menu_items</a></p>\n\n<pre><code>add_filter('wp_nav_menu_items','wpsites_add_avatar_to_nav', 10, 2);\nfunction wpsites_add_avatar_to_nav( $items, $args ) {\n if( $args-&gt;theme_location == 'primary' )\n return $items; \n\n $dude = get_avatar( get_current_user_id(), 48 );\n\n if (is_user_logged_in()) : \n echo'&lt;li class=\"your-custom-class right\"&gt;' . $dude . '&lt;/li&gt;';\n endif;\n\n return $items;\n}\n</code></pre>\n\n<p>Might need to use <a href=\"https://stackoverflow.com/a/2832207\">output buffering</a>.</p>\n\n<p>Some work is required on your behalf to get your code working with this filter. You will need to change the class depending on which theme you're using.</p>\n" } ]
2015/05/27
[ "https://wordpress.stackexchange.com/questions/189543", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So, I have following `php` code: ``` <?php global $my_profile; ?> <?php if (is_user_logged_in()) : ?> <div class="img" data-key="profile"><?php echo get_avatar( get_current_user_id(), 64 ); ?></div> <?php endif; ?> ``` It pulls the profile picture of currently logged in user. I am trying to add this to one of the menu item title, so that user profile picture is shown as a part of the menu. It looks like I cannot directly add this code into `menu`. What would be the best way to add this into one of the menu title? Thanks. Steve
Add to your functions file and use [wp\_nav\_menu\_items](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/nav-menu-template.php#L386) ``` add_filter('wp_nav_menu_items','wpsites_add_avatar_to_nav', 10, 2); function wpsites_add_avatar_to_nav( $items, $args ) { if( $args->theme_location == 'primary' ) return $items; $dude = get_avatar( get_current_user_id(), 48 ); if (is_user_logged_in()) : echo'<li class="your-custom-class right">' . $dude . '</li>'; endif; return $items; } ``` Might need to use [output buffering](https://stackoverflow.com/a/2832207). Some work is required on your behalf to get your code working with this filter. You will need to change the class depending on which theme you're using.
189,554
<p>I have recently had an issue where I have been unable to install the WP Smush Pro plugin because I don't have the Manual Install or One-Click Installation options available.</p> <p>I came across <a href="http://www.narga.net/stop-fix-wordpress-ask-for-ftp-credentials-upgrade-install-delete-themes-plugins/">this post</a> which suggested tweaking the settings in <code>wp-config.php</code>. I added the settings suggested, however the one that seems to be the most important is:</p> <p><code>define('FS_METHOD', 'direct');</code></p> <p>What I would like to know is what real concerns should I have around setting <code>FS_METHOD</code> to <code>direct</code>? Are there any other alternatives to installing the plugin?</p> <p>This is what the official documentation has to say:</p> <blockquote> <p>FS_METHOD forces the filesystem method. It should only be "direct", "ssh2", "ftpext", or "ftpsockets". Generally, you should only change this if you are experiencing update problems. If you change it and it doesn't help, change it back/remove it. Under most circumstances, setting it to 'ftpsockets' will work if the automatically chosen method does not.</p> <p>(Primary Preference) "direct" forces it to use Direct File I/O requests from within PHP, this is fraught with opening up security issues on poorly configured hosts, This is chosen automatically when appropriate.</p> </blockquote>
[ { "answer_id": 189570, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 6, "selected": true, "text": "<p>This is just, how I understood the idea of the <a href=\"https://codex.wordpress.org/Filesystem_API\">WordPress File API</a>. If it is wrong, please downvote :)</p>\n\n<p>Okay. If you upload a file, this file has an owner. If you upload your file with FTP, you login and the file will be owned by the FTP user. Since you have the credentials, you can alter these files through FTP. The owner can usually execute, delete, alter etc. the file. Of course, you can change this by changing the <a href=\"http://en.wikipedia.org/wiki/File_system_permissions\">file permissions</a>.</p>\n\n<p>If you upload a file using PHP, the linux user, which is executing PHP is owning the file. This user can now edit, delete, execute etc. the file. This is okay as long as only you are the user, who is executing PHP on your system.</p>\n\n<p>Lets assume, you are on a \"poorly\" configured shared host. A lot of people run their PHP websites on this system. Lets say only one linux user is executing PHP for all these people. One of the webmasters on this shared host has bad intentions. He sees your page and he figures out the path to your WordPress installation. For example, WP_DEBUG is set to true and there is an error message like</p>\n\n<pre><code>[warning] /var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php on line 1\n</code></pre>\n\n<p>\"Ha!\" the bad boy says. Lets see, if this guy has set <code>FS_METHOD</code> to <code>direct</code> and he writes a script like</p>\n\n<pre><code>&lt;?php\nunlink( '/var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php' );\n?&gt;\n</code></pre>\n\n<p>Since only one user is running PHP and this user is also used by the bad boy he can alter/delete/execute the files on your system if you have uploaded them via PHP and by this attached the PHP user as the owner.</p>\n\n<p>Your site is hacked.</p>\n\n<p>Or, as it says in the Codex:</p>\n\n<blockquote>\n <p>Many hosting systems have the webserver running as a different user\n than the owner of the WordPress files. When this is the case, a\n process writing files from the webserver user will have the resulting\n files owned by the webserver's user account instead of the actual\n user's account. This can lead to a security problem in shared hosting\n situations, where multiple users are sharing the same webserver for\n different sites.</p>\n</blockquote>\n" }, { "answer_id": 232291, "author": "Mark", "author_id": 78827, "author_profile": "https://wordpress.stackexchange.com/users/78827", "pm_score": 5, "selected": false, "text": "<h2>What's the risk?</h2>\n\n<p>On a poorly configured shared host, every customer's PHP will execute as the same user (let's say <code>apache</code> for discussion). This setup is surprisingly common.</p>\n\n<p>If you're on such a host and use WordPress to install the plugin using direct file access, all of your plugin files will belong to <code>apache</code>. A legitimate user on the same server would be able to attack you by writing a PHP script that injects evil code into your plugin files. They upload their script to their own website and request its URL. Your code is successfully compromised because their script runs as <code>apache</code>, the same one that owns your plugin files.</p>\n\n<h2>What does <code>FS_METHOD 'direct'</code> have to do with it?</h2>\n\n<p>When WordPress needs to install files (such as a plugin) it uses the <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-admin/includes/file.php#L951\" rel=\"noreferrer\">get_filesystem_method()</a> function to determine how to access the filesystem. If you don't define <code>FS_METHOD</code> it will choose a default for you, otherwise it will use your selection as long as it makes sense.</p>\n\n<p>The default behavior will <strong>try</strong> to detect whether you're in an at-risk environment like the one I described above, and if it thinks you're safe it will use the <code>'direct'</code> method. In this case WordPress will create the files directly through PHP, causing them to belong to the <code>apache</code> user (in this example). Otherwise it'll fall back to a safer method, such as prompting you for SFTP credentials and creating the files as you.</p>\n\n<p><code>FS_METHOD = 'direct'</code> asks WordPress to bypass that at-risk detection and <em>always</em> create files using the <code>'direct'</code> method.</p>\n\n<h3>Then why use <code>FS_METHOD = 'direct'</code>?</h3>\n\n<p>Unfortunately, WordPress' logic for detecting an at-risk environment is flawed and produces both false-positives and false-negatives. Whoops. The test involves creating a file and making sure it belongs to the same owner as the directory it lives in. The assumption is that if the users are the same, PHP is running as your own account and it's safe to install plugins as that account. If they're different, WordPress assumes that PHP is running as a shared account and it's not safe to install plugins as that account. Unfortunately both of these assumptions are educated guesses that will frequently be wrong.</p>\n\n<p>You would use <code>define('FS_METHOD', 'direct' );</code> in a false positive scenario such as this one: you are part of a trusted team whose members all upload files through their own account. PHP runs as its own separate user. WordPress will assume that this is an at-risk environment and will not default to <code>'direct'</code> mode. In reality it's only shared with users you trust and as such <code>'direct'</code> mode is safe. In this case you should use <code>define('FS_METHOD', 'direct' );</code> to force WordPress to write files directly.</p>\n" }, { "answer_id": 257737, "author": "Danny", "author_id": 98184, "author_profile": "https://wordpress.stackexchange.com/users/98184", "pm_score": 2, "selected": false, "text": "<p>There is a 'well-configured' situation where 'direct' will lead to problems.</p>\n\n<p>It is also possible to configure shared WP hosting with non-shared PHP execution users, different from the file/directory ownership users.\nSo you end up with the files owned by user1 and the PHP code is executed as php-user1.</p>\n\n<p>In that situation, hacked plugins or core code (a) can't write to (or even read from, depending on permissions) other users' directoriess; (b) can't write <em>this</em> user's files and so can't add trojan code to the core or plugin code.</p>\n\n<p>So if the hosting is set up like that, you MUST use FTP for updates and 'direct' will not work.</p>\n\n<p>If you set 'direct' in wp-config.php and the PHP execution user does not have write permission, you'll get Update Failed messages and have no pop-up asking for FTP credentials.</p>\n" } ]
2015/05/27
[ "https://wordpress.stackexchange.com/questions/189554", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38865/" ]
I have recently had an issue where I have been unable to install the WP Smush Pro plugin because I don't have the Manual Install or One-Click Installation options available. I came across [this post](http://www.narga.net/stop-fix-wordpress-ask-for-ftp-credentials-upgrade-install-delete-themes-plugins/) which suggested tweaking the settings in `wp-config.php`. I added the settings suggested, however the one that seems to be the most important is: `define('FS_METHOD', 'direct');` What I would like to know is what real concerns should I have around setting `FS_METHOD` to `direct`? Are there any other alternatives to installing the plugin? This is what the official documentation has to say: > > FS\_METHOD forces the filesystem method. It should only be "direct", > "ssh2", "ftpext", or "ftpsockets". Generally, you should only change > this if you are experiencing update problems. If you change it and it > doesn't help, change it back/remove it. Under most circumstances, > setting it to 'ftpsockets' will work if the automatically chosen > method does not. > > > (Primary Preference) "direct" forces it to use Direct File I/O requests from within PHP, this is fraught with opening up security > issues on poorly configured hosts, This is chosen automatically when > appropriate. > > >
This is just, how I understood the idea of the [WordPress File API](https://codex.wordpress.org/Filesystem_API). If it is wrong, please downvote :) Okay. If you upload a file, this file has an owner. If you upload your file with FTP, you login and the file will be owned by the FTP user. Since you have the credentials, you can alter these files through FTP. The owner can usually execute, delete, alter etc. the file. Of course, you can change this by changing the [file permissions](http://en.wikipedia.org/wiki/File_system_permissions). If you upload a file using PHP, the linux user, which is executing PHP is owning the file. This user can now edit, delete, execute etc. the file. This is okay as long as only you are the user, who is executing PHP on your system. Lets assume, you are on a "poorly" configured shared host. A lot of people run their PHP websites on this system. Lets say only one linux user is executing PHP for all these people. One of the webmasters on this shared host has bad intentions. He sees your page and he figures out the path to your WordPress installation. For example, WP\_DEBUG is set to true and there is an error message like ``` [warning] /var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php on line 1 ``` "Ha!" the bad boy says. Lets see, if this guy has set `FS_METHOD` to `direct` and he writes a script like ``` <?php unlink( '/var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php' ); ?> ``` Since only one user is running PHP and this user is also used by the bad boy he can alter/delete/execute the files on your system if you have uploaded them via PHP and by this attached the PHP user as the owner. Your site is hacked. Or, as it says in the Codex: > > Many hosting systems have the webserver running as a different user > than the owner of the WordPress files. When this is the case, a > process writing files from the webserver user will have the resulting > files owned by the webserver's user account instead of the actual > user's account. This can lead to a security problem in shared hosting > situations, where multiple users are sharing the same webserver for > different sites. > > >
189,584
<p>I am trying to output all the tags (custom taxonomy) without link, and add special class to current post tags. For example: if there are 10 tags but current post has 3 of them applied, then it should display all the 10 tags without link but only 3 tags should have special class.</p> <p>I am currently using:</p> <pre><code> $terms = get_the_terms( $post-&gt;ID, $tax ); $tag_list = implode(',', wp_list_pluck($terms, 'term_id') ); wp_tag_cloud( array( 'taxonomy' =&gt; $tax, 'include' =&gt; $tag_list) ); </code></pre> <p>which is just showing tags with link for current post.</p>
[ { "answer_id": 189570, "author": "websupporter", "author_id": 48693, "author_profile": "https://wordpress.stackexchange.com/users/48693", "pm_score": 6, "selected": true, "text": "<p>This is just, how I understood the idea of the <a href=\"https://codex.wordpress.org/Filesystem_API\">WordPress File API</a>. If it is wrong, please downvote :)</p>\n\n<p>Okay. If you upload a file, this file has an owner. If you upload your file with FTP, you login and the file will be owned by the FTP user. Since you have the credentials, you can alter these files through FTP. The owner can usually execute, delete, alter etc. the file. Of course, you can change this by changing the <a href=\"http://en.wikipedia.org/wiki/File_system_permissions\">file permissions</a>.</p>\n\n<p>If you upload a file using PHP, the linux user, which is executing PHP is owning the file. This user can now edit, delete, execute etc. the file. This is okay as long as only you are the user, who is executing PHP on your system.</p>\n\n<p>Lets assume, you are on a \"poorly\" configured shared host. A lot of people run their PHP websites on this system. Lets say only one linux user is executing PHP for all these people. One of the webmasters on this shared host has bad intentions. He sees your page and he figures out the path to your WordPress installation. For example, WP_DEBUG is set to true and there is an error message like</p>\n\n<pre><code>[warning] /var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php on line 1\n</code></pre>\n\n<p>\"Ha!\" the bad boy says. Lets see, if this guy has set <code>FS_METHOD</code> to <code>direct</code> and he writes a script like</p>\n\n<pre><code>&lt;?php\nunlink( '/var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php' );\n?&gt;\n</code></pre>\n\n<p>Since only one user is running PHP and this user is also used by the bad boy he can alter/delete/execute the files on your system if you have uploaded them via PHP and by this attached the PHP user as the owner.</p>\n\n<p>Your site is hacked.</p>\n\n<p>Or, as it says in the Codex:</p>\n\n<blockquote>\n <p>Many hosting systems have the webserver running as a different user\n than the owner of the WordPress files. When this is the case, a\n process writing files from the webserver user will have the resulting\n files owned by the webserver's user account instead of the actual\n user's account. This can lead to a security problem in shared hosting\n situations, where multiple users are sharing the same webserver for\n different sites.</p>\n</blockquote>\n" }, { "answer_id": 232291, "author": "Mark", "author_id": 78827, "author_profile": "https://wordpress.stackexchange.com/users/78827", "pm_score": 5, "selected": false, "text": "<h2>What's the risk?</h2>\n\n<p>On a poorly configured shared host, every customer's PHP will execute as the same user (let's say <code>apache</code> for discussion). This setup is surprisingly common.</p>\n\n<p>If you're on such a host and use WordPress to install the plugin using direct file access, all of your plugin files will belong to <code>apache</code>. A legitimate user on the same server would be able to attack you by writing a PHP script that injects evil code into your plugin files. They upload their script to their own website and request its URL. Your code is successfully compromised because their script runs as <code>apache</code>, the same one that owns your plugin files.</p>\n\n<h2>What does <code>FS_METHOD 'direct'</code> have to do with it?</h2>\n\n<p>When WordPress needs to install files (such as a plugin) it uses the <a href=\"https://core.trac.wordpress.org/browser/tags/4.5.3/src/wp-admin/includes/file.php#L951\" rel=\"noreferrer\">get_filesystem_method()</a> function to determine how to access the filesystem. If you don't define <code>FS_METHOD</code> it will choose a default for you, otherwise it will use your selection as long as it makes sense.</p>\n\n<p>The default behavior will <strong>try</strong> to detect whether you're in an at-risk environment like the one I described above, and if it thinks you're safe it will use the <code>'direct'</code> method. In this case WordPress will create the files directly through PHP, causing them to belong to the <code>apache</code> user (in this example). Otherwise it'll fall back to a safer method, such as prompting you for SFTP credentials and creating the files as you.</p>\n\n<p><code>FS_METHOD = 'direct'</code> asks WordPress to bypass that at-risk detection and <em>always</em> create files using the <code>'direct'</code> method.</p>\n\n<h3>Then why use <code>FS_METHOD = 'direct'</code>?</h3>\n\n<p>Unfortunately, WordPress' logic for detecting an at-risk environment is flawed and produces both false-positives and false-negatives. Whoops. The test involves creating a file and making sure it belongs to the same owner as the directory it lives in. The assumption is that if the users are the same, PHP is running as your own account and it's safe to install plugins as that account. If they're different, WordPress assumes that PHP is running as a shared account and it's not safe to install plugins as that account. Unfortunately both of these assumptions are educated guesses that will frequently be wrong.</p>\n\n<p>You would use <code>define('FS_METHOD', 'direct' );</code> in a false positive scenario such as this one: you are part of a trusted team whose members all upload files through their own account. PHP runs as its own separate user. WordPress will assume that this is an at-risk environment and will not default to <code>'direct'</code> mode. In reality it's only shared with users you trust and as such <code>'direct'</code> mode is safe. In this case you should use <code>define('FS_METHOD', 'direct' );</code> to force WordPress to write files directly.</p>\n" }, { "answer_id": 257737, "author": "Danny", "author_id": 98184, "author_profile": "https://wordpress.stackexchange.com/users/98184", "pm_score": 2, "selected": false, "text": "<p>There is a 'well-configured' situation where 'direct' will lead to problems.</p>\n\n<p>It is also possible to configure shared WP hosting with non-shared PHP execution users, different from the file/directory ownership users.\nSo you end up with the files owned by user1 and the PHP code is executed as php-user1.</p>\n\n<p>In that situation, hacked plugins or core code (a) can't write to (or even read from, depending on permissions) other users' directoriess; (b) can't write <em>this</em> user's files and so can't add trojan code to the core or plugin code.</p>\n\n<p>So if the hosting is set up like that, you MUST use FTP for updates and 'direct' will not work.</p>\n\n<p>If you set 'direct' in wp-config.php and the PHP execution user does not have write permission, you'll get Update Failed messages and have no pop-up asking for FTP credentials.</p>\n" } ]
2015/05/27
[ "https://wordpress.stackexchange.com/questions/189584", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69363/" ]
I am trying to output all the tags (custom taxonomy) without link, and add special class to current post tags. For example: if there are 10 tags but current post has 3 of them applied, then it should display all the 10 tags without link but only 3 tags should have special class. I am currently using: ``` $terms = get_the_terms( $post->ID, $tax ); $tag_list = implode(',', wp_list_pluck($terms, 'term_id') ); wp_tag_cloud( array( 'taxonomy' => $tax, 'include' => $tag_list) ); ``` which is just showing tags with link for current post.
This is just, how I understood the idea of the [WordPress File API](https://codex.wordpress.org/Filesystem_API). If it is wrong, please downvote :) Okay. If you upload a file, this file has an owner. If you upload your file with FTP, you login and the file will be owned by the FTP user. Since you have the credentials, you can alter these files through FTP. The owner can usually execute, delete, alter etc. the file. Of course, you can change this by changing the [file permissions](http://en.wikipedia.org/wiki/File_system_permissions). If you upload a file using PHP, the linux user, which is executing PHP is owning the file. This user can now edit, delete, execute etc. the file. This is okay as long as only you are the user, who is executing PHP on your system. Lets assume, you are on a "poorly" configured shared host. A lot of people run their PHP websites on this system. Lets say only one linux user is executing PHP for all these people. One of the webmasters on this shared host has bad intentions. He sees your page and he figures out the path to your WordPress installation. For example, WP\_DEBUG is set to true and there is an error message like ``` [warning] /var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php on line 1 ``` "Ha!" the bad boy says. Lets see, if this guy has set `FS_METHOD` to `direct` and he writes a script like ``` <?php unlink( '/var/www/vhosts/userxyz/wp-content/plugins/bad-plugin/doesnt-execute-correctly.php' ); ?> ``` Since only one user is running PHP and this user is also used by the bad boy he can alter/delete/execute the files on your system if you have uploaded them via PHP and by this attached the PHP user as the owner. Your site is hacked. Or, as it says in the Codex: > > Many hosting systems have the webserver running as a different user > than the owner of the WordPress files. When this is the case, a > process writing files from the webserver user will have the resulting > files owned by the webserver's user account instead of the actual > user's account. This can lead to a security problem in shared hosting > situations, where multiple users are sharing the same webserver for > different sites. > > >
189,627
<p>how do you make the user role "contributor" to be same as the user role "seller" by using functions.php</p> <p>I've tried user role editor, but it seems to be the dokan multivendor plugin has set only into user role "seller" but I wanted to make the "contributor" to be same as the seller role</p>
[ { "answer_id": 189629, "author": "sakibmoon", "author_id": 23214, "author_profile": "https://wordpress.stackexchange.com/users/23214", "pm_score": 1, "selected": false, "text": "<p>Contributor has the following capabilities</p>\n\n<ul>\n<li>delete_posts</li>\n<li>edit_posts</li>\n<li>read</li>\n</ul>\n\n<p>You can create the \"Seller\" role to have same capabilities as Contributor</p>\n\n<pre><code>add_role(\n 'seller',\n __( 'Seller' ),\n array(\n 'read' =&gt; true,\n 'edit_posts' =&gt; true,\n 'delete_posts' =&gt; true,\n )\n);\n</code></pre>\n\n<p>Warning from codex</p>\n\n<p><strong>NB: This setting is saved to the database (in table wp_options, field wp_user_roles), so it might be better to run this on theme/plugin activation</strong></p>\n\n<p>In <code>functions.php</code>, you should use this in <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow\">after_setup_theme</a> hook.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>You can also create a user role who have same permission as another this way</p>\n\n<pre><code>add_role(\n 'specialuser',\n __('Special User'),\n get_role('seller')-&gt;capabilities\n);\n</code></pre>\n\n<p>It will grant <code>specialuser</code> same capabilities as <code>seller</code>.</p>\n" }, { "answer_id": 190256, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>should I copy the code from the link provided?\n<a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow\">http://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme</a></p>\n\n<p>it's a twentytwelve theme, my theme is oxygen theme, how can I impliment the code? change the word twentytwelve into oxygen?</p>\n" } ]
2015/05/27
[ "https://wordpress.stackexchange.com/questions/189627", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73729/" ]
how do you make the user role "contributor" to be same as the user role "seller" by using functions.php I've tried user role editor, but it seems to be the dokan multivendor plugin has set only into user role "seller" but I wanted to make the "contributor" to be same as the seller role
Contributor has the following capabilities * delete\_posts * edit\_posts * read You can create the "Seller" role to have same capabilities as Contributor ``` add_role( 'seller', __( 'Seller' ), array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, ) ); ``` Warning from codex **NB: This setting is saved to the database (in table wp\_options, field wp\_user\_roles), so it might be better to run this on theme/plugin activation** In `functions.php`, you should use this in [after\_setup\_theme](http://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme) hook. **EDIT** You can also create a user role who have same permission as another this way ``` add_role( 'specialuser', __('Special User'), get_role('seller')->capabilities ); ``` It will grant `specialuser` same capabilities as `seller`.
189,668
<p>I've been searching for a couple hours and consulted multiple posts, but I seem to get this to work.</p> <p>I have this weird bug where users cannot see their drafts of a custom post type if they don't assign a category to them. So if they just click 'save as draft' and want to go back to it later, it won't be visible to them (I have to go in as an admin and set a category for it to be visible to them). I have no idea why this is occurring but I'm willing to work around it.</p> <p>In <strong>Settings</strong> > <strong>Writing</strong> you can set the default category for a regular post, but there is no such option available for a custom post type. I am fine to set the default type to 'Uncategorized', just like it is set with regular posts. So I'm trying to accomplish this.</p> <p>Some snippets I've come across like <a href="https://wordpress.org/support/topic/set-category-to-a-custom-post-type-automatically?replies=10" rel="noreferrer">this</a> are aimed for 'default category upon publish' but I need it upon autosave (some users just have access to 'save draft' and 'submit for publishing'). At least 6 I've come across are unanswered. </p> <p>I did implement one specific code unsuccessfully (I can't find the snippet for the life of me, but the desired default category used in the example was 'authors'). This is driving me nuts, and I would really appreciate your help. Thanks.</p> <p>EDIT: I have tried the following code (which I got from <a href="https://wordpress.org/support/topic/set-category-to-a-custom-post-type-automatically?replies=10" rel="noreferrer">here</a>) and got 'uncategorized' to be checked automatically upon save for the post type 'community' but the problem is that it completely <strong>overrides</strong> other categories you might replace this with. That is to say, if you uncheck 'uncategorized' and choose meaningful categories, upon 'publish' or 'save', all of those selections are erased and it reverts back to community. Need it to just have 'uncategorized' <em>until</em> the user replaces that default category (exactly the way a defaul category works with regular 'post' type).</p> <pre><code>function add_comm_category_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { $uncategorized= array (1); wp_set_object_terms( $post_ID, $uncategorized, 'category'); } } add_action('save_post', 'add_comm_category_automatically'); </code></pre>
[ { "answer_id": 189672, "author": "mishu", "author_id": 64607, "author_profile": "https://wordpress.stackexchange.com/users/64607", "pm_score": 4, "selected": true, "text": "<p>Use the save_post action hook and in the call back function use wp_set_object_terms( $object_id, $terms, $taxonomy, $append ) function.</p>\n\n<p>For your custom post type the code can be like this </p>\n\n<pre><code>function save_book_meta( $post_id, $post, $update ) {\n\n $slug = 'book'; //Slug of CPT\n\n // If this isn't a 'book' post, don't update it.\n if ( $slug != $post-&gt;post_type ) {\n return;\n }\n\n wp_set_object_terms( get_the_ID(), $term_id, $taxonomy );\n}\n\nadd_action( 'save_post', 'save_book_meta', 10, 3 );\n</code></pre>\n\n<p>$taxonomy - The context in which to relate the term to the object. This can be category, post_tag, or the name of another taxonomy.</p>\n\n<p>$term_id - term ID of the taxonomy</p>\n\n<p>I do not know your project thoroughly, so you can consider this snippet as a way of doing what you wanted to do.</p>\n\n<p>For more reference visit this two links given below : </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_set_object_terms\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/wp_set_object_terms</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/save_post</a></p>\n\n<p>I hope you will find a way out. </p>\n" }, { "answer_id": 245891, "author": "BrainBUG", "author_id": 42681, "author_profile": "https://wordpress.stackexchange.com/users/42681", "pm_score": 0, "selected": false, "text": "<p>I am using pods.io to build my CPTs and custom taxonomies. Had the same problem. With the code from @mishu, I was able to accomplish my goal.</p>\n\n<pre><code>function event_preset_category( $post_id, $post, $update ) {\n\n $slug = 'termine'; //Slug of CPT\n\n // If this isn't the right slug, don't update it.\n if ( $slug != $post-&gt;post_type ) {\n return;\n }\n\n // Get the ID of default/ fallback category\n // $default_term = get_term_by('slug', 'your_term_slug', 'your_custom_taxonomy');\n\n $default_term = get_term_by('slug', 'alle', 'termin_cat');\n\n wp_set_object_terms( get_the_ID(), $default_term-&gt;term_id, 'termin_cat' );\n}\n\nadd_action( 'save_post', 'event_preset_category', 10, 3 );\n</code></pre>\n" }, { "answer_id": 375310, "author": "izikz", "author_id": 195056, "author_profile": "https://wordpress.stackexchange.com/users/195056", "pm_score": 0, "selected": false, "text": "<p>If I understand correctly, all you need to do is to add the optional parameter $append as true (the default is false)</p>\n<p>wp_set_object_terms( int $object_id, string|int|array $terms, string $taxonomy, bool $append = false )</p>\n<p>for example, in the code you posted:\nwp_set_object_terms( $post_ID, $uncategorized, 'category', true);</p>\n<p>that worked for me.</p>\n" }, { "answer_id": 383838, "author": "firstlord", "author_id": 202322, "author_profile": "https://wordpress.stackexchange.com/users/202322", "pm_score": 0, "selected": false, "text": "<p>It is possible to do it this way. If other answers didn't work, you can try this:</p>\n<pre><code>function auto_category( $post_id, $post, $update ) {\n \n $slug = 'news'; //Slug of CPT\n \n // If this isn't the right slug, don't update it.\n if ( $slug != $post-&gt;post_type ) {\n return;\n }\n \n $category_term = get_term_by( 'name', 'news_category_slug', 'category' );\n \n wp_set_object_terms( get_the_ID(), $category_term-&gt;term_id, 'category' );\n}\n\nadd_action( 'save_post', 'auto_category', 10, 3 );\n</code></pre>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189668", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70893/" ]
I've been searching for a couple hours and consulted multiple posts, but I seem to get this to work. I have this weird bug where users cannot see their drafts of a custom post type if they don't assign a category to them. So if they just click 'save as draft' and want to go back to it later, it won't be visible to them (I have to go in as an admin and set a category for it to be visible to them). I have no idea why this is occurring but I'm willing to work around it. In **Settings** > **Writing** you can set the default category for a regular post, but there is no such option available for a custom post type. I am fine to set the default type to 'Uncategorized', just like it is set with regular posts. So I'm trying to accomplish this. Some snippets I've come across like [this](https://wordpress.org/support/topic/set-category-to-a-custom-post-type-automatically?replies=10) are aimed for 'default category upon publish' but I need it upon autosave (some users just have access to 'save draft' and 'submit for publishing'). At least 6 I've come across are unanswered. I did implement one specific code unsuccessfully (I can't find the snippet for the life of me, but the desired default category used in the example was 'authors'). This is driving me nuts, and I would really appreciate your help. Thanks. EDIT: I have tried the following code (which I got from [here](https://wordpress.org/support/topic/set-category-to-a-custom-post-type-automatically?replies=10)) and got 'uncategorized' to be checked automatically upon save for the post type 'community' but the problem is that it completely **overrides** other categories you might replace this with. That is to say, if you uncheck 'uncategorized' and choose meaningful categories, upon 'publish' or 'save', all of those selections are erased and it reverts back to community. Need it to just have 'uncategorized' *until* the user replaces that default category (exactly the way a defaul category works with regular 'post' type). ``` function add_comm_category_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { $uncategorized= array (1); wp_set_object_terms( $post_ID, $uncategorized, 'category'); } } add_action('save_post', 'add_comm_category_automatically'); ```
Use the save\_post action hook and in the call back function use wp\_set\_object\_terms( $object\_id, $terms, $taxonomy, $append ) function. For your custom post type the code can be like this ``` function save_book_meta( $post_id, $post, $update ) { $slug = 'book'; //Slug of CPT // If this isn't a 'book' post, don't update it. if ( $slug != $post->post_type ) { return; } wp_set_object_terms( get_the_ID(), $term_id, $taxonomy ); } add_action( 'save_post', 'save_book_meta', 10, 3 ); ``` $taxonomy - The context in which to relate the term to the object. This can be category, post\_tag, or the name of another taxonomy. $term\_id - term ID of the taxonomy I do not know your project thoroughly, so you can consider this snippet as a way of doing what you wanted to do. For more reference visit this two links given below : <https://codex.wordpress.org/Function_Reference/wp_set_object_terms> <https://codex.wordpress.org/Plugin_API/Action_Reference/save_post> I hope you will find a way out.
189,692
<p>I'm raising this problem because I don't find a latest answer and the problem still exist to me.</p> <p>I'm running wordpress 4.2.2 with <a href="http://theme.co/x/" rel="nofollow">x theme</a> when I'm editing the content via WP default editor (tinymce). I'm having lot of problem with HTML format. For example if I edit the content in VISUAL/TEXT mode in the front-end I'm getting empty <code>&lt;p&gt;&lt;/p&gt;</code> tags even sometime I noticed if I add content like this:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Content1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Content2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Content3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>it'll be transform into: (this is happening once in while)</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;/a&gt;Content1&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;/a&gt;Content2&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;/a&gt;Content3&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>My questions are:</p> <ul> <li>Is there a solution for this?</li> <li>Or can we change the default editor to the plain text area? perhaps disable the tinymce editor</li> </ul>
[ { "answer_id": 190036, "author": "Mathew Tinsley", "author_id": 69793, "author_profile": "https://wordpress.stackexchange.com/users/69793", "pm_score": 4, "selected": true, "text": "<p>You can disable the visual editor entirely in your <a href=\"https://codex.wordpress.org/Users_Your_Profile_Screen\">profile settings</a>. If you need to disable it on a per page basis, take a look at <a href=\"https://wordpress.stackexchange.com/questions/12370/disable-wysiwyg-editor-only-when-creating-a-page/18149#18149\">this answer</a>.</p>\n\n<p>Using text mode may not solve the empty paragraph problem, the <a href=\"https://codex.wordpress.org/Function_Reference/wpautop\">wpautop</a> filter is applied to the content regardless of how the content is edited. You can remove the filter, but then you'll have to manually break and paragraph your content.</p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nremove_filter( 'the_excerpt', 'wpautop' );\n</code></pre>\n\n<p>Alternatively, you can use a filter to strip out any empty paragraphs when displaying your content:</p>\n\n<p><a href=\"https://gist.github.com/ninnypants/1668216\">https://gist.github.com/ninnypants/1668216</a></p>\n\n<p>Regarding the issue with the anchors, I haven't had this particular issue with the editor. In general, if I am writing a lot of HTML in a post I like to use a \"raw html\" plugin. For example: <a href=\"https://wordpress.org/plugins/preserved-html-editor-markup-plus/\">https://wordpress.org/plugins/preserved-html-editor-markup-plus/</a></p>\n" }, { "answer_id": 190037, "author": "gdarko", "author_id": 73926, "author_profile": "https://wordpress.stackexchange.com/users/73926", "pm_score": 1, "selected": false, "text": "<p>It's called <em>wpautop</em>. There is a plugin that will help you to effectively deal with this</p>\n\n<p>Please check <a href=\"https://wordpress.org/plugins/ps-disable-auto-formatting/\" rel=\"nofollow\">PS Disable Auto Formatting</a></p>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 190072, "author": "sohan", "author_id": 69017, "author_profile": "https://wordpress.stackexchange.com/users/69017", "pm_score": 0, "selected": false, "text": "<p>you can use this if you looking any certain post type </p>\n\n<pre><code>remove_filter('the_content','wpautop');\n\n//decide when you want to apply the auto paragraph\n\nadd_filter('the_content','my_custom_formatting');\n\nfunction my_custom_formatting($content){\nif(get_post_type()=='my_custom_post') //if it does not work, you may want to pass the current post object to get_post_type\n return $content;//no autop\nelse\n return wpautop($content);\n}\n</code></pre>\n\n<p>please find here <a href=\"https://wordpress.stackexchange.com/questions/82860/remove-filter-the-content-wpautop-only-for-certain-post-types\">remove_filter( &#39;the_content&#39;, &#39;wpautop&#39; ); only for certain post types</a></p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189692", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69455/" ]
I'm raising this problem because I don't find a latest answer and the problem still exist to me. I'm running wordpress 4.2.2 with [x theme](http://theme.co/x/) when I'm editing the content via WP default editor (tinymce). I'm having lot of problem with HTML format. For example if I edit the content in VISUAL/TEXT mode in the front-end I'm getting empty `<p></p>` tags even sometime I noticed if I add content like this: ``` <ul> <li><a href="#">Content1</a></li> <li><a href="#">Content2</a></li> <li><a href="#">Content3</a></li> </ul> ``` it'll be transform into: (this is happening once in while) ``` <ul> <li><a href="#"></a>Content1</li> <li><a href="#"></a>Content2</li> <li><a href="#"></a>Content3</li> </ul> ``` My questions are: * Is there a solution for this? * Or can we change the default editor to the plain text area? perhaps disable the tinymce editor
You can disable the visual editor entirely in your [profile settings](https://codex.wordpress.org/Users_Your_Profile_Screen). If you need to disable it on a per page basis, take a look at [this answer](https://wordpress.stackexchange.com/questions/12370/disable-wysiwyg-editor-only-when-creating-a-page/18149#18149). Using text mode may not solve the empty paragraph problem, the [wpautop](https://codex.wordpress.org/Function_Reference/wpautop) filter is applied to the content regardless of how the content is edited. You can remove the filter, but then you'll have to manually break and paragraph your content. ``` remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); ``` Alternatively, you can use a filter to strip out any empty paragraphs when displaying your content: <https://gist.github.com/ninnypants/1668216> Regarding the issue with the anchors, I haven't had this particular issue with the editor. In general, if I am writing a lot of HTML in a post I like to use a "raw html" plugin. For example: <https://wordpress.org/plugins/preserved-html-editor-markup-plus/>
189,693
<p>I know that you can remove the editor section of the page editor page ( :/) depending on the template chosen using <code>add_action( 'load-page.php', 'hide_editor_function' );</code> (with proper functionality of course). The problem with this though, as you should be able to tell, is that this will only work on a page load/reload. Not as soon as the template is changed.</p> <p>As far as I can find, there is no specific hook for this. So my question really is, is there a hook for when the user changes the page template for a page in the admin panel? And if not, what would be the best way to have 'instantaneous' hiding/revealing of the editor (and add custom meta boxes)?</p> <p>Thank you for your time, Lyphiix</p>
[ { "answer_id": 189716, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 2, "selected": true, "text": "<p>If you want to toggle the editor \"on the fly\", you'll need to revert to a pure JavaScript solution, and only ever \"visually\" hide it (as opposed to removing it server-side):</p>\n\n<pre><code>function wpse_189693_hide_on_template_toggle() {\n $screen = get_current_screen();\n if ( $screen &amp;&amp; $screen-&gt;id === 'page' ) :\n ?&gt;\n\n&lt;script&gt;\n jQuery( \"#page_template\" ).change(\n function() {\n jQuery( \"#postdivrich\" ).toggle( jQuery( this ).val() === \"my-template.php\" );\n }\n ).trigger( \"change\" );\n&lt;/script&gt;\n\n&lt;?php\n endif;\n}\n\nadd_action( 'admin_print_footer_scripts', 'wpse_189693_hide_on_template_toggle' );\n</code></pre>\n\n<p>The reason you can't keep your <code>hide_editor_function</code> is, whilst this will work to initially hide the editor, once the user saves and reloads the page the editor will no longer be in the source to \"toggle\". So it always has to be there, even if it's just hidden.</p>\n" }, { "answer_id": 348147, "author": "James Cushing", "author_id": 67327, "author_profile": "https://wordpress.stackexchange.com/users/67327", "pm_score": 0, "selected": false, "text": "<p>For anyone using the Gutenberg editor, I found that (in addition to my comment on the accepted answer) there's more work which needs doing here.</p>\n\n<p>Gutenberg injects children of <code>.block-editor__container</code> on the fly, so it's not enough to amend the selectors to catch the change event, you have to watch for the correct element being inserted. Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver\" rel=\"nofollow noreferrer\">MutationObserver</a> (since this is the better practice which replaces the soon-deprecated DOM Mutation Events and has <a href=\"https://caniuse.com/#feat=mutationobserver\" rel=\"nofollow noreferrer\">full browser support</a>), this is how I accomplished catching the template change:</p>\n\n<pre><code>$ = $ || jQuery; // Allow non-conflicting use of '$'\n\n$(function(){\n\n // Create an observer to watch for Gutenberg editor changes\n const observer = new MutationObserver( function( mutationsList, observer ){\n\n // Template select box element\n let $templateField = $( '.editor-page-attributes__template select' );\n\n // Once we have the select in the DOM...\n if( $templateField.length ){\n\n // ...add the handler, then...\n $templateField.on( 'change', function(){\n\n // ...do your on-change work here\n console.log( 'The template was changed to ' + $( this ).val() );\n\n });\n observer.disconnect();\n\n }\n\n });\n // Trigger the observer on the nearest parent that exists at 'DOMReady' time\n observer.observe( document.getElementsByClassName( 'block-editor__container' )[0], {\n childList: true, // One of the required-to-be-true attributes (throws error if not set)\n subtree: true // Watches for the target element's subtree (where the select lives)\n });\n\n});\n</code></pre>\n\n<p>Hope this helps someone!</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189693", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73761/" ]
I know that you can remove the editor section of the page editor page ( :/) depending on the template chosen using `add_action( 'load-page.php', 'hide_editor_function' );` (with proper functionality of course). The problem with this though, as you should be able to tell, is that this will only work on a page load/reload. Not as soon as the template is changed. As far as I can find, there is no specific hook for this. So my question really is, is there a hook for when the user changes the page template for a page in the admin panel? And if not, what would be the best way to have 'instantaneous' hiding/revealing of the editor (and add custom meta boxes)? Thank you for your time, Lyphiix
If you want to toggle the editor "on the fly", you'll need to revert to a pure JavaScript solution, and only ever "visually" hide it (as opposed to removing it server-side): ``` function wpse_189693_hide_on_template_toggle() { $screen = get_current_screen(); if ( $screen && $screen->id === 'page' ) : ?> <script> jQuery( "#page_template" ).change( function() { jQuery( "#postdivrich" ).toggle( jQuery( this ).val() === "my-template.php" ); } ).trigger( "change" ); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'wpse_189693_hide_on_template_toggle' ); ``` The reason you can't keep your `hide_editor_function` is, whilst this will work to initially hide the editor, once the user saves and reloads the page the editor will no longer be in the source to "toggle". So it always has to be there, even if it's just hidden.
189,714
<p>Hoping for some help here as I'm scratching my head. I'm trying to create a custom login page for my site which has gone rather well until I try to add in a custom CSS to make it look pretty. I'm trying to add in the style-login.css file using the following:</p> <pre><code>// add a custom css file for login page function nb_login_style(){ wp_enqueue_style('nublue-login', get_stylesheet_directory_uri() . '/style-login.css', FALSE, NULL, all); if ( ! has_action( 'login_enqueue_scripts', 'wp_print_styles' ) ){ add_action( 'login_enqueue_scripts', 'wp_print_styles', 11 ); } } add_action( 'login_enqueue_scripts', 'nb_login_style'); </code></pre> <p>However the style-login.css file is never being inserted into the header of my page.</p> <p>Any ideas?</p>
[ { "answer_id": 189715, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 3, "selected": true, "text": "<p>Your code works just fine for me, other than small kink that <code>all</code> should be quoted string <code>'all'</code>. But as far as WP queue is concerned it's valid.</p>\n" }, { "answer_id": 189730, "author": "Ezra Free", "author_id": 73451, "author_profile": "https://wordpress.stackexchange.com/users/73451", "pm_score": 0, "selected": false, "text": "<p>Place the following code in your theme's functions.php:</p>\n\n<pre><code>if ( ! function_exists( 'nb_login_style' ) ) :\n function nb_login_style() {\n wp_enqueue_style( 'nublue-login', get_template_directory_uri() . '/style-login.css' );\n }\n add_action( 'login_enqueue_scripts', 'nb_login_style' );\nendif;\n</code></pre>\n\n<p>Above code was loosely taken from:</p>\n\n<p><a href=\"https://codex.wordpress.org/Customizing_the_Login_Form#Styling_Your_Login\" rel=\"nofollow\">https://codex.wordpress.org/Customizing_the_Login_Form#Styling_Your_Login</a></p>\n\n<p>Also, I have a plugin I created awhile back that sounds like it does exactly what you're trying to do, might be worth taking a look:</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-customize/\" rel=\"nofollow\">https://wordpress.org/plugins/wp-customize/</a></p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189714", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73777/" ]
Hoping for some help here as I'm scratching my head. I'm trying to create a custom login page for my site which has gone rather well until I try to add in a custom CSS to make it look pretty. I'm trying to add in the style-login.css file using the following: ``` // add a custom css file for login page function nb_login_style(){ wp_enqueue_style('nublue-login', get_stylesheet_directory_uri() . '/style-login.css', FALSE, NULL, all); if ( ! has_action( 'login_enqueue_scripts', 'wp_print_styles' ) ){ add_action( 'login_enqueue_scripts', 'wp_print_styles', 11 ); } } add_action( 'login_enqueue_scripts', 'nb_login_style'); ``` However the style-login.css file is never being inserted into the header of my page. Any ideas?
Your code works just fine for me, other than small kink that `all` should be quoted string `'all'`. But as far as WP queue is concerned it's valid.
189,725
<p>I'm using <code>FontAwesome</code> and hence I need to include some extra code next to <code>parent menu</code> options that have a <code>sub-menu</code>, such as:</p> <pre><code>&lt;li&gt; &lt;a href=""&gt;About &lt;span class="fa fa-angle-down"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href=""&gt;About Us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=""&gt;Why Choose Us?&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p>However I am unsure how to do this when using <code>wp_nav_menu</code>.</p> <p>My code:</p> <pre><code>wp_nav_menu( array( 'menu' =&gt; 'main', 'container' =&gt; 'div', 'container_id' =&gt; 'mr_nav', 'container_class' =&gt; 'mr_nav collapse navbar-collapse', 'menu_class' =&gt; 'clearfix', 'menu_id' =&gt; 'main_menu' ) ); </code></pre> <p>Is there anyway to add the span tag as above when the menu item has a <code>sub-menu</code>?</p>
[ { "answer_id": 189837, "author": "Flamenco", "author_id": 72914, "author_profile": "https://wordpress.stackexchange.com/users/72914", "pm_score": 1, "selected": false, "text": "<p>Filtering menu items is something that I don't enjoy much. :-) So I'm going to give you another idea. Instead of using extra HTML, I have a purely CSS solution. It targets the top level of your menu, and leaves the submenu alone. If you're on the FontAwesome site, you can get unicode for the symbol you want. I grabbed the unicode for your choice. </p>\n\n<p>See if this works for you. (You may have a different ID or class on your top level). You'll probably need to adjust for spacing. I do all FontAwesome stuff on my sites this way. </p>\n\n<pre><code>ul#menu-top-navigation-menu &gt; li &gt; a:after {\n content: \"\\f107\";\n font-family: 'FontAwesome';\n font-size: 27px;\n padding-left: 12px;\n speak: none;\n}\n</code></pre>\n" }, { "answer_id": 189852, "author": "Brett", "author_id": 1839, "author_profile": "https://wordpress.stackexchange.com/users/1839", "pm_score": 1, "selected": true, "text": "<p>Ok, figured it out. You need to use a <code>walker</code> instance which is passed in as an instance via the <code>wp_nav_menu</code> function, like so:</p>\n\n<pre><code>wp_nav_menu( array(\n 'menu' =&gt; 'main',\n 'container' =&gt; 'div',\n 'container_id' =&gt; 'mr_nav',\n 'container_class' =&gt; 'mr_nav collapse navbar-collapse',\n 'menu_class' =&gt; 'clearfix',\n 'menu_id' =&gt; 'main_menu',\n 'walker' =&gt; new My_Walker,\n )\n );\n</code></pre>\n\n<p>Then you put the following inside your <code>functions.php</code> file:</p>\n\n<pre><code>class My_Walker extends Walker_Nav_Menu {\n\n function start_el(&amp;$output, $item, $depth, $args) {\n\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes[] = 'menu-item-' . $item-&gt;ID;\n\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item-&gt;ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n $output .= $indent . '&lt;li' . $id . $class_names .'&gt;';\n\n $atts = array();\n $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n\n\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr =&gt; $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a'. $attributes .'&gt;';\n /** This filter is documented in wp-includes/post-template.php */\n $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after;\n $item_output .= ($this-&gt;has_children) ? ' &lt;span class=\"fa fa-angle-down\"&gt;&lt;/span&gt;' : '';\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n\n }\n\n}\n</code></pre>\n\n<p>To break it down... the above is basically a copy of the default <code>Walker_Nav_Menu</code> method with one small addition:</p>\n\n<pre><code> $item_output .= '&lt;a'. $attributes .'&gt;';\n /** This filter is documented in wp-includes/post-template.php */\n $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after;\n $item_output .= ($this-&gt;has_children) ? ' &lt;span class=\"fa fa-angle-down\"&gt;&lt;/span&gt;' : '';\n $item_output .= '&lt;/a&gt;';\n</code></pre>\n\n<p>In the above code I merely added the line:</p>\n\n<pre><code>$item_output .= ($this-&gt;has_children) ? ' &lt;span class=\"fa fa-angle-down\"&gt;&lt;/span&gt;' : '';\n</code></pre>\n\n<p>...before the closing <code>&lt;/a&gt;</code> was added.</p>\n\n<p>That's it! :)</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189725", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1839/" ]
I'm using `FontAwesome` and hence I need to include some extra code next to `parent menu` options that have a `sub-menu`, such as: ``` <li> <a href="">About <span class="fa fa-angle-down"></span></a> <ul class="sub-menu"> <li><a href="">About Us</a></li> <li><a href="">Why Choose Us?</a></li> </ul> </li> ``` However I am unsure how to do this when using `wp_nav_menu`. My code: ``` wp_nav_menu( array( 'menu' => 'main', 'container' => 'div', 'container_id' => 'mr_nav', 'container_class' => 'mr_nav collapse navbar-collapse', 'menu_class' => 'clearfix', 'menu_id' => 'main_menu' ) ); ``` Is there anyway to add the span tag as above when the menu item has a `sub-menu`?
Ok, figured it out. You need to use a `walker` instance which is passed in as an instance via the `wp_nav_menu` function, like so: ``` wp_nav_menu( array( 'menu' => 'main', 'container' => 'div', 'container_id' => 'mr_nav', 'container_class' => 'mr_nav collapse navbar-collapse', 'menu_class' => 'clearfix', 'menu_id' => 'main_menu', 'walker' => new My_Walker, ) ); ``` Then you put the following inside your `functions.php` file: ``` class My_Walker extends Walker_Nav_Menu { function start_el(&$output, $item, $depth, $args) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $class_names .'>'; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; /** This filter is documented in wp-includes/post-template.php */ $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= ($this->has_children) ? ' <span class="fa fa-angle-down"></span>' : ''; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } } ``` To break it down... the above is basically a copy of the default `Walker_Nav_Menu` method with one small addition: ``` $item_output .= '<a'. $attributes .'>'; /** This filter is documented in wp-includes/post-template.php */ $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= ($this->has_children) ? ' <span class="fa fa-angle-down"></span>' : ''; $item_output .= '</a>'; ``` In the above code I merely added the line: ``` $item_output .= ($this->has_children) ? ' <span class="fa fa-angle-down"></span>' : ''; ``` ...before the closing `</a>` was added. That's it! :)
189,728
<p>I have a site where YouTube video IDs are used as a post's title. This mostly works fine, except some valid YouTube video IDs have two consecutive dashes. For example, "j--c0wP54JU" is getting automatically modified by wordpress to be "j-c0wP54JU" (Note the single dash).</p> <p>When I try to manually edit the permalink from the Edit Post page, it keeps removing the 2 consecutive dashes when I press OK.</p> <p>Where can I disable this part of Wordpress that changes the URLs to be "web safe"?</p>
[ { "answer_id": 189729, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Regarding the <strong>why</strong> part, I think I've traced this to the following <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378\">line</a>:</p>\n\n<pre><code>$title = preg_replace('|-+|', '-', $title);\n</code></pre>\n\n<p>within the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378\"><code>sanitize_title_with_dashes()</code></a> function. </p>\n\n<p>It's added to the <code>santize_title()</code> via the filter:</p>\n\n<pre><code>add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 );\n</code></pre>\n\n<p>but I wouldn't recommend removing it totally.</p>\n\n<h2>Update:</h2>\n\n<p>Here's a quick and dirty way around this:</p>\n\n<pre><code>add_filter( 'sanitize_title', function( $title )\n{\n return str_replace( '--', 'twotempdashes', $title );\n},9 );\n\n\nadd_filter( 'sanitize_title', function( $title )\n{\n return str_replace( 'twotempdashes', '--', $title );\n},11 );\n</code></pre>\n\n<p>where we replace two dashes into some temporary string, before the <code>sanitize_title_with_dashes</code> is activated and then replace the string again to two dashes afterwards. We could adjust this to the more general case, but you get the idea ;-)</p>\n" }, { "answer_id": 189731, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The culprit here is <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title/\" rel=\"nofollow\"><code>sanitize_title()</code></a> via the <a href=\"https://developer.wordpress.org/reference/hooks/sanitize_title/\" rel=\"nofollow\"><code>sanitize_title</code></a> hook. The function hooked to it is <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/\" rel=\"nofollow\"><code>sanitize_title_with_dashes()</code></a>; I see @birgire tracked it down too, as it can be seen in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L186\" rel=\"nofollow\"><code>wp-includes/default-filters.php</code></a>. </p>\n\n<blockquote>\n <p>add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 );</p>\n</blockquote>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/remove_filter/\" rel=\"nofollow\"><code>remove_filter()</code></a> to do just that.</p>\n\n<pre><code>remove_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10 );\n</code></pre>\n\n<p>But <strong>beware</strong>, you are not longer sanitizing your titles now, which really is <strong>not</strong> recommended. @birgire is absolutely right about the why part, but you can't change that easily so I would recommend duplicating <code>sanitize_title_with_dashes()</code>, leaving out the \"bad\" part. Use <code>add_filter()</code> to hook your custom filter function to <code>sanitize_title</code>.</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189728", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49254/" ]
I have a site where YouTube video IDs are used as a post's title. This mostly works fine, except some valid YouTube video IDs have two consecutive dashes. For example, "j--c0wP54JU" is getting automatically modified by wordpress to be "j-c0wP54JU" (Note the single dash). When I try to manually edit the permalink from the Edit Post page, it keeps removing the 2 consecutive dashes when I press OK. Where can I disable this part of Wordpress that changes the URLs to be "web safe"?
Regarding the **why** part, I think I've traced this to the following [line](https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378): ``` $title = preg_replace('|-+|', '-', $title); ``` within the [`sanitize_title_with_dashes()`](https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378) function. It's added to the `santize_title()` via the filter: ``` add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 ); ``` but I wouldn't recommend removing it totally. Update: ------- Here's a quick and dirty way around this: ``` add_filter( 'sanitize_title', function( $title ) { return str_replace( '--', 'twotempdashes', $title ); },9 ); add_filter( 'sanitize_title', function( $title ) { return str_replace( 'twotempdashes', '--', $title ); },11 ); ``` where we replace two dashes into some temporary string, before the `sanitize_title_with_dashes` is activated and then replace the string again to two dashes afterwards. We could adjust this to the more general case, but you get the idea ;-)
189,733
<p>I have been running a network of WordPress sites (Multisite) since version 3.8.1. I've been constantly updating plugins and core. At some point, I discovered that uploading new images yields broken results. </p> <p>When I upload a file it goes to <code>wp-content/blogs.dir/7/files</code>, 7 being the blog id. WordPress, for some reason thinks that it should link to <code>https://siteurl.com/files/file-name.png</code> and therefore all images in Media Library or in newly added content are broken.</p> <p>I do not recall editing any configuration and previously all files went to the directory e.g. <code>wp-content/uploads/sites/7/files/2015/05/</code>. I was guessing that updating some plugin or core caused the behavior, but as I go in the history through a VCS, I cannot restore the previous upload behavior so it hints that the issue might be caused by file permissions, .htaccess or similar. I did try to play around with those as well, but to no success.</p> <p>When looking at the source code, I can't figure out how it was working before. There's a line that defines the upload path to be blogs.dir here <a href="https://github.com/WordPress/WordPress/blob/master/wp-includes/ms-default-constants.php#L31" rel="nofollow">https://github.com/WordPress/WordPress/blob/master/wp-includes/ms-default-constants.php#L31</a></p> <p>I tried overriding these three values</p> <pre><code>define( 'UPLOADBLOGSDIR', 'wp-content/blogs.dir' ); define( 'UPLOADS', UPLOADBLOGSDIR . "/{$wpdb-&gt;blogid}/files/" ); define( 'BLOGUPLOADDIR', WP_CONTENT_DIR . "/blogs.dir/{$wpdb-&gt;blogid}/files/" ); </code></pre> <p>with</p> <pre><code>define( 'UPLOADBLOGSDIR', WP_CONTENT_DIR . '/uploads' ); define( 'UPLOADS', UPLOADBLOGSDIR . "sites/{$wpdb-&gt;blogid}/" ); define( 'BLOGUPLOADDIR', WP_CONTENT_DIR . "/uploads/{$wpdb-&gt;blogid}/" ); </code></pre> <p>but I cannot get the $wpdb->blogid in the wp-config.php so it doesn't work. And still, I can't figure out how it was working before.</p> <p>Any thoughts?</p> <p>P.S Just found out that uploads are working for the top level blog.</p> <p>P.S2 Tried uploading a file in the top level blog. It shows the link to <code>/wp-content/uploads/2015/05/Screen-Shot-2015-05-29-at-09.56.02.png</code> in media browser. Now when I open <code>/wp-includes/ms-files.php?file=2015/05/Screen-Shot-2015-05-29-at-09.56.02.png</code> I get a 404 and when I echo out the file path ms-files.php is trying to include, I get <code>/wp-content/blogs.dir/1/files/2015/05/Screen-Shot-2015-05-29-at-09.56.02.png</code></p>
[ { "answer_id": 189729, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>Regarding the <strong>why</strong> part, I think I've traced this to the following <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378\">line</a>:</p>\n\n<pre><code>$title = preg_replace('|-+|', '-', $title);\n</code></pre>\n\n<p>within the <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378\"><code>sanitize_title_with_dashes()</code></a> function. </p>\n\n<p>It's added to the <code>santize_title()</code> via the filter:</p>\n\n<pre><code>add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 );\n</code></pre>\n\n<p>but I wouldn't recommend removing it totally.</p>\n\n<h2>Update:</h2>\n\n<p>Here's a quick and dirty way around this:</p>\n\n<pre><code>add_filter( 'sanitize_title', function( $title )\n{\n return str_replace( '--', 'twotempdashes', $title );\n},9 );\n\n\nadd_filter( 'sanitize_title', function( $title )\n{\n return str_replace( 'twotempdashes', '--', $title );\n},11 );\n</code></pre>\n\n<p>where we replace two dashes into some temporary string, before the <code>sanitize_title_with_dashes</code> is activated and then replace the string again to two dashes afterwards. We could adjust this to the more general case, but you get the idea ;-)</p>\n" }, { "answer_id": 189731, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>The culprit here is <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title/\" rel=\"nofollow\"><code>sanitize_title()</code></a> via the <a href=\"https://developer.wordpress.org/reference/hooks/sanitize_title/\" rel=\"nofollow\"><code>sanitize_title</code></a> hook. The function hooked to it is <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/\" rel=\"nofollow\"><code>sanitize_title_with_dashes()</code></a>; I see @birgire tracked it down too, as it can be seen in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/default-filters.php#L186\" rel=\"nofollow\"><code>wp-includes/default-filters.php</code></a>. </p>\n\n<blockquote>\n <p>add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 );</p>\n</blockquote>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/remove_filter/\" rel=\"nofollow\"><code>remove_filter()</code></a> to do just that.</p>\n\n<pre><code>remove_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10 );\n</code></pre>\n\n<p>But <strong>beware</strong>, you are not longer sanitizing your titles now, which really is <strong>not</strong> recommended. @birgire is absolutely right about the why part, but you can't change that easily so I would recommend duplicating <code>sanitize_title_with_dashes()</code>, leaving out the \"bad\" part. Use <code>add_filter()</code> to hook your custom filter function to <code>sanitize_title</code>.</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189733", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48751/" ]
I have been running a network of WordPress sites (Multisite) since version 3.8.1. I've been constantly updating plugins and core. At some point, I discovered that uploading new images yields broken results. When I upload a file it goes to `wp-content/blogs.dir/7/files`, 7 being the blog id. WordPress, for some reason thinks that it should link to `https://siteurl.com/files/file-name.png` and therefore all images in Media Library or in newly added content are broken. I do not recall editing any configuration and previously all files went to the directory e.g. `wp-content/uploads/sites/7/files/2015/05/`. I was guessing that updating some plugin or core caused the behavior, but as I go in the history through a VCS, I cannot restore the previous upload behavior so it hints that the issue might be caused by file permissions, .htaccess or similar. I did try to play around with those as well, but to no success. When looking at the source code, I can't figure out how it was working before. There's a line that defines the upload path to be blogs.dir here <https://github.com/WordPress/WordPress/blob/master/wp-includes/ms-default-constants.php#L31> I tried overriding these three values ``` define( 'UPLOADBLOGSDIR', 'wp-content/blogs.dir' ); define( 'UPLOADS', UPLOADBLOGSDIR . "/{$wpdb->blogid}/files/" ); define( 'BLOGUPLOADDIR', WP_CONTENT_DIR . "/blogs.dir/{$wpdb->blogid}/files/" ); ``` with ``` define( 'UPLOADBLOGSDIR', WP_CONTENT_DIR . '/uploads' ); define( 'UPLOADS', UPLOADBLOGSDIR . "sites/{$wpdb->blogid}/" ); define( 'BLOGUPLOADDIR', WP_CONTENT_DIR . "/uploads/{$wpdb->blogid}/" ); ``` but I cannot get the $wpdb->blogid in the wp-config.php so it doesn't work. And still, I can't figure out how it was working before. Any thoughts? P.S Just found out that uploads are working for the top level blog. P.S2 Tried uploading a file in the top level blog. It shows the link to `/wp-content/uploads/2015/05/Screen-Shot-2015-05-29-at-09.56.02.png` in media browser. Now when I open `/wp-includes/ms-files.php?file=2015/05/Screen-Shot-2015-05-29-at-09.56.02.png` I get a 404 and when I echo out the file path ms-files.php is trying to include, I get `/wp-content/blogs.dir/1/files/2015/05/Screen-Shot-2015-05-29-at-09.56.02.png`
Regarding the **why** part, I think I've traced this to the following [line](https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378): ``` $title = preg_replace('|-+|', '-', $title); ``` within the [`sanitize_title_with_dashes()`](https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L1378) function. It's added to the `santize_title()` via the filter: ``` add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 ); ``` but I wouldn't recommend removing it totally. Update: ------- Here's a quick and dirty way around this: ``` add_filter( 'sanitize_title', function( $title ) { return str_replace( '--', 'twotempdashes', $title ); },9 ); add_filter( 'sanitize_title', function( $title ) { return str_replace( 'twotempdashes', '--', $title ); },11 ); ``` where we replace two dashes into some temporary string, before the `sanitize_title_with_dashes` is activated and then replace the string again to two dashes afterwards. We could adjust this to the more general case, but you get the idea ;-)
189,736
<p>I have a large wordpress database:</p> <p>rows in key tables:</p> <blockquote> <p>730K wp_posts<br> 404K wp_terms<br> 752K wp_term_relationships<br> 27K wp_term_taxonomy<br> 1.8 Million wp_postmeta<br></p> </blockquote> <p>The issue is that I have a query <strong>that takes 5 seconds to complete</strong> and I want to optimize the query before adding any caching.</p> <pre><code>mysql&gt; SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = '_Original Post ID' ) LEFT JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND wp_posts.ID NOT IN (731467) AND ( wp_term_relationships.term_taxonomy_id IN (5) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND ( wp_postmeta.post_id IS NULL OR ( mt1.meta_key = '_Original Post ID' AND CAST(mt1.meta_value AS CHAR) = 'deleted' ) ) GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC LIMIT 0, 20; </code></pre> <p>Here is the results:</p> <pre><code>+--------+ | ID | +--------+ | 731451 | | 731405 | | 731403 | | 731397 | | 731391 | | 731385 | | 731375 | | 731363 | | 731361 | | 731353 | | 731347 | | 731345 | | 731335 | | 731331 | | 731304 | | 731300 | | 731284 | | 731273 | | 731258 | | 731254 | +--------+ </code></pre> <p>Doing an explain on the query yields the following information</p> <pre><code>+----+-------------+-----------------------+--------+------------------------------------------------------------+------------------+---------+----------------------------------------+--------+-----------------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-----------------------+--------+------------------------------------------------------------+------------------+---------+----------------------------------------+--------+-----------------------------------------------------------+ | 1 | SIMPLE | wp_term_relationships | range | PRIMARY,term_taxonomy_id | term_taxonomy_id | 16 | NULL | 130445 | Using where; Using index; Using temporary; Using filesort | | 1 | SIMPLE | wp_posts | eq_ref | PRIMARY,post_name,type_status_date,post_parent,post_author | PRIMARY | 8 | mydatabase.wp_term_relationships.object_id | 1 | Using where | | 1 | SIMPLE | wp_postmeta | ref | post_id,meta_key | post_id | 8 | mydatabase.wp_term_relationships.object_id | 1 | Using where | | 1 | SIMPLE | mt1 | ref | post_id | post_id | 8 | mydatabase.wp_term_relationships.object_id | 1 | Using where | +----+-------------+-----------------------+--------+------------------------------------------------------------+------------------+---------+----------------------------------------+--------+-----------------------------------------------------------+ </code></pre> <p>How can I optimize this query to load faster? I thinking a custom index would be the way to go but not sure on which fields. Also I tried to order the results wp_posts.ID DESC but get the same time to execute the query.</p>
[ { "answer_id": 189781, "author": "Kladskull", "author_id": 63596, "author_profile": "https://wordpress.stackexchange.com/users/63596", "pm_score": 3, "selected": false, "text": "<p>I had the exact same issue. The problem is not one that can be fixed without modifying some code that you probably shouldn't (or perhaps writing a filter or a 'drop-in'). The issue is the CAST directive in the SQL statement. It CASTS the entire table before it does anything, with the amount of records you have, its going to take a while. </p>\n\n<p>Capture the query, remove the following <code>\"AND CAST(mt1.meta_value AS CHAR) = 'deleted'\"</code> and run it, it should be a lot quicker now. </p>\n\n<p>Edit: (Correction) change the query to <code>\"AND mt1.meta_value = 'deleted'\"</code></p>\n\n<p>I have no idea what the developers were thinking when they added that useless CAST, with MySQL it works fine without it (TEXT is no different than CHAR except the size). I am sure there are some edge cases where removing it will not give the desired results, but I have yet to find one.</p>\n\n<p>Long live Wordpress SQL X)</p>\n" }, { "answer_id": 191251, "author": "Ranknoodle", "author_id": 51263, "author_profile": "https://wordpress.stackexchange.com/users/51263", "pm_score": 3, "selected": true, "text": "<p>So what I'm going to do going forward if I use wordpress for this project is to create a reverse post id index. I don't think this is the \"correct\" answer and some people will definitely outright disagree with this approach but this is working for me in production.</p>\n\n<p>I got the idea from reading this blog post here:</p>\n\n<p><a href=\"https://www.igvita.com/2007/08/20/pseudo-reverse-indexes-in-mysql/\" rel=\"nofollow\">https://www.igvita.com/2007/08/20/pseudo-reverse-indexes-in-mysql/</a></p>\n\n<blockquote>\n <p>As I recently discovered, MySQL currently only supports storage of index values in ascending order....It took all of three weeks for AideRSS to hit the 3 million plus indexed blog posts, and in the process I could feel the site getting more sluggish: the descending order by clause was killing us. In the worst case, merging a union of several queries meant the performance hit of a filesort operation! </p>\n</blockquote>\n\n<p>Because of this limitation with mysql, the following order &amp; sorting functions are the bottleneck in the query.</p>\n\n<pre><code>GROUP BY wp_posts.ID\nORDER BY wp_posts.ID DESC\n</code></pre>\n\n<p>However removing those conditions the query will return in 20ms from an average of 5-15 seconds in production. However the issue is that the posts are ordered by oldest to newest. What I want is newest to oldest.</p>\n\n<pre><code>SELECT wp_posts.*\nFROM wp_posts\nWHERE wp_posts.ID IN( \nSELECT distinct(ID) \nFROM wp_posts \nINNER JOIN wp_term_relationships \nON (wp_posts.ID = wp_term_relationships.object_id) \nLEFT JOIN wp_postmeta \nON (wp_posts.ID = wp_postmeta.post_id \nAND wp_postmeta.meta_key = '_Original Post ID' ) \nLEFT JOIN wp_postmeta AS mt1 \nON ( wp_posts.ID = mt1.post_id ) \nWHERE wp_posts.ID NOT IN (795025) \nAND ( wp_term_relationships.term_taxonomy_id IN (1) ) \nAND wp_posts.post_type = 'post' \nAND (wp_posts.post_status = 'publish' \nOR wp_posts.post_status = 'private') \nAND ( wp_postmeta.post_id IS NULL \nOR ( mt1.meta_key = '_Original Post ID' \nAND CAST(mt1.meta_value AS CHAR) = 'deleted' ) ) ) limit 0, 20;\n</code></pre>\n\n<p>So again going back to this post here: <a href=\"https://www.igvita.com/2007/08/20/pseudo-reverse-indexes-in-mysql/\" rel=\"nofollow\">https://www.igvita.com/2007/08/20/pseudo-reverse-indexes-in-mysql/</a></p>\n\n<blockquote>\n <p>Following Peter Zaitsev's advice on faking a reverse index, I decided to sidestep our problem by creating a separate reverse timestamp for the publication time of an indexed blog post. The trick is, since all indexes are stored in ascending order, instead of storing the publication date, you need to store a 'countdown' value from some date in the future. A few SQL queries will do the trick:</p>\n</blockquote>\n\n<p>Instead of storing the post creation date \"reversed\", I decided to store the Post ID in a negative format in the wp_posts table.</p>\n\n<p>So I added in mysql in my wordpress database an additional column to the wp_posts table. This new column stores a int negative number.</p>\n\n<pre><code>alter table wp_posts add column reverse_post_id int;\n</code></pre>\n\n<p>Update current posts to have this reverse number for new column:</p>\n\n<pre><code> update wp_posts set reverse_post_id = (ID/ -1);\n</code></pre>\n\n<p>I then create an index on this new reverse_post_id:</p>\n\n<pre><code> create index reverse_post_id_index on wp_posts(post_type,post_status,reverse_post_id);\n</code></pre>\n\n<p>Currently I insert posts programmatically via an custom api interface so I create the reverse post id after insertion. I will be adding a hook to create the reverse_post_id in wordpress after inserting a post through the interface.</p>\n\n<p>Im also going to add a mysql scheduled event to run at some interval to update wp_posts where reverse_post_id is null.</p>\n\n<p>The final query looks like this and runs in under 20 ms or less in production:</p>\n\n<pre><code>SELECT wp_posts.*\nFROM wp_posts\nWHERE wp_posts.ID IN( \nSELECT distinct(ID) \nFROM wp_posts **force index (reverse_post_id_index)** \nINNER JOIN wp_term_relationships \nON (wp_posts.ID = wp_term_relationships.object_id) \nLEFT JOIN wp_postmeta \nON (wp_posts.ID = wp_postmeta.post_id \nAND wp_postmeta.meta_key = '_Original Post ID' ) \nLEFT JOIN wp_postmeta AS mt1 \nON ( wp_posts.ID = mt1.post_id ) \nWHERE wp_posts.ID NOT IN (795025) \nAND ( wp_term_relationships.term_taxonomy_id IN (1) ) \nAND wp_posts.post_type = 'post' \nAND (wp_posts.post_status = 'publish' \nOR wp_posts.post_status = 'private') \nAND ( wp_postmeta.post_id IS NULL \nOR ( mt1.meta_key = '_Original Post ID' \nAND CAST(mt1.meta_value AS CHAR) = 'deleted' ) ) ) limit 0, 20;\n</code></pre>\n\n<p>Notice the addition of \"<strong>force index (reverse_post_id_index)</strong>\" this returns the wp_posts in desc order newest to oldest without \"order by\" operation. The caveat is that the reverese_post_id can not be null.</p>\n\n<p>Again this is probably not the correct answer but the answer I found to make it work for me and my situation.</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189736", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51263/" ]
I have a large wordpress database: rows in key tables: > > 730K wp\_posts > 404K wp\_terms > 752K wp\_term\_relationships > 27K > wp\_term\_taxonomy > > 1.8 Million wp\_postmeta > > > > The issue is that I have a query **that takes 5 seconds to complete** and I want to optimize the query before adding any caching. ``` mysql> SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = '_Original Post ID' ) LEFT JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND wp_posts.ID NOT IN (731467) AND ( wp_term_relationships.term_taxonomy_id IN (5) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND ( wp_postmeta.post_id IS NULL OR ( mt1.meta_key = '_Original Post ID' AND CAST(mt1.meta_value AS CHAR) = 'deleted' ) ) GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC LIMIT 0, 20; ``` Here is the results: ``` +--------+ | ID | +--------+ | 731451 | | 731405 | | 731403 | | 731397 | | 731391 | | 731385 | | 731375 | | 731363 | | 731361 | | 731353 | | 731347 | | 731345 | | 731335 | | 731331 | | 731304 | | 731300 | | 731284 | | 731273 | | 731258 | | 731254 | +--------+ ``` Doing an explain on the query yields the following information ``` +----+-------------+-----------------------+--------+------------------------------------------------------------+------------------+---------+----------------------------------------+--------+-----------------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-----------------------+--------+------------------------------------------------------------+------------------+---------+----------------------------------------+--------+-----------------------------------------------------------+ | 1 | SIMPLE | wp_term_relationships | range | PRIMARY,term_taxonomy_id | term_taxonomy_id | 16 | NULL | 130445 | Using where; Using index; Using temporary; Using filesort | | 1 | SIMPLE | wp_posts | eq_ref | PRIMARY,post_name,type_status_date,post_parent,post_author | PRIMARY | 8 | mydatabase.wp_term_relationships.object_id | 1 | Using where | | 1 | SIMPLE | wp_postmeta | ref | post_id,meta_key | post_id | 8 | mydatabase.wp_term_relationships.object_id | 1 | Using where | | 1 | SIMPLE | mt1 | ref | post_id | post_id | 8 | mydatabase.wp_term_relationships.object_id | 1 | Using where | +----+-------------+-----------------------+--------+------------------------------------------------------------+------------------+---------+----------------------------------------+--------+-----------------------------------------------------------+ ``` How can I optimize this query to load faster? I thinking a custom index would be the way to go but not sure on which fields. Also I tried to order the results wp\_posts.ID DESC but get the same time to execute the query.
So what I'm going to do going forward if I use wordpress for this project is to create a reverse post id index. I don't think this is the "correct" answer and some people will definitely outright disagree with this approach but this is working for me in production. I got the idea from reading this blog post here: <https://www.igvita.com/2007/08/20/pseudo-reverse-indexes-in-mysql/> > > As I recently discovered, MySQL currently only supports storage of index values in ascending order....It took all of three weeks for AideRSS to hit the 3 million plus indexed blog posts, and in the process I could feel the site getting more sluggish: the descending order by clause was killing us. In the worst case, merging a union of several queries meant the performance hit of a filesort operation! > > > Because of this limitation with mysql, the following order & sorting functions are the bottleneck in the query. ``` GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC ``` However removing those conditions the query will return in 20ms from an average of 5-15 seconds in production. However the issue is that the posts are ordered by oldest to newest. What I want is newest to oldest. ``` SELECT wp_posts.* FROM wp_posts WHERE wp_posts.ID IN( SELECT distinct(ID) FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = '_Original Post ID' ) LEFT JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE wp_posts.ID NOT IN (795025) AND ( wp_term_relationships.term_taxonomy_id IN (1) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND ( wp_postmeta.post_id IS NULL OR ( mt1.meta_key = '_Original Post ID' AND CAST(mt1.meta_value AS CHAR) = 'deleted' ) ) ) limit 0, 20; ``` So again going back to this post here: <https://www.igvita.com/2007/08/20/pseudo-reverse-indexes-in-mysql/> > > Following Peter Zaitsev's advice on faking a reverse index, I decided to sidestep our problem by creating a separate reverse timestamp for the publication time of an indexed blog post. The trick is, since all indexes are stored in ascending order, instead of storing the publication date, you need to store a 'countdown' value from some date in the future. A few SQL queries will do the trick: > > > Instead of storing the post creation date "reversed", I decided to store the Post ID in a negative format in the wp\_posts table. So I added in mysql in my wordpress database an additional column to the wp\_posts table. This new column stores a int negative number. ``` alter table wp_posts add column reverse_post_id int; ``` Update current posts to have this reverse number for new column: ``` update wp_posts set reverse_post_id = (ID/ -1); ``` I then create an index on this new reverse\_post\_id: ``` create index reverse_post_id_index on wp_posts(post_type,post_status,reverse_post_id); ``` Currently I insert posts programmatically via an custom api interface so I create the reverse post id after insertion. I will be adding a hook to create the reverse\_post\_id in wordpress after inserting a post through the interface. Im also going to add a mysql scheduled event to run at some interval to update wp\_posts where reverse\_post\_id is null. The final query looks like this and runs in under 20 ms or less in production: ``` SELECT wp_posts.* FROM wp_posts WHERE wp_posts.ID IN( SELECT distinct(ID) FROM wp_posts **force index (reverse_post_id_index)** INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = '_Original Post ID' ) LEFT JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE wp_posts.ID NOT IN (795025) AND ( wp_term_relationships.term_taxonomy_id IN (1) ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') AND ( wp_postmeta.post_id IS NULL OR ( mt1.meta_key = '_Original Post ID' AND CAST(mt1.meta_value AS CHAR) = 'deleted' ) ) ) limit 0, 20; ``` Notice the addition of "**force index (reverse\_post\_id\_index)**" this returns the wp\_posts in desc order newest to oldest without "order by" operation. The caveat is that the reverese\_post\_id can not be null. Again this is probably not the correct answer but the answer I found to make it work for me and my situation.
189,739
<p>I've made a custom post type "brands". I have a custom template that display's these brands on this page: <a href="http://www.southernms.com/new/brands/" rel="nofollow">http://www.southernms.com/new/brands/</a></p> <p>I also want these brands added to the homepage. So I am using a widget to show them on the homepage: <a href="http://www.southernms.com/new/" rel="nofollow">http://www.southernms.com/new/</a></p> <p>My problem is. On the brands page, you can see the logo's and nothing else. <strong><em>However</em></strong> on the homepage it shows the logo's yes, but at the bottom of the page it also shows the name of all the brands like they are posts. I am using the same code to display the brand logos in my custom template, as I am in the widget. So I'm not sure why one of them is adding extra code I don't want and the other isn't. </p> <p>Any suggestions?</p> <p>Here's my code:</p> <pre><code>&lt;?php global $theme; query_posts(array( 'post_type' =&gt; 'brands', 'order' =&gt; 'ASC', 'posts_per_page' =&gt; 99 )); ?&gt; &lt;ul class="brands"&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php printf( esc_attr__( 'Permalink to %s', 'themater' ), the_title_attribute( 'echo=0' ) ); ?&gt;" rel="bookmark"&gt;&lt;?php the_post_thumbnail( array(125,125) ); ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 189743, "author": "KVDD", "author_id": 54304, "author_profile": "https://wordpress.stackexchange.com/users/54304", "pm_score": 1, "selected": false, "text": "<p>This is what I changed it to, and it seems to be working on the Homepage without extra added code.</p>\n\n<pre><code>&lt;ul class=\"brands\"&gt;\n &lt;?php\n global $post;\n $posts = get_posts( array( 'numberposts' =&gt; 99, 'post_type' =&gt; 'brands', 'order' =&gt; 'ASC' ) );\n if( $posts ):\n foreach( $posts as $post ) : \n setup_postdata($post); ?&gt;\n\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_post_thumbnail( array(125,125) ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n\n &lt;?php endforeach; \n wp_reset_postdata(); \n endif; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 189754, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>As already mentioned, don't use <code>query_posts()</code>. Even the WordPress docs state this: </p>\n\n<blockquote>\n <p>Note: <strong><em>This function isn't meant to be used by plugins or themes</em></strong>. As\n explained later, there are better, more performant options to alter\n the main query. query_posts() is overly simplistic and problematic way\n to modify main query of a page by replacing it with new instance of\n the query. It is inefficient (re-runs SQL queries) and will outright\n fail in some circumstances (especially often when dealing with posts\n pagination). Any modern WP code should use more reliable methods, like\n making use of pre_get_posts hook, for this purpose. </p>\n \n <p><a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/query_posts</a></p>\n</blockquote>\n\n<p>The problems with that function are many, including clobbering the main query which can cause unexpected issues with plugins and theme code and its use increases the number of queries to the database thus negatively effecting the page load time. I suspect the fact that you are clobbering the main query is the cause of your issue. </p>\n\n<p>If this is the main query of the page, then you need: </p>\n\n<pre><code>function pregp_wpse_189739($qry) {\n if (is_main_query()) {\n $qry-&gt;set('post_type','brands');\n $qry-&gt;set('posts_per_page',99);\n $qry-&gt;set('order','ASC');\n }\n}\nadd_action('pre_get_posts','pregp_wpse_189739');\n</code></pre>\n\n<p>If it is not the main query then:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'brands',\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; 99\n);\n$my_query = new WP_Query($args);\nif ($my_query-&gt;have_posts()) {\n while ($my_query-&gt;have_posts()) {\n $my_query-&gt;the_post();\n // you Loop code\n }\n}\nwp_reset_postdata(); \n</code></pre>\n\n<p>I find <code>get_posts()</code> to be a bit cumbersome and awkward as you have to code some of the loop yourself, but it should work though not all Loop hooks will fire.</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189739", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54304/" ]
I've made a custom post type "brands". I have a custom template that display's these brands on this page: <http://www.southernms.com/new/brands/> I also want these brands added to the homepage. So I am using a widget to show them on the homepage: <http://www.southernms.com/new/> My problem is. On the brands page, you can see the logo's and nothing else. ***However*** on the homepage it shows the logo's yes, but at the bottom of the page it also shows the name of all the brands like they are posts. I am using the same code to display the brand logos in my custom template, as I am in the widget. So I'm not sure why one of them is adding extra code I don't want and the other isn't. Any suggestions? Here's my code: ``` <?php global $theme; query_posts(array( 'post_type' => 'brands', 'order' => 'ASC', 'posts_per_page' => 99 )); ?> <ul class="brands"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <li> <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'themater' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail( array(125,125) ); ?></a> </li> <?php endwhile; ?> </ul> <?php endif; ?> ```
As already mentioned, don't use `query_posts()`. Even the WordPress docs state this: > > Note: ***This function isn't meant to be used by plugins or themes***. As > explained later, there are better, more performant options to alter > the main query. query\_posts() is overly simplistic and problematic way > to modify main query of a page by replacing it with new instance of > the query. It is inefficient (re-runs SQL queries) and will outright > fail in some circumstances (especially often when dealing with posts > pagination). Any modern WP code should use more reliable methods, like > making use of pre\_get\_posts hook, for this purpose. > > > <https://codex.wordpress.org/Function_Reference/query_posts> > > > The problems with that function are many, including clobbering the main query which can cause unexpected issues with plugins and theme code and its use increases the number of queries to the database thus negatively effecting the page load time. I suspect the fact that you are clobbering the main query is the cause of your issue. If this is the main query of the page, then you need: ``` function pregp_wpse_189739($qry) { if (is_main_query()) { $qry->set('post_type','brands'); $qry->set('posts_per_page',99); $qry->set('order','ASC'); } } add_action('pre_get_posts','pregp_wpse_189739'); ``` If it is not the main query then: ``` $args = array( 'post_type' => 'brands', 'order' => 'ASC', 'posts_per_page' => 99 ); $my_query = new WP_Query($args); if ($my_query->have_posts()) { while ($my_query->have_posts()) { $my_query->the_post(); // you Loop code } } wp_reset_postdata(); ``` I find `get_posts()` to be a bit cumbersome and awkward as you have to code some of the loop yourself, but it should work though not all Loop hooks will fire.
189,746
<p>I have been looking around for the past few hours and I am starting to be kind of desperate...</p> <p>I have created a plugin to add my custom post type "project" (making a new portfolio)...</p> <p>In this plugin, I have the function file, and a template file single-project.php and also a template part folder with content-single-project.php within it. On that part, everything is working fine just as I want...</p> <p>To be able to load the template file from the plugin folder, I did the following in the function file: </p> <pre><code>function get_custom_post_type_single_template($single_template) { global $post; if ($post-&gt;post_type == 'project') { $single_template = dirname( __FILE__ ) . '/templates/single-project.php'; } return $single_template; } function get_custom_post_type_archive_template($archive_template) { global $post; if ($post-&gt;post_type == 'project') { $archive_template = dirname( __FILE__ ) . '/templates/archive-project.php'; } return $archive_template; } function get_custom_post_type_category_template($category_template) { global $post; if ($post-&gt;post_type == 'project') { $category_template = dirname( __FILE__ ) . '/templates/category-project.php'; } return $category_template; } add_filter( 'single_template', 'get_custom_post_type_single_template' ); add_filter( 'archive_template', 'get_custom_post_type_archive_template' ); add_filter( 'category_template', 'get_custom_post_type_category_template' ); </code></pre> <p>Since it is working fine for the single template file, I don't see why I have a problem making it work for a category (or even archive) page... The category is not a custom taxonomy, it is the default (if I'm correct.. ) Category of Wordpress, same for Tags...</p> <p>They are added in the project CPT while registering the new post type in the function file of the plugin, like so:</p> <pre><code> 'taxonomies' =&gt; array( 'post_tag', 'category' ), </code></pre> <p>They are "classic" right ?</p> <p>Well... My primary navigation is displaying those categories (I have 3, Frontend, Design, Apps... ). When clicking on any of those links, redirecting to an URL like "root/category/post-name/", the 404 template is loaded, not the category template from the plugin folder, neither the one from the theme folder, neither archive... etc. Just the 404 template.</p> <p>My permalinks are flush, I tried all the posts I have found online and nothing is changing, still not working...</p> <p>I hope you guys will understand my english and will be able to help, Feel free to ask any question, Thank you for your time.</p>
[ { "answer_id": 189743, "author": "KVDD", "author_id": 54304, "author_profile": "https://wordpress.stackexchange.com/users/54304", "pm_score": 1, "selected": false, "text": "<p>This is what I changed it to, and it seems to be working on the Homepage without extra added code.</p>\n\n<pre><code>&lt;ul class=\"brands\"&gt;\n &lt;?php\n global $post;\n $posts = get_posts( array( 'numberposts' =&gt; 99, 'post_type' =&gt; 'brands', 'order' =&gt; 'ASC' ) );\n if( $posts ):\n foreach( $posts as $post ) : \n setup_postdata($post); ?&gt;\n\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_post_thumbnail( array(125,125) ); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n\n &lt;?php endforeach; \n wp_reset_postdata(); \n endif; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 189754, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>As already mentioned, don't use <code>query_posts()</code>. Even the WordPress docs state this: </p>\n\n<blockquote>\n <p>Note: <strong><em>This function isn't meant to be used by plugins or themes</em></strong>. As\n explained later, there are better, more performant options to alter\n the main query. query_posts() is overly simplistic and problematic way\n to modify main query of a page by replacing it with new instance of\n the query. It is inefficient (re-runs SQL queries) and will outright\n fail in some circumstances (especially often when dealing with posts\n pagination). Any modern WP code should use more reliable methods, like\n making use of pre_get_posts hook, for this purpose. </p>\n \n <p><a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/query_posts</a></p>\n</blockquote>\n\n<p>The problems with that function are many, including clobbering the main query which can cause unexpected issues with plugins and theme code and its use increases the number of queries to the database thus negatively effecting the page load time. I suspect the fact that you are clobbering the main query is the cause of your issue. </p>\n\n<p>If this is the main query of the page, then you need: </p>\n\n<pre><code>function pregp_wpse_189739($qry) {\n if (is_main_query()) {\n $qry-&gt;set('post_type','brands');\n $qry-&gt;set('posts_per_page',99);\n $qry-&gt;set('order','ASC');\n }\n}\nadd_action('pre_get_posts','pregp_wpse_189739');\n</code></pre>\n\n<p>If it is not the main query then:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'brands',\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; 99\n);\n$my_query = new WP_Query($args);\nif ($my_query-&gt;have_posts()) {\n while ($my_query-&gt;have_posts()) {\n $my_query-&gt;the_post();\n // you Loop code\n }\n}\nwp_reset_postdata(); \n</code></pre>\n\n<p>I find <code>get_posts()</code> to be a bit cumbersome and awkward as you have to code some of the loop yourself, but it should work though not all Loop hooks will fire.</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189746", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73792/" ]
I have been looking around for the past few hours and I am starting to be kind of desperate... I have created a plugin to add my custom post type "project" (making a new portfolio)... In this plugin, I have the function file, and a template file single-project.php and also a template part folder with content-single-project.php within it. On that part, everything is working fine just as I want... To be able to load the template file from the plugin folder, I did the following in the function file: ``` function get_custom_post_type_single_template($single_template) { global $post; if ($post->post_type == 'project') { $single_template = dirname( __FILE__ ) . '/templates/single-project.php'; } return $single_template; } function get_custom_post_type_archive_template($archive_template) { global $post; if ($post->post_type == 'project') { $archive_template = dirname( __FILE__ ) . '/templates/archive-project.php'; } return $archive_template; } function get_custom_post_type_category_template($category_template) { global $post; if ($post->post_type == 'project') { $category_template = dirname( __FILE__ ) . '/templates/category-project.php'; } return $category_template; } add_filter( 'single_template', 'get_custom_post_type_single_template' ); add_filter( 'archive_template', 'get_custom_post_type_archive_template' ); add_filter( 'category_template', 'get_custom_post_type_category_template' ); ``` Since it is working fine for the single template file, I don't see why I have a problem making it work for a category (or even archive) page... The category is not a custom taxonomy, it is the default (if I'm correct.. ) Category of Wordpress, same for Tags... They are added in the project CPT while registering the new post type in the function file of the plugin, like so: ``` 'taxonomies' => array( 'post_tag', 'category' ), ``` They are "classic" right ? Well... My primary navigation is displaying those categories (I have 3, Frontend, Design, Apps... ). When clicking on any of those links, redirecting to an URL like "root/category/post-name/", the 404 template is loaded, not the category template from the plugin folder, neither the one from the theme folder, neither archive... etc. Just the 404 template. My permalinks are flush, I tried all the posts I have found online and nothing is changing, still not working... I hope you guys will understand my english and will be able to help, Feel free to ask any question, Thank you for your time.
As already mentioned, don't use `query_posts()`. Even the WordPress docs state this: > > Note: ***This function isn't meant to be used by plugins or themes***. As > explained later, there are better, more performant options to alter > the main query. query\_posts() is overly simplistic and problematic way > to modify main query of a page by replacing it with new instance of > the query. It is inefficient (re-runs SQL queries) and will outright > fail in some circumstances (especially often when dealing with posts > pagination). Any modern WP code should use more reliable methods, like > making use of pre\_get\_posts hook, for this purpose. > > > <https://codex.wordpress.org/Function_Reference/query_posts> > > > The problems with that function are many, including clobbering the main query which can cause unexpected issues with plugins and theme code and its use increases the number of queries to the database thus negatively effecting the page load time. I suspect the fact that you are clobbering the main query is the cause of your issue. If this is the main query of the page, then you need: ``` function pregp_wpse_189739($qry) { if (is_main_query()) { $qry->set('post_type','brands'); $qry->set('posts_per_page',99); $qry->set('order','ASC'); } } add_action('pre_get_posts','pregp_wpse_189739'); ``` If it is not the main query then: ``` $args = array( 'post_type' => 'brands', 'order' => 'ASC', 'posts_per_page' => 99 ); $my_query = new WP_Query($args); if ($my_query->have_posts()) { while ($my_query->have_posts()) { $my_query->the_post(); // you Loop code } } wp_reset_postdata(); ``` I find `get_posts()` to be a bit cumbersome and awkward as you have to code some of the loop yourself, but it should work though not all Loop hooks will fire.
189,758
<p>I would like to know How can i redirect users to their profile after they log in to my website.</p> <p>Right now, when users log in, they get riderected to the home page but i would like for them to get redirected to their respective profile.</p> <p>thanks in advance </p>
[ { "answer_id": 189771, "author": "flomei", "author_id": 65455, "author_profile": "https://wordpress.stackexchange.com/users/65455", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>wp_authenticate</code>-hook (see <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_authenticate\" rel=\"nofollow\">Codex</a>) to trigger a function, when a user was successfully logged in and then use <code>wp_redirect</code> (see <a href=\"https://codex.wordpress.org/Function_Reference/wp_redirect\" rel=\"nofollow\">Codex</a>) to bringt him to a specific page.</p>\n\n<pre><code>add_action ('wp_authenticate' , 'redirect_to_profile');\n\nfunction redirect_to_profile() {\n $user_profile_url = 'getthisfromwhereever...';\n wp_redirect($user_profile_url);\n exit;\n}\n</code></pre>\n" }, { "answer_id": 189773, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>function custom_user_login_redirect( redirect_to, $redirect_to_raw, $user ) {\n $redirect_to = bp_loggedin_user_domain();\n return $redirect_to;\n}\nadd_filter('bp_login_redirect','custom_user_login_redirect',10,3);\n</code></pre>\n" }, { "answer_id": 198133, "author": "jpussacq", "author_id": 68189, "author_profile": "https://wordpress.stackexchange.com/users/68189", "pm_score": 0, "selected": false, "text": "<p>You can try <a href=\"https://wordpress.org/plugins/buddypress-login-redirect\" rel=\"nofollow noreferrer\">BP Login Redirect</a></p>\n\n<p>Plugin description: </p>\n\n<blockquote>\n <p>Allows to decide buddypress website admins where their users should\n land after log in</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/Lc7xT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Lc7xT.png\" alt=\"enter image description here\"></a></p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189758", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73798/" ]
I would like to know How can i redirect users to their profile after they log in to my website. Right now, when users log in, they get riderected to the home page but i would like for them to get redirected to their respective profile. thanks in advance
Try: ``` function custom_user_login_redirect( redirect_to, $redirect_to_raw, $user ) { $redirect_to = bp_loggedin_user_domain(); return $redirect_to; } add_filter('bp_login_redirect','custom_user_login_redirect',10,3); ```
189,760
<p>How do I find out which taxonomy triggered the save?</p> <pre><code>add_action ( 'edited_' . $taxonomy-&gt;name, 'save_taxonomy' ); function save_taxonomy( $term_id ) { $term = get_term( $term_id, $taxonomy ); // Where can I get the taxonomy? } </code></pre>
[ { "answer_id": 189762, "author": "Mark", "author_id": 8757, "author_profile": "https://wordpress.stackexchange.com/users/8757", "pm_score": 1, "selected": false, "text": "<p>This seems to work, don't know if it's the correct approach. </p>\n\n<pre><code>add_action ( 'edited_' . $taxonomy-&gt;name, function( $term_id ) use ( $taxonomy ) {\n $term = get_term( $term_id, $taxonomy-&gt;name ); \n});\n</code></pre>\n" }, { "answer_id": 189763, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 0, "selected": false, "text": "<p>Just use the action <code>edited_term</code> instead. It fires immediately before <code>edited_$taxonomy</code> and you get the taxonomy as an argument.</p>\n\n<pre><code>add_action( 'edited_term', function( $term_id, $tt_id, $taxonomy ) {\n // Do something.\n}, 10, 3 );\n</code></pre>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189760", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8757/" ]
How do I find out which taxonomy triggered the save? ``` add_action ( 'edited_' . $taxonomy->name, 'save_taxonomy' ); function save_taxonomy( $term_id ) { $term = get_term( $term_id, $taxonomy ); // Where can I get the taxonomy? } ```
This seems to work, don't know if it's the correct approach. ``` add_action ( 'edited_' . $taxonomy->name, function( $term_id ) use ( $taxonomy ) { $term = get_term( $term_id, $taxonomy->name ); }); ```
189,767
<p>I am looking for a simple clean solution when someone visits my <strong>homepage</strong> with a mobile device. Should I use something like Mobile Detect? I've seen many plugins with lots of downvotes or crashing.</p> <p>Is it otherwise possible to only add a javascript thingie on the homepage only?</p> <pre><code>if ('ontouchstart' in window) window.location = 'http://someurl.com/single/page'; </code></pre>
[ { "answer_id": 189803, "author": "tushonline", "author_id": 15946, "author_profile": "https://wordpress.stackexchange.com/users/15946", "pm_score": -1, "selected": false, "text": "<p>Javascript Thingie!! \nYou should have tried Mobile Detect first. That should suffice your requirement. If you need more help using the plugin, consider posting on their support forum on WP repo. </p>\n" }, { "answer_id": 189815, "author": "tutoground", "author_id": 57371, "author_profile": "https://wordpress.stackexchange.com/users/57371", "pm_score": 0, "selected": false, "text": "<p>I hope it will help you to detect</p>\n\n<pre><code>var isMobile = {\nAndroid: function() {\n return navigator.userAgent.match(/Android/i);\n},\nBlackBerry: function() {\n return navigator.userAgent.match(/BlackBerry/i);\n},\niOS: function() {\n return navigator.userAgent.match(/iPhone|iPad|iPod/i);\n},\nOpera: function() {\n return navigator.userAgent.match(/Opera Mini/i);\n},\nWindows: function() {\n return navigator.userAgent.match(/IEMobile/i);\n},\nany: function() {\n return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());\n}\n</code></pre>\n\n<p>};</p>\n\n<pre><code>if(isMobile.any()) { alert(\"This is a Mobile Device\");}\n</code></pre>\n\n<p>You can read more about it here.\n<a href=\"http://jstricks.com/detect-mobile-devices-javascript-jquery/\" rel=\"nofollow\">http://jstricks.com/detect-mobile-devices-javascript-jquery/</a></p>\n" }, { "answer_id": 189817, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 1, "selected": true, "text": "<p>You could use <a href=\"https://codex.wordpress.org/Function_Reference/wp_is_mobile\" rel=\"nofollow\"><code>wp_is_mobile</code></a> with <a href=\"https://codex.wordpress.org/Function_Reference/wp_redirect\" rel=\"nofollow\"><code>wp_redirect</code></a></p>\n\n<pre><code>if ( wp_is_mobile() AND is_front_page() ) {\n wp_redirect( $location, $status );\nexit;\n}\n</code></pre>\n\n<p>You can add the js directly to a front-page.php or home.php file or <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\"><code>enqueue</code></a> it directly from either file.</p>\n\n<p>Example:</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'load_script');\nfunction load_script(){\n wp_enqueue_script( 'script-handle', get_stylesheet_directory_uri() . '/js/your-script.js', array( 'jquery' ) );\n}\n</code></pre>\n" }, { "answer_id": 255870, "author": "imsolutionsgroup", "author_id": 99135, "author_profile": "https://wordpress.stackexchange.com/users/99135", "pm_score": 0, "selected": false, "text": "<p>If you're using wordpress, give this plugin a try - <a href=\"http://www.ultimate-wordpress-mobile-redirect.com\" rel=\"nofollow noreferrer\">http://www.ultimate-wordpress-mobile-redirect.com</a></p>\n\n<p>With this plugin you can set a unique redirect URL for every page and post of your website.</p>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189767", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73800/" ]
I am looking for a simple clean solution when someone visits my **homepage** with a mobile device. Should I use something like Mobile Detect? I've seen many plugins with lots of downvotes or crashing. Is it otherwise possible to only add a javascript thingie on the homepage only? ``` if ('ontouchstart' in window) window.location = 'http://someurl.com/single/page'; ```
You could use [`wp_is_mobile`](https://codex.wordpress.org/Function_Reference/wp_is_mobile) with [`wp_redirect`](https://codex.wordpress.org/Function_Reference/wp_redirect) ``` if ( wp_is_mobile() AND is_front_page() ) { wp_redirect( $location, $status ); exit; } ``` You can add the js directly to a front-page.php or home.php file or [`enqueue`](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) it directly from either file. Example: ``` add_action('wp_enqueue_scripts', 'load_script'); function load_script(){ wp_enqueue_script( 'script-handle', get_stylesheet_directory_uri() . '/js/your-script.js', array( 'jquery' ) ); } ```
189,774
<p>Why $has_children doesn't work here?</p> <pre><code>class walker_name extends Walker_Nav_Menu{ function start_el(&amp;$output, $item, $depth, $args) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ); $class_names = ' class="' . esc_attr( $class_names ) . '"'; $output .= $indent . '&lt;li id="menu-item-'. $item-&gt;ID . '"' . $value . $class_names .'&gt;'; $attributes = ! empty( $item-&gt;attr_title ) ? ' title="' . esc_attr( $item-&gt;attr_title ) .'"' : ''; $attributes .= ! empty( $item-&gt;target ) ? ' target="' . esc_attr( $item-&gt;target ) .'"' : ''; $attributes .= ! empty( $item-&gt;xfn ) ? ' rel="' . esc_attr( $item-&gt;xfn ) .'"' : ''; $attributes .= ! empty( $item-&gt;url ) ? ' href="' . esc_attr( $item-&gt;url ) .'"' : ''; $item_output = $args-&gt;before; $item_output .= '&lt;a'. $attributes .'&gt;'; $item_output .= $args-&gt;link_before . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . $args-&gt;link_after; $item_output .= '&lt;/a&gt;'; $has_children = (is_object($args) &amp;&amp; $args-&gt;has_children) || (is_array($args) &amp;&amp; $args['has_children']); if ( $has_children ) { // not working } } } </code></pre>
[ { "answer_id": 189778, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>I am not sure why you think that <code>$args-&gt;has_children</code> (or <code>$args['has_children']</code>) exists at all. I am not finding that in my tests <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src//wp-includes/nav-menu-template.php#L0\" rel=\"nofollow\">nor do I see it in source</a>.</p>\n\n<p>I think that what you want is <code>$menu_item-&gt;menu_item_parent</code> as <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src//wp-includes/nav-menu-template.php#L330\" rel=\"nofollow\">seen in the Core walker</a>.</p>\n\n<pre><code>330 $sorted_menu_items = $menu_items_with_children = array();\n331 foreach ( (array) $menu_items as $menu_item ) {\n332 $sorted_menu_items[ $menu_item-&gt;menu_order ] = $menu_item;\n333 if ( $menu_item-&gt;menu_item_parent )\n334 $menu_items_with_children[ $menu_item-&gt;menu_item_parent ] = true;\n335 }\n</code></pre>\n" }, { "answer_id": 212775, "author": "solgar", "author_id": 85743, "author_profile": "https://wordpress.stackexchange.com/users/85743", "pm_score": 3, "selected": false, "text": "<p>I just resolved this issue! Woo hoo! The thing is that using <code>var_dump($args)</code> shows a lot stuff like so:</p>\n\n<pre><code>object(stdClass)#152 (16) { [\"menu\"]=&gt; object(WP_Term)#145 (10) { [\"term_id\"]=&gt;\nint(2) [\"name\"]=&gt; string(9) \"Main menu\" [\"slug\"]=&gt; string(9) \"main-menu\"\n[\"term_group\"]=&gt; int(0) [\"term_taxonomy_id\"]=&gt; int(2) [\"taxonomy\"]=&gt; string(8)\n\"nav_menu\" [\"description\"]=&gt; string(0) \"\" [\"parent\"]=&gt; int(0) [\"count\"]=&gt; int(12)\n[\"filter\"]=&gt; string(3) \"raw\" } [\"container\"]=&gt; string(0) \"\" [\"container_class\"]=&gt;\nstring(0) \"\" [\"container_id\"]=&gt; string(0) \"\" [\"menu_class\"]=&gt; string(4) \"menu\"\n[\"menu_id\"]=&gt; string(0) \"\" [\"echo\"]=&gt; bool(true) [\"fallback_cb\"]=&gt; string(12)\n\"wp_page_menu\" [\"before\"]=&gt; string(0) \"\" [\"after\"]=&gt; string(0) \"\" [\"link_before\"]=&gt;\nstring(0) \"\" [\"link_after\"]=&gt; string(0) \"\" [\"items_wrap\"]=&gt; string(4) \"%3$s\"\n[\"depth\"]=&gt; int(0) [\"walker\"]=&gt; object(themeslug_walker_nav_menu)#151 (4) {\n[\"tree_type\"]=&gt; array(3) { [0]=&gt; string(9) \"post_type\" [1]=&gt; string(8) \"taxonomy\"\n[2]=&gt; string(6) \"custom\" } [\"db_fields\"]=&gt; array(2) { [\"parent\"]=&gt; string(16)\n\"menu_item_parent\" [\"id\"]=&gt; string(5) \"db_id\" } [\"max_pages\"]=&gt; int(1)\n[\"has_children\"]=&gt; bool(true) } [\"theme_location\"]=&gt; string(0) \"\" }\n</code></pre>\n\n<p>Searching through this dump you can clearly see <code>[\"has_children\"]=&gt; bool(true)</code> but the thing is that it isn't part of <code>$args</code> object! In fact it is part of object which is held under <code>\"walker\"</code> value. This is more obvious when you indent a bit output like so:</p>\n\n<pre><code>object(stdClass)#152 (16) {\n [\"menu\"]=&gt; object(WP_Term)#145 (10) {\n [\"term_id\"]=&gt; int(2)\n [\"name\"]=&gt; string(9) \"Main menu\"\n [\"slug\"]=&gt; string(9) \"main-menu\"\n [\"term_group\"]=&gt; int(0)\n [\"term_taxonomy_id\"]=&gt; int(2)\n [\"taxonomy\"]=&gt; string(8) \"nav_menu\"\n [\"description\"]=&gt; string(0) \"\"\n [\"parent\"]=&gt; int(0)\n [\"count\"]=&gt; int(12)\n [\"filter\"]=&gt; string(3) \"raw\"\n }\n [\"container\"]=&gt; string(0) \"\"\n [\"container_class\"]=&gt; string(0) \"\"\n [\"container_id\"]=&gt; string(0) \"\"\n [\"menu_class\"]=&gt; string(4) \"menu\"\n [\"menu_id\"]=&gt; string(0) \"\"\n [\"echo\"]=&gt; bool(true)\n [\"fallback_cb\"]=&gt; string(12) \"wp_page_menu\"\n [\"before\"]=&gt; string(0) \"\"\n [\"after\"]=&gt; string(0) \"\"\n [\"link_before\"]=&gt; string(0) \"\"\n [\"link_after\"]=&gt; string(0) \"\"\n [\"items_wrap\"]=&gt; string(4) \"%3$s\"\n [\"depth\"]=&gt; int(0)\n [\"walker\"]=&gt; object(themeslug_walker_nav_menu)#151 (4) {\n [\"tree_type\"]=&gt; array(3) {\n [0]=&gt; string(9) \"post_type\"\n [1]=&gt; string(8) \"taxonomy\"\n [2]=&gt; string(6) \"custom\"\n }\n [\"db_fields\"]=&gt; array(2) {\n [\"parent\"]=&gt; string(16) \"menu_item_parent\"\n [\"id\"]=&gt; string(5) \"db_id\"\n }\n [\"max_pages\"]=&gt; int(1)\n [\"has_children\"]=&gt; bool(true)\n }\n [\"theme_location\"]=&gt; string(0) \"\"\n}\n</code></pre>\n\n<p>Now you can clearly see that to access <code>has_children</code> property you need to call this line:</p>\n\n<pre><code>$args-&gt;walker-&gt;has_children\n</code></pre>\n" } ]
2015/05/28
[ "https://wordpress.stackexchange.com/questions/189774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37529/" ]
Why $has\_children doesn't work here? ``` class walker_name extends Walker_Nav_Menu{ function start_el(&$output, $item, $depth, $args) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ); $class_names = ' class="' . esc_attr( $class_names ) . '"'; $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>'; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= '</a>'; $has_children = (is_object($args) && $args->has_children) || (is_array($args) && $args['has_children']); if ( $has_children ) { // not working } } } ```
I just resolved this issue! Woo hoo! The thing is that using `var_dump($args)` shows a lot stuff like so: ``` object(stdClass)#152 (16) { ["menu"]=> object(WP_Term)#145 (10) { ["term_id"]=> int(2) ["name"]=> string(9) "Main menu" ["slug"]=> string(9) "main-menu" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(2) ["taxonomy"]=> string(8) "nav_menu" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(12) ["filter"]=> string(3) "raw" } ["container"]=> string(0) "" ["container_class"]=> string(0) "" ["container_id"]=> string(0) "" ["menu_class"]=> string(4) "menu" ["menu_id"]=> string(0) "" ["echo"]=> bool(true) ["fallback_cb"]=> string(12) "wp_page_menu" ["before"]=> string(0) "" ["after"]=> string(0) "" ["link_before"]=> string(0) "" ["link_after"]=> string(0) "" ["items_wrap"]=> string(4) "%3$s" ["depth"]=> int(0) ["walker"]=> object(themeslug_walker_nav_menu)#151 (4) { ["tree_type"]=> array(3) { [0]=> string(9) "post_type" [1]=> string(8) "taxonomy" [2]=> string(6) "custom" } ["db_fields"]=> array(2) { ["parent"]=> string(16) "menu_item_parent" ["id"]=> string(5) "db_id" } ["max_pages"]=> int(1) ["has_children"]=> bool(true) } ["theme_location"]=> string(0) "" } ``` Searching through this dump you can clearly see `["has_children"]=> bool(true)` but the thing is that it isn't part of `$args` object! In fact it is part of object which is held under `"walker"` value. This is more obvious when you indent a bit output like so: ``` object(stdClass)#152 (16) { ["menu"]=> object(WP_Term)#145 (10) { ["term_id"]=> int(2) ["name"]=> string(9) "Main menu" ["slug"]=> string(9) "main-menu" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(2) ["taxonomy"]=> string(8) "nav_menu" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(12) ["filter"]=> string(3) "raw" } ["container"]=> string(0) "" ["container_class"]=> string(0) "" ["container_id"]=> string(0) "" ["menu_class"]=> string(4) "menu" ["menu_id"]=> string(0) "" ["echo"]=> bool(true) ["fallback_cb"]=> string(12) "wp_page_menu" ["before"]=> string(0) "" ["after"]=> string(0) "" ["link_before"]=> string(0) "" ["link_after"]=> string(0) "" ["items_wrap"]=> string(4) "%3$s" ["depth"]=> int(0) ["walker"]=> object(themeslug_walker_nav_menu)#151 (4) { ["tree_type"]=> array(3) { [0]=> string(9) "post_type" [1]=> string(8) "taxonomy" [2]=> string(6) "custom" } ["db_fields"]=> array(2) { ["parent"]=> string(16) "menu_item_parent" ["id"]=> string(5) "db_id" } ["max_pages"]=> int(1) ["has_children"]=> bool(true) } ["theme_location"]=> string(0) "" } ``` Now you can clearly see that to access `has_children` property you need to call this line: ``` $args->walker->has_children ```
189,788
<p>So, I understand how to target a specific menu using the following to add a custom code.</p> <pre><code>&lt;?php wp_nav_menu( array( 'menu' =&gt; 'Project Nav', // do not fall back to first non-empty menu 'theme_location' =&gt; '__no_such_location', // do not fall back to wp_page_menu() 'fallback_cb' =&gt; false ) ); ?&gt; </code></pre> <p>Question I have is the following.</p> <p>Let say I have a menu called "primary". Within this menu, there are 4 menu items (picture below).</p> <p><img src="https://i.stack.imgur.com/KGVxI.png" alt="enter image description here"></p> <p>One of the items is called "Profile".</p> <p>I want to replace the word "Profile" with the following code which shows user profile photo instead of the word "Profile".</p> <pre><code> &lt;?php global $my_profile; ?&gt; &lt;?php if (is_user_logged_in()) : ?&gt; &lt;div class="img" data-key="profile"&gt;&lt;?php echo get_avatar( get_current_user_id(), 64 ); ?&gt;&lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>So, the final result would look like this:</p> <p><img src="https://i.stack.imgur.com/U0FJq.png" alt="enter image description here"></p> <p>Now, how can I specifically target a menu item title? </p> <p>EDIT:</p> <p>So, I got the following based and I am not sure why it is not working.</p> <pre><code>function nav_replace_wpse_189788($item_output, $item, $args) { //var_dump($item_output, $item); if( $args-&gt;theme_location == 'primary' ){ return $items; if ('royal_profile_menu_title' == $item-&gt;title) { global $my_profile; if (is_user_logged_in()) { return '&lt;div class="img" data-key="profile"&gt;'.get_avatar( get_current_user_id(), 64 ).'&lt;/div&gt;'; } } } return $item_output; } add_filter('walker_nav_menu_start_el','nav_replace_wpse_189788',10,2); </code></pre> <p>Here is my logic. First target the "primary" menu, then look for item title "royal_profile_menu_title" then replace the word title with the output</p> <p>(My menu title is "royal_profile_menu_title": Picture below) <img src="https://i.stack.imgur.com/mHUZL.png" alt="enter image description here"></p> <p>Any</p>
[ { "answer_id": 189789, "author": "Marek", "author_id": 54031, "author_profile": "https://wordpress.stackexchange.com/users/54031", "pm_score": 1, "selected": false, "text": "<p>Presonally, I would use some CSS workaround. In menu administration you can add CSS class to menu item (if the field is not displayed, you can find it in Screen Options), for example \"profile-link\".</p>\n\n<p>And than you can add something like this to your template HEAD section:</p>\n\n<pre><code>&lt;?php\n$avatar = get_avatar_url( get_current_user_id(), array('size' =&gt; 64) ); // from WP 4.2\n$image_url = $avatar['url'];\n?&gt;\n\n&lt;style type=\"text/css\"&gt;\n.menu li.profile-link { background-image: url(&lt;?php echo $image_url ?&gt;); /* + another CSS*/ }\n.menu li.profile-link span { display: none; }\n&lt;/style&gt;\n</code></pre>\n\n<p>And add to your <code>wp_nav_menu</code> function <code>'link_before' =&gt; '&lt;span&gt;', 'link_after' =&gt; '&lt;/span&gt;'</code> options.</p>\n\n<p>Not tested, but it should do the job. </p>\n" }, { "answer_id": 189829, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 4, "selected": true, "text": "<p>This is relatively easily done using the <code>walker_nav_menu_start_el</code> filter (without all that PHP tag spam):</p>\n\n<pre><code>function nav_replace_wpse_189788($item_output, $item) {\n // var_dump($item_output, $item);\n if ('Profile' == $item-&gt;title) {\n global $my_profile; // no idea what this does?\n if (is_user_logged_in()) { \n return '&lt;div class=\"img\" data-key=\"profile\"&gt;'.get_avatar( get_current_user_id(), 64 ).'&lt;/div&gt;';\n }\n }\n return $item_output;\n}\nadd_filter('walker_nav_menu_start_el','nav_replace_wpse_189788',10,2);\n</code></pre>\n\n<p>Note: I had to edit your code to <code>return</code> a string, not <code>echo</code> one. You may need to tweak the <code>if</code> conditional. Uncomment the <code>var_dump()</code> to see what you have to work with.</p>\n" } ]
2015/05/29
[ "https://wordpress.stackexchange.com/questions/189788", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67604/" ]
So, I understand how to target a specific menu using the following to add a custom code. ``` <?php wp_nav_menu( array( 'menu' => 'Project Nav', // do not fall back to first non-empty menu 'theme_location' => '__no_such_location', // do not fall back to wp_page_menu() 'fallback_cb' => false ) ); ?> ``` Question I have is the following. Let say I have a menu called "primary". Within this menu, there are 4 menu items (picture below). ![enter image description here](https://i.stack.imgur.com/KGVxI.png) One of the items is called "Profile". I want to replace the word "Profile" with the following code which shows user profile photo instead of the word "Profile". ``` <?php global $my_profile; ?> <?php if (is_user_logged_in()) : ?> <div class="img" data-key="profile"><?php echo get_avatar( get_current_user_id(), 64 ); ?></div> <?php endif; ?> ``` So, the final result would look like this: ![enter image description here](https://i.stack.imgur.com/U0FJq.png) Now, how can I specifically target a menu item title? EDIT: So, I got the following based and I am not sure why it is not working. ``` function nav_replace_wpse_189788($item_output, $item, $args) { //var_dump($item_output, $item); if( $args->theme_location == 'primary' ){ return $items; if ('royal_profile_menu_title' == $item->title) { global $my_profile; if (is_user_logged_in()) { return '<div class="img" data-key="profile">'.get_avatar( get_current_user_id(), 64 ).'</div>'; } } } return $item_output; } add_filter('walker_nav_menu_start_el','nav_replace_wpse_189788',10,2); ``` Here is my logic. First target the "primary" menu, then look for item title "royal\_profile\_menu\_title" then replace the word title with the output (My menu title is "royal\_profile\_menu\_title": Picture below) ![enter image description here](https://i.stack.imgur.com/mHUZL.png) Any
This is relatively easily done using the `walker_nav_menu_start_el` filter (without all that PHP tag spam): ``` function nav_replace_wpse_189788($item_output, $item) { // var_dump($item_output, $item); if ('Profile' == $item->title) { global $my_profile; // no idea what this does? if (is_user_logged_in()) { return '<div class="img" data-key="profile">'.get_avatar( get_current_user_id(), 64 ).'</div>'; } } return $item_output; } add_filter('walker_nav_menu_start_el','nav_replace_wpse_189788',10,2); ``` Note: I had to edit your code to `return` a string, not `echo` one. You may need to tweak the `if` conditional. Uncomment the `var_dump()` to see what you have to work with.
189,816
<p>I have created a custom post type named 14kgold. Under this I defined two categories: Symphony and Noir. Now I added items/ products to each category. When I open a product under one category i.e. symphony for example, It takes me to single.php. Till now everything is working fine. But when I do next, It shows me the next item of noir. How can I make the pagination specific to symphony only?</p> <pre><code> /*Custom post type 14K Gold and Silver*/ function my_custom_post_14kgs() { $labels = array( 'name' =&gt; _x( '14k Gold &amp; Silver', 'post type general name' ), 'singular_name' =&gt; _x( '14k Gold &amp; Silver', 'post type singular name' ), 'add_new' =&gt; _x( 'Add New', 'book' ), 'add_new_item' =&gt; __( 'Add New Item' ), 'edit_item' =&gt; __( 'Modify Item' ), 'new_item' =&gt; __( 'New Item' ), 'all_items' =&gt; __( 'All Items' ), 'view_item' =&gt; __( 'View Item' ), 'search_items' =&gt; __( 'Search Items' ), 'not_found' =&gt; __( 'No Products found' ), 'not_found_in_trash' =&gt; __( 'No products found in trash' ), 'parent_item_colon' =&gt; '', 'menu_name' =&gt; '14k Gold &amp; Silver' ); $args = array( 'labels' =&gt; $labels, 'description' =&gt; '', 'public' =&gt; true, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ), 'has_archive' =&gt; true, 'hierarchical' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; '14k-gold-silver/%14kgscollection%','with_front' =&gt; false), 'query_var' =&gt; true, //'rewrite' =&gt; true, //'publicly_queryable' =&gt; false, ); register_post_type( '14kgs', $args ); } add_action( 'init', 'my_custom_post_14kgs' ); function my_taxonomies_product_14kgs() { $labels = array( 'name' =&gt; _x( '14kgscollection', 'taxonomy general name' ), 'singular_name' =&gt; _x( '14kgscollection', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Product Categories' ), 'all_items' =&gt; __( 'All Product Categories' ), 'parent_item' =&gt; __( 'Parent Product Category' ), 'parent_item_colon' =&gt; __( 'Parent Product Category:' ), 'edit_item' =&gt; __( 'Edit Product Category' ), 'update_item' =&gt; __( 'Update Product Category' ), 'add_new_item' =&gt; __( 'Add New Product Category' ), 'new_item_name' =&gt; __( 'New Product Category' ), 'menu_name' =&gt; __( '14kgscollection' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'query_var' =&gt; '14kgscollection', 'rewrite' =&gt; array('slug' =&gt; '14k-gold-silver' ), '_builtin' =&gt; false, ); register_taxonomy( '14kgscollection', '14kgs', $args ); } add_action( 'init', 'my_taxonomies_product_14kgs', 0 ); /*Filter permalink structure*/ add_filter('post_link', 'collection14kgs_permalink', 1, 3); add_filter('post_type_link', 'collection14kgs_permalink', 1, 3); function collection14kgs_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%14kgscollection%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post-&gt;ID, '14kgscollection'); if (!is_wp_error($terms) &amp;&amp; !empty($terms) &amp;&amp; is_object($terms[0])) $taxonomy_slug = $terms[0]-&gt;slug; else $taxonomy_slug = 'no-collection'; return str_replace('%14kgscollection%', $taxonomy_slug, $permalink); } </code></pre> <p>Is there anything I can add to the above code which gives me a unique value which can help me in differentiating the products under two categories?</p>
[ { "answer_id": 189789, "author": "Marek", "author_id": 54031, "author_profile": "https://wordpress.stackexchange.com/users/54031", "pm_score": 1, "selected": false, "text": "<p>Presonally, I would use some CSS workaround. In menu administration you can add CSS class to menu item (if the field is not displayed, you can find it in Screen Options), for example \"profile-link\".</p>\n\n<p>And than you can add something like this to your template HEAD section:</p>\n\n<pre><code>&lt;?php\n$avatar = get_avatar_url( get_current_user_id(), array('size' =&gt; 64) ); // from WP 4.2\n$image_url = $avatar['url'];\n?&gt;\n\n&lt;style type=\"text/css\"&gt;\n.menu li.profile-link { background-image: url(&lt;?php echo $image_url ?&gt;); /* + another CSS*/ }\n.menu li.profile-link span { display: none; }\n&lt;/style&gt;\n</code></pre>\n\n<p>And add to your <code>wp_nav_menu</code> function <code>'link_before' =&gt; '&lt;span&gt;', 'link_after' =&gt; '&lt;/span&gt;'</code> options.</p>\n\n<p>Not tested, but it should do the job. </p>\n" }, { "answer_id": 189829, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 4, "selected": true, "text": "<p>This is relatively easily done using the <code>walker_nav_menu_start_el</code> filter (without all that PHP tag spam):</p>\n\n<pre><code>function nav_replace_wpse_189788($item_output, $item) {\n // var_dump($item_output, $item);\n if ('Profile' == $item-&gt;title) {\n global $my_profile; // no idea what this does?\n if (is_user_logged_in()) { \n return '&lt;div class=\"img\" data-key=\"profile\"&gt;'.get_avatar( get_current_user_id(), 64 ).'&lt;/div&gt;';\n }\n }\n return $item_output;\n}\nadd_filter('walker_nav_menu_start_el','nav_replace_wpse_189788',10,2);\n</code></pre>\n\n<p>Note: I had to edit your code to <code>return</code> a string, not <code>echo</code> one. You may need to tweak the <code>if</code> conditional. Uncomment the <code>var_dump()</code> to see what you have to work with.</p>\n" } ]
2015/05/29
[ "https://wordpress.stackexchange.com/questions/189816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36324/" ]
I have created a custom post type named 14kgold. Under this I defined two categories: Symphony and Noir. Now I added items/ products to each category. When I open a product under one category i.e. symphony for example, It takes me to single.php. Till now everything is working fine. But when I do next, It shows me the next item of noir. How can I make the pagination specific to symphony only? ``` /*Custom post type 14K Gold and Silver*/ function my_custom_post_14kgs() { $labels = array( 'name' => _x( '14k Gold & Silver', 'post type general name' ), 'singular_name' => _x( '14k Gold & Silver', 'post type singular name' ), 'add_new' => _x( 'Add New', 'book' ), 'add_new_item' => __( 'Add New Item' ), 'edit_item' => __( 'Modify Item' ), 'new_item' => __( 'New Item' ), 'all_items' => __( 'All Items' ), 'view_item' => __( 'View Item' ), 'search_items' => __( 'Search Items' ), 'not_found' => __( 'No Products found' ), 'not_found_in_trash' => __( 'No products found in trash' ), 'parent_item_colon' => '', 'menu_name' => '14k Gold & Silver' ); $args = array( 'labels' => $labels, 'description' => '', 'public' => true, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ), 'has_archive' => true, 'hierarchical' => true, 'rewrite' => array('slug' => '14k-gold-silver/%14kgscollection%','with_front' => false), 'query_var' => true, //'rewrite' => true, //'publicly_queryable' => false, ); register_post_type( '14kgs', $args ); } add_action( 'init', 'my_custom_post_14kgs' ); function my_taxonomies_product_14kgs() { $labels = array( 'name' => _x( '14kgscollection', 'taxonomy general name' ), 'singular_name' => _x( '14kgscollection', 'taxonomy singular name' ), 'search_items' => __( 'Search Product Categories' ), 'all_items' => __( 'All Product Categories' ), 'parent_item' => __( 'Parent Product Category' ), 'parent_item_colon' => __( 'Parent Product Category:' ), 'edit_item' => __( 'Edit Product Category' ), 'update_item' => __( 'Update Product Category' ), 'add_new_item' => __( 'Add New Product Category' ), 'new_item_name' => __( 'New Product Category' ), 'menu_name' => __( '14kgscollection' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'query_var' => '14kgscollection', 'rewrite' => array('slug' => '14k-gold-silver' ), '_builtin' => false, ); register_taxonomy( '14kgscollection', '14kgs', $args ); } add_action( 'init', 'my_taxonomies_product_14kgs', 0 ); /*Filter permalink structure*/ add_filter('post_link', 'collection14kgs_permalink', 1, 3); add_filter('post_type_link', 'collection14kgs_permalink', 1, 3); function collection14kgs_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%14kgscollection%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post->ID, '14kgscollection'); if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug; else $taxonomy_slug = 'no-collection'; return str_replace('%14kgscollection%', $taxonomy_slug, $permalink); } ``` Is there anything I can add to the above code which gives me a unique value which can help me in differentiating the products under two categories?
This is relatively easily done using the `walker_nav_menu_start_el` filter (without all that PHP tag spam): ``` function nav_replace_wpse_189788($item_output, $item) { // var_dump($item_output, $item); if ('Profile' == $item->title) { global $my_profile; // no idea what this does? if (is_user_logged_in()) { return '<div class="img" data-key="profile">'.get_avatar( get_current_user_id(), 64 ).'</div>'; } } return $item_output; } add_filter('walker_nav_menu_start_el','nav_replace_wpse_189788',10,2); ``` Note: I had to edit your code to `return` a string, not `echo` one. You may need to tweak the `if` conditional. Uncomment the `var_dump()` to see what you have to work with.
189,820
<p>I have created A custom post type as mentioned in <a href="https://wordpress.stackexchange.com/questions/189816/show-posts-of-one-category-only-with-custom-taxonomy-on-single-php">my older question</a></p> <p>When I try to use get_the_category() function to retrieve the category of the post(if it is symphony or noir). It returns "Array". How can I keep the posts under the two categories separate which do not interfere in the pagination of one category.<img src="https://i.stack.imgur.com/ZuUOm.jpg" alt="My custom post type with a taxonomy 14kgoldsilver"></p> <p><img src="https://i.stack.imgur.com/Tn06S.jpg" alt="The section where I select the category for each post"></p> <pre><code> /*Custom post type 14K Gold and Silver*/ function my_custom_post_14kgs() { $labels = array( 'name' =&gt; _x( '14k Gold &amp; Silver', 'post type general name' ), 'singular_name' =&gt; _x( '14k Gold &amp; Silver', 'post type singular name' ), 'add_new' =&gt; _x( 'Add New', 'book' ), 'add_new_item' =&gt; __( 'Add New Item' ), 'edit_item' =&gt; __( 'Modify Item' ), 'new_item' =&gt; __( 'New Item' ), 'all_items' =&gt; __( 'All Items' ), 'view_item' =&gt; __( 'View Item' ), 'search_items' =&gt; __( 'Search Items' ), 'not_found' =&gt; __( 'No Products found' ), 'not_found_in_trash' =&gt; __( 'No products found in trash' ), 'parent_item_colon' =&gt; '', 'menu_name' =&gt; '14k Gold &amp; Silver' ); $args = array( 'labels' =&gt; $labels, 'description' =&gt; '', 'public' =&gt; true, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ), 'has_archive' =&gt; true, 'hierarchical' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; '14k-gold-silver/%14kgscollection%','with_front' =&gt; false), 'query_var' =&gt; true, //'rewrite' =&gt; true, //'publicly_queryable' =&gt; false, ); register_post_type( '14kgs', $args ); } add_action( 'init', 'my_custom_post_14kgs' ); function my_taxonomies_product_14kgs() { $labels = array( 'name' =&gt; _x( '14kgscollection', 'taxonomy general name' ), 'singular_name' =&gt; _x( '14kgscollection', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Product Categories' ), 'all_items' =&gt; __( 'All Product Categories' ), 'parent_item' =&gt; __( 'Parent Product Category' ), 'parent_item_colon' =&gt; __( 'Parent Product Category:' ), 'edit_item' =&gt; __( 'Edit Product Category' ), 'update_item' =&gt; __( 'Update Product Category' ), 'add_new_item' =&gt; __( 'Add New Product Category' ), 'new_item_name' =&gt; __( 'New Product Category' ), 'menu_name' =&gt; __( '14kgscollection' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'query_var' =&gt; '14kgscollection', 'rewrite' =&gt; array('slug' =&gt; '14k-gold-silver' ), '_builtin' =&gt; false, ); register_taxonomy( '14kgscollection', '14kgs', $args ); } add_action( 'init', 'my_taxonomies_product_14kgs', 0 ); /*Filter permalink structure*/ add_filter('post_link', 'collection14kgs_permalink', 1, 3); add_filter('post_type_link', 'collection14kgs_permalink', 1, 3); function collection14kgs_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%14kgscollection%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post-&gt;ID, '14kgscollection'); if (!is_wp_error($terms) &amp;&amp; !empty($terms) &amp;&amp; is_object($terms[0])) $taxonomy_slug = $terms[0]-&gt;slug; else $taxonomy_slug = 'no-collection'; return str_replace('%14kgscollection%', $taxonomy_slug, $permalink); } </code></pre>
[ { "answer_id": 189900, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 1, "selected": false, "text": "<p>Check the 3rd and 4th parameters for previous and <a href=\"https://codex.wordpress.org/Function_Reference/next_post_link\" rel=\"nofollow\"><code>next_post_link</code></a>:</p>\n\n<p><strong>in_same_term</strong>\n(boolean) (optional) Indicates whether next post must be within the same taxonomy term as the current post. If set to 'true', only posts from the current taxonomy term will be displayed. If the post is in both the parent and subcategory, or more than one term, the next post link will lead to the next post in any of those terms.\ntrue\nfalse\nDefault: false</p>\n\n<p><strong>excluded_terms</strong>\n(string/array) (optional) Array or a comma-separated list of numeric terms IDs from which the next post should not be listed. For example array(1, 5) or '1,5'. This argument used to accept a list of IDs separated by 'and', this was deprecated in WordPress 3.3</p>\n\n<p>Default: None</p>\n\n<p>Also, you may find creating custom taxonomy types better for use with CPT's than categories.</p>\n\n<pre><code>add_action( 'init', 'video_type_taxonomy' );\nfunction video_type_taxonomy() {\n\n register_taxonomy( 'video-type', 'video',\n array(\n 'labels' =&gt; array(\n 'name' =&gt; _x( 'Types', 'taxonomy general name', 'executive' ),\n 'add_new_item' =&gt; __( 'Add New Video Type', '$text_domain' ),\n 'new_item_name' =&gt; __( 'New Video Type', '$text_domain' ),\n ),\n 'exclude_from_search' =&gt; true,\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'video-type', 'with_front' =&gt; false ),\n 'show_ui' =&gt; true,\n 'show_tagcloud' =&gt; false,\n )\n );\n\n}\n</code></pre>\n" }, { "answer_id": 191034, "author": "Disha", "author_id": 36324, "author_profile": "https://wordpress.stackexchange.com/users/36324", "pm_score": 0, "selected": false, "text": "<p><code>get_next_post ( )</code> and <code>get_previous_post ( )</code> helped in getting what I was looking for. </p>\n\n<p>Thanx all for your time</p>\n" } ]
2015/05/29
[ "https://wordpress.stackexchange.com/questions/189820", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36324/" ]
I have created A custom post type as mentioned in [my older question](https://wordpress.stackexchange.com/questions/189816/show-posts-of-one-category-only-with-custom-taxonomy-on-single-php) When I try to use get\_the\_category() function to retrieve the category of the post(if it is symphony or noir). It returns "Array". How can I keep the posts under the two categories separate which do not interfere in the pagination of one category.![My custom post type with a taxonomy 14kgoldsilver](https://i.stack.imgur.com/ZuUOm.jpg) ![The section where I select the category for each post](https://i.stack.imgur.com/Tn06S.jpg) ``` /*Custom post type 14K Gold and Silver*/ function my_custom_post_14kgs() { $labels = array( 'name' => _x( '14k Gold & Silver', 'post type general name' ), 'singular_name' => _x( '14k Gold & Silver', 'post type singular name' ), 'add_new' => _x( 'Add New', 'book' ), 'add_new_item' => __( 'Add New Item' ), 'edit_item' => __( 'Modify Item' ), 'new_item' => __( 'New Item' ), 'all_items' => __( 'All Items' ), 'view_item' => __( 'View Item' ), 'search_items' => __( 'Search Items' ), 'not_found' => __( 'No Products found' ), 'not_found_in_trash' => __( 'No products found in trash' ), 'parent_item_colon' => '', 'menu_name' => '14k Gold & Silver' ); $args = array( 'labels' => $labels, 'description' => '', 'public' => true, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ), 'has_archive' => true, 'hierarchical' => true, 'rewrite' => array('slug' => '14k-gold-silver/%14kgscollection%','with_front' => false), 'query_var' => true, //'rewrite' => true, //'publicly_queryable' => false, ); register_post_type( '14kgs', $args ); } add_action( 'init', 'my_custom_post_14kgs' ); function my_taxonomies_product_14kgs() { $labels = array( 'name' => _x( '14kgscollection', 'taxonomy general name' ), 'singular_name' => _x( '14kgscollection', 'taxonomy singular name' ), 'search_items' => __( 'Search Product Categories' ), 'all_items' => __( 'All Product Categories' ), 'parent_item' => __( 'Parent Product Category' ), 'parent_item_colon' => __( 'Parent Product Category:' ), 'edit_item' => __( 'Edit Product Category' ), 'update_item' => __( 'Update Product Category' ), 'add_new_item' => __( 'Add New Product Category' ), 'new_item_name' => __( 'New Product Category' ), 'menu_name' => __( '14kgscollection' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'query_var' => '14kgscollection', 'rewrite' => array('slug' => '14k-gold-silver' ), '_builtin' => false, ); register_taxonomy( '14kgscollection', '14kgs', $args ); } add_action( 'init', 'my_taxonomies_product_14kgs', 0 ); /*Filter permalink structure*/ add_filter('post_link', 'collection14kgs_permalink', 1, 3); add_filter('post_type_link', 'collection14kgs_permalink', 1, 3); function collection14kgs_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%14kgscollection%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post->ID, '14kgscollection'); if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug; else $taxonomy_slug = 'no-collection'; return str_replace('%14kgscollection%', $taxonomy_slug, $permalink); } ```
Check the 3rd and 4th parameters for previous and [`next_post_link`](https://codex.wordpress.org/Function_Reference/next_post_link): **in\_same\_term** (boolean) (optional) Indicates whether next post must be within the same taxonomy term as the current post. If set to 'true', only posts from the current taxonomy term will be displayed. If the post is in both the parent and subcategory, or more than one term, the next post link will lead to the next post in any of those terms. true false Default: false **excluded\_terms** (string/array) (optional) Array or a comma-separated list of numeric terms IDs from which the next post should not be listed. For example array(1, 5) or '1,5'. This argument used to accept a list of IDs separated by 'and', this was deprecated in WordPress 3.3 Default: None Also, you may find creating custom taxonomy types better for use with CPT's than categories. ``` add_action( 'init', 'video_type_taxonomy' ); function video_type_taxonomy() { register_taxonomy( 'video-type', 'video', array( 'labels' => array( 'name' => _x( 'Types', 'taxonomy general name', 'executive' ), 'add_new_item' => __( 'Add New Video Type', '$text_domain' ), 'new_item_name' => __( 'New Video Type', '$text_domain' ), ), 'exclude_from_search' => true, 'has_archive' => true, 'hierarchical' => true, 'rewrite' => array( 'slug' => 'video-type', 'with_front' => false ), 'show_ui' => true, 'show_tagcloud' => false, ) ); } ```
189,827
<p>When changing the slug for a page (clicking OK) an ajax call is made to check if the slug is available and to generate a different one if not. Does anyone know if there is any logging for this, or any way to investigate what's happening? Even knowing where the source is for this process would be helpful.</p> <p>I'm experiencing a very strange behaviour whereby the slug of pages is changing to that of a post in a different post type <em>but only when the slug isn't being changed</em>. It's as if it's determined that the slug is a duplicate of itself.</p> <p>Not sure how to investigate this behaviour, any pokes in the right direction appreciated!</p>
[ { "answer_id": 189832, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>Firebug's \"Network\" tab should tell you, or something more aggressive like Wireshark. </p>\n\n<p>The <code>wp-admin/admin-ajax.php</code> file does fire the <code>admin_init</code> hook so you could use that to create a log. Something like:</p>\n\n<pre><code>function log_ajax_wpse_189827() {\n if (defined(DOING_AJAX) &amp;&amp; TRUE === DOING_AJAX) {\n error_log(\"Howdy!\");\n }\n}\nadd_filter('admin_init','log_ajax_wpse_189827');\n</code></pre>\n" }, { "answer_id": 189833, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>If we trace the Ajax process after you click <kbd>OK</kbd>, we would walk the following path from the core and into the database:</p>\n\n<pre><code>Press OK on Edit slug:\n \\\n \\-&gt; AJAX POST request with action=sample-permalink Action: wp_ajax_sample-permalink\n \\\n \\-&gt; function: wp_ajax_sample_permalink()\n \\\n \\-&gt; function: get_sample_permalink_html() Filter: get_sample_permalink_html\n \\\n \\-&gt; function: get_sample_permalink() Filters: get_sample_permalink, editable_slug\n \\\n \\-&gt; function: wp_unique_post_slug() Filter: wp_unique_post_slug\n \\\n \\-&gt; db call: $wpdb-&gt;get_var() \n</code></pre>\n\n<p>So you could hook into some of those filters to check/log what's happening to your slug generation. You could for example wrap your logging part within the <code>wp_ajax_sample-permalink</code> action:</p>\n\n<pre><code>add_action( 'wp_ajax_sample-permalink', function()\n{\n add_filter( 'somefilter', function( $var )\n {\n // --&gt; your EARLY logging part here &lt;---\n\n return $var;\n }, 0 ); \n\n add_filter( 'somefilter', function( $var )\n {\n // --&gt; your LATE logging part here &lt;---\n\n return $var;\n }, PHP_INT_MAX ); \n} );\n</code></pre>\n\n<p>where you can adjust the <code>somefilter</code> to your needs.</p>\n" } ]
2015/05/29
[ "https://wordpress.stackexchange.com/questions/189827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57301/" ]
When changing the slug for a page (clicking OK) an ajax call is made to check if the slug is available and to generate a different one if not. Does anyone know if there is any logging for this, or any way to investigate what's happening? Even knowing where the source is for this process would be helpful. I'm experiencing a very strange behaviour whereby the slug of pages is changing to that of a post in a different post type *but only when the slug isn't being changed*. It's as if it's determined that the slug is a duplicate of itself. Not sure how to investigate this behaviour, any pokes in the right direction appreciated!
If we trace the Ajax process after you click `OK`, we would walk the following path from the core and into the database: ``` Press OK on Edit slug: \ \-> AJAX POST request with action=sample-permalink Action: wp_ajax_sample-permalink \ \-> function: wp_ajax_sample_permalink() \ \-> function: get_sample_permalink_html() Filter: get_sample_permalink_html \ \-> function: get_sample_permalink() Filters: get_sample_permalink, editable_slug \ \-> function: wp_unique_post_slug() Filter: wp_unique_post_slug \ \-> db call: $wpdb->get_var() ``` So you could hook into some of those filters to check/log what's happening to your slug generation. You could for example wrap your logging part within the `wp_ajax_sample-permalink` action: ``` add_action( 'wp_ajax_sample-permalink', function() { add_filter( 'somefilter', function( $var ) { // --> your EARLY logging part here <--- return $var; }, 0 ); add_filter( 'somefilter', function( $var ) { // --> your LATE logging part here <--- return $var; }, PHP_INT_MAX ); } ); ``` where you can adjust the `somefilter` to your needs.
189,855
<p>Is there a built-in workflow or process for running one-time wordpress database updates relating to things like taxonomy, new categories, filters, hooks, plugin setup, etc? </p> <p>Right now I'm putting all of these programmatic database updates into my custom functions.php file. This feels wrong since the code will run repeatedly even though it's for a one-time task. Deploying then redeploying with the changes commented out also feels cloogy. I'm coming from other technology stacks where there is a built-in workflow for managing one-time database migrations and imports. Is there something like this for Wordpress? </p>
[ { "answer_id": 189832, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 2, "selected": false, "text": "<p>Firebug's \"Network\" tab should tell you, or something more aggressive like Wireshark. </p>\n\n<p>The <code>wp-admin/admin-ajax.php</code> file does fire the <code>admin_init</code> hook so you could use that to create a log. Something like:</p>\n\n<pre><code>function log_ajax_wpse_189827() {\n if (defined(DOING_AJAX) &amp;&amp; TRUE === DOING_AJAX) {\n error_log(\"Howdy!\");\n }\n}\nadd_filter('admin_init','log_ajax_wpse_189827');\n</code></pre>\n" }, { "answer_id": 189833, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>If we trace the Ajax process after you click <kbd>OK</kbd>, we would walk the following path from the core and into the database:</p>\n\n<pre><code>Press OK on Edit slug:\n \\\n \\-&gt; AJAX POST request with action=sample-permalink Action: wp_ajax_sample-permalink\n \\\n \\-&gt; function: wp_ajax_sample_permalink()\n \\\n \\-&gt; function: get_sample_permalink_html() Filter: get_sample_permalink_html\n \\\n \\-&gt; function: get_sample_permalink() Filters: get_sample_permalink, editable_slug\n \\\n \\-&gt; function: wp_unique_post_slug() Filter: wp_unique_post_slug\n \\\n \\-&gt; db call: $wpdb-&gt;get_var() \n</code></pre>\n\n<p>So you could hook into some of those filters to check/log what's happening to your slug generation. You could for example wrap your logging part within the <code>wp_ajax_sample-permalink</code> action:</p>\n\n<pre><code>add_action( 'wp_ajax_sample-permalink', function()\n{\n add_filter( 'somefilter', function( $var )\n {\n // --&gt; your EARLY logging part here &lt;---\n\n return $var;\n }, 0 ); \n\n add_filter( 'somefilter', function( $var )\n {\n // --&gt; your LATE logging part here &lt;---\n\n return $var;\n }, PHP_INT_MAX ); \n} );\n</code></pre>\n\n<p>where you can adjust the <code>somefilter</code> to your needs.</p>\n" } ]
2015/05/29
[ "https://wordpress.stackexchange.com/questions/189855", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73514/" ]
Is there a built-in workflow or process for running one-time wordpress database updates relating to things like taxonomy, new categories, filters, hooks, plugin setup, etc? Right now I'm putting all of these programmatic database updates into my custom functions.php file. This feels wrong since the code will run repeatedly even though it's for a one-time task. Deploying then redeploying with the changes commented out also feels cloogy. I'm coming from other technology stacks where there is a built-in workflow for managing one-time database migrations and imports. Is there something like this for Wordpress?
If we trace the Ajax process after you click `OK`, we would walk the following path from the core and into the database: ``` Press OK on Edit slug: \ \-> AJAX POST request with action=sample-permalink Action: wp_ajax_sample-permalink \ \-> function: wp_ajax_sample_permalink() \ \-> function: get_sample_permalink_html() Filter: get_sample_permalink_html \ \-> function: get_sample_permalink() Filters: get_sample_permalink, editable_slug \ \-> function: wp_unique_post_slug() Filter: wp_unique_post_slug \ \-> db call: $wpdb->get_var() ``` So you could hook into some of those filters to check/log what's happening to your slug generation. You could for example wrap your logging part within the `wp_ajax_sample-permalink` action: ``` add_action( 'wp_ajax_sample-permalink', function() { add_filter( 'somefilter', function( $var ) { // --> your EARLY logging part here <--- return $var; }, 0 ); add_filter( 'somefilter', function( $var ) { // --> your LATE logging part here <--- return $var; }, PHP_INT_MAX ); } ); ``` where you can adjust the `somefilter` to your needs.
189,891
<p>this is the header section for enqueueing my scripts</p> <pre><code>&lt;?php wp_enqueue_script( 'menu' ); wp_enqueue_script('thumbnail'); ?&gt; &lt;?php wp_head(); ?&gt; &lt;link rel="stylesheet" href="&lt;?php bloginfo('stylesheet_url'); ?&gt;" type="text/css" /&gt; &lt;script type="text/javascript" src="&lt;?php get_template_directory_uri();?&gt;/js/menu-effect.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="&lt;?php get_template_directory_uri();?&gt;/js/thumbnail-effect.js"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>and this is functions.php section</p> <pre><code>function my_jsfile() { wp_register_script( 'menu', get_template_directory_uri() . '/js/menu-effect.js', array() ); wp_register_script( 'thumbnail', get_template_directory_uri().'/js/thumbnail-effect.js', array() ); } add_action( 'wp_enqueue_scripts', 'my_jsfile' ); </code></pre>
[ { "answer_id": 189892, "author": "Robert hue", "author_id": 22461, "author_profile": "https://wordpress.stackexchange.com/users/22461", "pm_score": 2, "selected": true, "text": "<p>You should enqueue scripts in <code>functions.php</code> itself with <code>wp_enqueue_scripts</code> hook. Like this.</p>\n\n<pre><code>function my_jsfile() {\n\n wp_register_script( 'menu', get_template_directory_uri() . '/js/menu-effect.js', array() );\n wp_register_script( 'thumbnail', get_template_directory_uri() . '/js/thumbnail-effect.js', array() );\n\n wp_enqueue_script( 'menu' );\n wp_enqueue_script( 'thumbnail' );\n\n}\nadd_action( 'wp_enqueue_scripts', 'my_jsfile' );\n</code></pre>\n\n<p>And also you should remove <code>wp_enqueue_script</code> from <code>header.php</code> as well as script links.</p>\n\n<p>And finally make sure your script paths are correct.</p>\n" }, { "answer_id": 189893, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 0, "selected": false, "text": "<p><code>wp_enqueue_scripts</code> fires after the call to the function <code>wp_head()</code>. So your <code>wp_enqueue_script()</code> calls are too early.</p>\n\n<p><strong>Register</strong> your scripts on <code>wp_loaded</code>, <strong>enqueue</strong> them on <code>wp_enqueue_scripts</code>.</p>\n\n<pre><code>add_action( 'wp_loaded', function() {\n $base = get_template_directory_uri();\n wp_register_script( 'menu', \"$base/js/menu-effect.js\" );\n wp_register_script( 'thumbnail', \"$base/js/thumbnail-effect.js\" );\n});\n\n\nadd_action( 'wp_enqueue_scripts', function() {\n wp_enqueue_script( 'menu' );\n wp_enqueue_script('thumbnail');\n});\n</code></pre>\n" } ]
2015/05/30
[ "https://wordpress.stackexchange.com/questions/189891", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73600/" ]
this is the header section for enqueueing my scripts ``` <?php wp_enqueue_script( 'menu' ); wp_enqueue_script('thumbnail'); ?> <?php wp_head(); ?> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" /> <script type="text/javascript" src="<?php get_template_directory_uri();?>/js/menu-effect.js"></script> <script type="text/javascript" src="<?php get_template_directory_uri();?>/js/thumbnail-effect.js"></script> </head> ``` and this is functions.php section ``` function my_jsfile() { wp_register_script( 'menu', get_template_directory_uri() . '/js/menu-effect.js', array() ); wp_register_script( 'thumbnail', get_template_directory_uri().'/js/thumbnail-effect.js', array() ); } add_action( 'wp_enqueue_scripts', 'my_jsfile' ); ```
You should enqueue scripts in `functions.php` itself with `wp_enqueue_scripts` hook. Like this. ``` function my_jsfile() { wp_register_script( 'menu', get_template_directory_uri() . '/js/menu-effect.js', array() ); wp_register_script( 'thumbnail', get_template_directory_uri() . '/js/thumbnail-effect.js', array() ); wp_enqueue_script( 'menu' ); wp_enqueue_script( 'thumbnail' ); } add_action( 'wp_enqueue_scripts', 'my_jsfile' ); ``` And also you should remove `wp_enqueue_script` from `header.php` as well as script links. And finally make sure your script paths are correct.
189,901
<p>I am trying to choose different databases for admin and user to decrease the load on database. in wp-config.php when i am trying to use the code</p> <pre><code>if(is_admin()) { define('DB_NAME', 'wp_db'); } else { define('DB_NAME', 'other_wp_db'); } </code></pre> <p>both databases uses same user name and password. </p> <p>I am getting an error of</p> <blockquote> <p>Fatal error: Call to undefined function is_admin() in D:\xampp\htdocs\wordpress\wp-config.php on line 24</p> </blockquote> <p>How to use is_admin() function in the wp-config.php file?</p> <p>can someone please help.</p>
[ { "answer_id": 189903, "author": "Marek", "author_id": 54031, "author_profile": "https://wordpress.stackexchange.com/users/54031", "pm_score": 2, "selected": false, "text": "<p>It's too early to use this WP built-in function. You can use it in some plugin or theme files, but not when WP enviroment is still loading.</p>\n\n<p>As I am not really sure if your intention is really correct, you have to use some other way (with PHP native functions) to distinct between front-end and administration. For example something like this:</p>\n\n<pre><code>if( strpos($_SERVER['REQUEST_URI'],'/wp-admin/') !== FALSE ) {\n define('DB_NAME', 'wp_db');\n} else { ... }\n</code></pre>\n\n<p>But I don't think it is bulletproof solution. Ajax call are processed in administration, <code>wp-login.php</code> is not covered by the code above, etc.</p>\n" }, { "answer_id": 189906, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>I would be careful doing this, because you are assuming all your database modifications will only happen within the admin backend, but that might not always be the case. The <code>wp-cron</code> comes to mind, but there are also some plugins that use front-end writes. So you might get nasty sync problems with your two databases, using this method.</p>\n\n<p>There are many things you can do before going the <em>master/slave</em> route:</p>\n\n<ul>\n<li>Check for example your logs, if there's anything strange going on there. </li>\n<li>Maybe it's a plugin that's giving you problems? </li>\n<li>Maybe you have a <code>WP_Query</code> that's not efficient? </li>\n<li>Maybe you can use the transients API?</li>\n<li>Maybe you can consider persistant object cache?</li>\n<li>There are many cache plugins out there that can help.</li>\n<li>Maybe the hosting environment is slowing you down?</li>\n<li>Maybe the MySQL server isn't tuned well enough? Some helpful tuning scripts exists.</li>\n<li>Maybe it's time to update PHP, MySQL and start using NginX ;-)</li>\n<li>...</li>\n</ul>\n\n<p>If you decide this route is necessary, there are already solutions out there, like the <em>HyperDB</em> plugin, that gives you a <code>db.php</code> drop-in to be placed in the <code>wp-content</code> directory. It checks for any writes/updates in the incoming SQL queries and redirects them to the master database. But I just scanned through the <a href=\"http://plugins.svn.wordpress.org/hyperdb/trunk/db.php\" rel=\"nofollow\">source</a> and it looks like it's not supporting the <code>mysqli</code> extension, only the deprecated <code>mysql</code>. If you don't like forking this yourself, there seems to exists at least one <a href=\"https://github.com/soulseekah/hyperdb-mysqli\" rel=\"nofollow\">fork</a> that supports <code>mysqli</code> (I'm not related to this project).</p>\n" }, { "answer_id": 286811, "author": "Dmitio Tar", "author_id": 132020, "author_profile": "https://wordpress.stackexchange.com/users/132020", "pm_score": -1, "selected": false, "text": "<p>Try to insert your code </p>\n\n<pre><code>if(is_admin()) {...}\n</code></pre>\n\n<p>AFTER </p>\n\n<pre><code>require_once(ABSPATH . 'wp-settings.php');\n</code></pre>\n\n<p>because function is_admin() is loaded while wp-setting.php is executed. In this way you could avoid the error message, but I cannot understand why have your site to work correctly only for administrator? It seems the semantic error. I think some components will not work correctly under administrator too.</p>\n" } ]
2015/05/30
[ "https://wordpress.stackexchange.com/questions/189901", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73859/" ]
I am trying to choose different databases for admin and user to decrease the load on database. in wp-config.php when i am trying to use the code ``` if(is_admin()) { define('DB_NAME', 'wp_db'); } else { define('DB_NAME', 'other_wp_db'); } ``` both databases uses same user name and password. I am getting an error of > > Fatal error: Call to undefined function is\_admin() in D:\xampp\htdocs\wordpress\wp-config.php on line 24 > > > How to use is\_admin() function in the wp-config.php file? can someone please help.
It's too early to use this WP built-in function. You can use it in some plugin or theme files, but not when WP enviroment is still loading. As I am not really sure if your intention is really correct, you have to use some other way (with PHP native functions) to distinct between front-end and administration. For example something like this: ``` if( strpos($_SERVER['REQUEST_URI'],'/wp-admin/') !== FALSE ) { define('DB_NAME', 'wp_db'); } else { ... } ``` But I don't think it is bulletproof solution. Ajax call are processed in administration, `wp-login.php` is not covered by the code above, etc.
189,911
<p>i tried many conditions to my footer.php section to include this function in my front page only and not on blog page...but it just pops up on both pages or none of them...can anyone explain the fault ?</p> <pre><code> &lt;?php if( is_home() &amp;&amp; is_front_page() ) : ?&gt; &lt;div id="blurbs"&gt; &lt;ul&gt; &lt;?php $the_query = new WP_Query( 'showposts=3' ); ?&gt; &lt;?php while ($the_query -&gt; have_posts()) : $the_query -&gt; the_post(); ?&gt; &lt;div class="postwrapper"&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;li style="display:inline; font-size: 20px; font-weight:light;"&gt;&lt;?php the_title(); ?&gt;&lt;/li&gt; &lt;br class="clear"&gt; &lt;li style=" font-size: 14px; font-weight:light;"&gt;&lt;?php the_content(); ?&gt;&lt;/li&gt; &lt;/div&gt; &lt;?php endwhile;?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 189915, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 0, "selected": false, "text": "<ul>\n<li>On the site front page, is_front_page() will always return TRUE,\nregardless of whether the site front page displays the blog posts\nindex or a static page. </li>\n<li>On the blog posts index, is_home() will\nalways return TRUE, regardless of whether the blog posts index is\ndisplayed on the site front page or a separate page.</li>\n</ul>\n\n<p>So try following condition instead:</p>\n\n<pre><code>&lt;?php if( 'page' == get_option( 'show_on_front' ) &amp;&amp; is_front_page() ) : ?&gt;\n</code></pre>\n" }, { "answer_id": 189921, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 5, "selected": true, "text": "<pre><code> &lt;?php if( is_front_page() ) : ?&gt;\n</code></pre>\n\n<p>is_home relates to the posts page according to your reading settings. is_front_page always returns true on the front page.</p>\n" }, { "answer_id": 189924, "author": "Piyush Rawat", "author_id": 73600, "author_profile": "https://wordpress.stackexchange.com/users/73600", "pm_score": -1, "selected": false, "text": "<p>wp_reset_query(); solved the problem...it was maybe due to loops running prior to this one..</p>\n" }, { "answer_id": 306728, "author": "Ден Покровский", "author_id": 145730, "author_profile": "https://wordpress.stackexchange.com/users/145730", "pm_score": -1, "selected": false, "text": "<p>wp_reset_query(); is realy worked, if you use custom queries before call check front page</p>\n" } ]
2015/05/30
[ "https://wordpress.stackexchange.com/questions/189911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73600/" ]
i tried many conditions to my footer.php section to include this function in my front page only and not on blog page...but it just pops up on both pages or none of them...can anyone explain the fault ? ``` <?php if( is_home() && is_front_page() ) : ?> <div id="blurbs"> <ul> <?php $the_query = new WP_Query( 'showposts=3' ); ?> <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?> <div class="postwrapper"> <?php the_post_thumbnail(); ?> <li style="display:inline; font-size: 20px; font-weight:light;"><?php the_title(); ?></li> <br class="clear"> <li style=" font-size: 14px; font-weight:light;"><?php the_content(); ?></li> </div> <?php endwhile;?> </ul> </div> <?php endif; ?> ```
``` <?php if( is_front_page() ) : ?> ``` is\_home relates to the posts page according to your reading settings. is\_front\_page always returns true on the front page.
189,965
<p>This is what I want: I have made a Custom Post Type in my theme and it shows in my home too, but the problem is that tha CPT takes the same elements and style of a default post in Wordpress, how I can assign a template for how my CPT is displayed at my home? When I say home I mean www.mysite.com (The content of index.php, this archive has the aspect of all the post in the home, so how I can create a dedicaded template to my CPT in the home) </p> <p>Check this code example of a theme in index.php, but doesn't work for me: </p> <pre><code>&lt;?php if (have_posts()) : ?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;?php if ( get_post_type() == 'reviews' ) : ?&gt; &lt;?php include( TEMPLATEPATH . '/includes/show-reviews-frontpage.php' ); ?&gt; &lt;?php elseif ( get_post_type() == 'videos' ) : ?&gt; &lt;?php include( TEMPLATEPATH . '/includes/show-videos-frontpage.php' ); ?&gt; &lt;?php elseif ( get_post_type() == 'screenshots' ) : ?&gt; &lt;?php include( TEMPLATEPATH . '/includes/show-screenshots-frontpage.php' ); ?&gt; &lt;?php else: ?&gt; &lt;?php include( TEMPLATEPATH . '/includes/show-posts-frontpage.php' ); ?&gt; &lt;?php endif; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; </code></pre> <p>Thanks a lot.</p>
[ { "answer_id": 189974, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>There is only one home/frontpage, so I'm not sure, what are you trying to achieve...</p>\n\n<p>Let's assume that your page is example.com and your CPT is books.</p>\n\n<p>If you'd like to change the look of home/frontpage (the page you see when you go to example.com), then use one of these templates.</p>\n\n<p>If you want to change the look of CPT index (the page you see when you go to example.com/books), then it is this CPT's archive template...</p>\n\n<p>If you'd like to show books on home, then you should use <code>pre_get_posts</code> action to change main query for home...</p>\n" }, { "answer_id": 189978, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 0, "selected": false, "text": "<p>You can create a page template (refer this <a href=\"https://developer.wordpress.org/themes/basics/page-templates/\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/page-templates/</a> ). The page template code shall have a custom query to show the poats from your custom post type. Then create page named let's say 'Home'. Assign that page template to it. Then from 'Settings > Reading' Select static page to 'Home'.</p>\n" }, { "answer_id": 190023, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": true, "text": "<p>I am thinking you probably want <a href=\"https://codex.wordpress.org/Function_Reference/get_template_part\" rel=\"nofollow\"><code>get_template_part()</code></a> to load CPT specific pieces of code. For example (from the Codex):</p>\n\n<pre><code>get_template_part( 'nav', 'single' ); // Navigation bar to use in single pages (nav-single.php)\n</code></pre>\n\n<p>You can then reuse pieces of code on your home page, your CPT archives, etc.</p>\n\n<p><a href=\"https://codex.wordpress.org/Post_Formats\" rel=\"nofollow\">You may also find post formats useful</a>, though I am still unclear about exactly what you want to accomplish.</p>\n\n<p>Take a look at the way Twenty Thirteen (for example), handles posts formats by using <code>content-aside.php</code>, <code>content-audio.php</code>, etc</p>\n" } ]
2015/05/30
[ "https://wordpress.stackexchange.com/questions/189965", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73891/" ]
This is what I want: I have made a Custom Post Type in my theme and it shows in my home too, but the problem is that tha CPT takes the same elements and style of a default post in Wordpress, how I can assign a template for how my CPT is displayed at my home? When I say home I mean www.mysite.com (The content of index.php, this archive has the aspect of all the post in the home, so how I can create a dedicaded template to my CPT in the home) Check this code example of a theme in index.php, but doesn't work for me: ``` <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php if ( get_post_type() == 'reviews' ) : ?> <?php include( TEMPLATEPATH . '/includes/show-reviews-frontpage.php' ); ?> <?php elseif ( get_post_type() == 'videos' ) : ?> <?php include( TEMPLATEPATH . '/includes/show-videos-frontpage.php' ); ?> <?php elseif ( get_post_type() == 'screenshots' ) : ?> <?php include( TEMPLATEPATH . '/includes/show-screenshots-frontpage.php' ); ?> <?php else: ?> <?php include( TEMPLATEPATH . '/includes/show-posts-frontpage.php' ); ?> <?php endif; ?> <?php endwhile; ?> <?php endif; ?> ``` Thanks a lot.
I am thinking you probably want [`get_template_part()`](https://codex.wordpress.org/Function_Reference/get_template_part) to load CPT specific pieces of code. For example (from the Codex): ``` get_template_part( 'nav', 'single' ); // Navigation bar to use in single pages (nav-single.php) ``` You can then reuse pieces of code on your home page, your CPT archives, etc. [You may also find post formats useful](https://codex.wordpress.org/Post_Formats), though I am still unclear about exactly what you want to accomplish. Take a look at the way Twenty Thirteen (for example), handles posts formats by using `content-aside.php`, `content-audio.php`, etc
189,981
<p>I know that you can remove the following line from the WordPress source code:</p> <pre><code>&lt;meta name="generator" content="WordPress 4.2.2" /&gt; </code></pre> <p>But instead of removing the tag completely, I just want to change its value. Is there a way to achieve that?</p>
[ { "answer_id": 189987, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 4, "selected": true, "text": "<p>Actually there is no hook there to change the texts on the fly. So the way is like below:</p>\n\n<p>Let's first remove the default one, use the following code in <code>functions.php</code>:</p>\n\n<pre><code>remove_action( 'wp_head', 'wp_generator' );\n</code></pre>\n\n<p>Now show our new one, add the following code in <code>functions.php</code>:</p>\n\n<pre><code>function wpse_custom_generator_meta_tag() { \n echo '&lt;meta name=\"generator\" content=\"Mr. Kauwa Kala\" /&gt;' . \"\\n\";\n}\nadd_action( 'wp_head', 'wpse_custom_generator_meta_tag' );\n</code></pre>\n" }, { "answer_id": 189988, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>If you want to target the <code>xhtml</code> type generator, you can use the <code>the_generator</code> filter:</p>\n\n<pre><code>/**\n * Change the version number to PI for the 'xhtml' type generator\n */\nadd_filter( 'the_generator', function ( $html, $type )\n{\n if( 'xhtml' === $type )\n $html = sprintf( '&lt;meta name=\"generator\" content=\"WordPress %f\"/&gt;', M_PI );\n return $html;\n}, 10, 2 );\n</code></pre>\n\n<p>or the <code>get_the_generator_{$type}</code> filter:</p>\n\n<pre><code>/**\n * Change the version number to PI for the 'xhtml' type generator\n */\nadd_filter( 'get_the_generator_xhtml', function ( $html )\n{\n return sprintf( '&lt;meta name=\"generator\" content=\"WordPress %f\"/&gt;', M_PI ); \n} );\n</code></pre>\n\n<p>Other types are <code>html</code>, <code>atom</code>, <code>rss2</code>, <code>rdf</code>, <code>comment</code> and <code>export</code>. They do not all use the same HTML structure.</p>\n\n<p>But I doubt it will do much for security, if that's the reason for changing it.</p>\n" } ]
2015/05/31
[ "https://wordpress.stackexchange.com/questions/189981", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70882/" ]
I know that you can remove the following line from the WordPress source code: ``` <meta name="generator" content="WordPress 4.2.2" /> ``` But instead of removing the tag completely, I just want to change its value. Is there a way to achieve that?
Actually there is no hook there to change the texts on the fly. So the way is like below: Let's first remove the default one, use the following code in `functions.php`: ``` remove_action( 'wp_head', 'wp_generator' ); ``` Now show our new one, add the following code in `functions.php`: ``` function wpse_custom_generator_meta_tag() { echo '<meta name="generator" content="Mr. Kauwa Kala" />' . "\n"; } add_action( 'wp_head', 'wpse_custom_generator_meta_tag' ); ```
189,982
<p>Sorry if this question is trivial. I'm just beginning to develop plugins in WordPress. </p> <p>In all the tutorials I found this: while creating the custom tables, <code>$wpdb-&gt;prefix</code> is used.</p> <p>Example:</p> <pre><code>$table_name = $wpdb-&gt;prefix . "liveshoutbox"; </code></pre> <p>My question: </p> <blockquote> <p>Is it mandatory to use <code>$wpdb-&gt;prefix</code>? What happens If I don't use prefix for my custom tables?</p> </blockquote>
[ { "answer_id": 189983, "author": "sakibmoon", "author_id": 23214, "author_profile": "https://wordpress.stackexchange.com/users/23214", "pm_score": 6, "selected": true, "text": "<p>It is mandatory, though it is not enforced.</p>\n\n<p>Consider the scenario when two Wordpress site has been setup in the same database. One with prefix <code>wp_</code> and another with <code>wp2_</code>. If you install your plugin in both of the sites with the prefix, your created tables will be <code>wp_liveshoutbox</code> for first site and <code>wp2_liveshoutbox</code> for the second site. But if you omit the prefix, both of the site will be using the same table named <code>liveshoutbox</code> and the whole thing will break up.</p>\n" }, { "answer_id": 190009, "author": "paul", "author_id": 73912, "author_profile": "https://wordpress.stackexchange.com/users/73912", "pm_score": 2, "selected": false, "text": "<p>Consider the following:</p>\n\n<p>Your plugin is used on a wordpress network, which uses different table prefixes for each site. Your plugin could be running simultaneously on 836 different sites, all in the same database. <code>wp_385677_liveshoutbox</code> is a perfectly reasonable table name.</p>\n\n<p>Your plugin is installed by a user who has some concept of security, and has changed the table prefix to block bots that try to inject <code>select * from wp_users</code> into the system. Even if they find a new vulnerability it won't work.</p>\n\n<p>Taking shortcuts like hardcoding table names is a good way to get a product up and running, but not a good way to release it. in a very short time the plugin will have a pile of \"doesn't work\" comments on it, in the worst case you will break someone else's site.</p>\n\n<p>If I have a complex query and I don't want to deal with the pain of writing <code>'select foo from ' . $wpdb-&gt;prefix . '_mytable left join ' . $wpdb-&gt;prefix . '_mytablemeta on ' . $wpdb-&gt;prefix . '.ID = ' . $wpdb-&gt;prefix . '.meta_id ....</code> you can use replacers. For example:</p>\n\n<pre><code>$query = 'select foo from %table% left join %meta% on %table%.ID = %meta%.meta_id ... ';\n\n$change = array (\n '%table%' =&gt; $wpdb-&gt;prefix . '_mytable',\n '%meta%' =&gt; $wpdb-&gt;prefix . '_mytablemeta'\n );\n\n\n$sql = str_replace( array_keys( $change ), array_values( $change ), $query );\n\n$results = $wpdb-&gt;get_results( $sql );\n</code></pre>\n\n<p>Wordpress is constantly changing. What \"works\" today may not work tomorrow. That's why there are API functions. The Wordpress developers will make sure the public API behaviour is consistent (or they will depreciate the function). If you start using internal method calls because it's 'faster that way' it will usually come back to bite you. There are very few true shortcuts in software - they just move the required work from now to later, and like your credit card \"later\" usually costs more.</p>\n" } ]
2015/05/31
[ "https://wordpress.stackexchange.com/questions/189982", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66633/" ]
Sorry if this question is trivial. I'm just beginning to develop plugins in WordPress. In all the tutorials I found this: while creating the custom tables, `$wpdb->prefix` is used. Example: ``` $table_name = $wpdb->prefix . "liveshoutbox"; ``` My question: > > Is it mandatory to use `$wpdb->prefix`? What happens If I don't use prefix for my custom tables? > > >
It is mandatory, though it is not enforced. Consider the scenario when two Wordpress site has been setup in the same database. One with prefix `wp_` and another with `wp2_`. If you install your plugin in both of the sites with the prefix, your created tables will be `wp_liveshoutbox` for first site and `wp2_liveshoutbox` for the second site. But if you omit the prefix, both of the site will be using the same table named `liveshoutbox` and the whole thing will break up.
189,985
<p>I made a parent theme and a child theme in one of my project. I enqueued CSS and JavaScripts in my parent theme like below:</p> <pre><code>function project_necessary_scripts() { //Stylesheets wp_register_style( 'bootstrap-css', get_template_directory_uri() .'/css/bootstrap.min.css' ); wp_register_style( 'bootstrap-map', get_template_directory_uri() .'/css/bootstrap.css.map' ); wp_register_style( 'project-css', get_stylesheet_uri() ); wp_enqueue_style( 'bootstrap-css' ); wp_enqueue_style( 'bootstrap-map' ); wp_enqueue_style( 'project-css' ); //JavaScripts wp_register_script( 'modernizr-js', get_template_directory_uri() .'/js/modernizr-2.8.3.min.js', array(), '2.8.3' ); wp_register_script( 'project-js', get_template_directory_uri() .'/js/project.min.js', array('jquery'), '20150401', true ); wp_enqueue_script( 'modernizr-js' ); wp_enqueue_script( 'project-js' ); } add_action( 'wp_enqueue_scripts', 'project_necessary_scripts' ); </code></pre> <p>Now, in my <strong>Child theme</strong> I want to dequeue some stylesheets and javascripts. So I used the following code:</p> <pre><code>function project_dequeue_unnecessary_scripts() { wp_dequeue_style( 'bootstrap-map' ); wp_dequeue_script( 'modernizr-js' ); wp_dequeue_script( 'project-js' ); } add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' ); </code></pre> <p>But actually the <code>bootstrap.css.map</code> file is still enqueuing, but the modernizr-js project-js is not loading, so it's working partially. How can I solve that?</p> <p>I even tried action priorities:</p> <pre><code>add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts', 11 ); </code></pre>
[ { "answer_id": 189986, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 6, "selected": true, "text": "<p>You are very nearer to the solution, because you are on the right path. Just to tweak a little bit:</p>\n\n<p>There are two such action hooks:</p>\n\n<ol>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_print_scripts\" rel=\"noreferrer\"><code>wp_print_scripts</code></a>, and</li>\n<li><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_print_styles\" rel=\"noreferrer\"><code>wp_print_styles</code></a></li>\n</ol>\n\n<p>So the way you can do it, is: hook 'em differently:</p>\n\n<pre><code>//Dequeue Styles\nfunction project_dequeue_unnecessary_styles() {\n wp_dequeue_style( 'bootstrap-map' );\n wp_deregister_style( 'bootstrap-map' );\n}\nadd_action( 'wp_print_styles', 'project_dequeue_unnecessary_styles' );\n\n//Dequeue JavaScripts\nfunction project_dequeue_unnecessary_scripts() {\n wp_dequeue_script( 'modernizr-js' );\n wp_deregister_script( 'modernizr-js' );\n wp_dequeue_script( 'project-js' );\n wp_deregister_script( 'project-js' );\n}\nadd_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );\n</code></pre>\n\n<p>And the correct way is to deregister them beside dequeuing. So first dequeue them, and then deregister them accordingly.</p>\n" }, { "answer_id": 386408, "author": "Morshed Alam Sumon", "author_id": 186443, "author_profile": "https://wordpress.stackexchange.com/users/186443", "pm_score": 2, "selected": false, "text": "<p>This is not the proper way. WordPress said not to use both wp_print_scripts, and\nwp_print_styles since WordPress 3.3.</p>\n<p>Either you are enqueueing or dequeueing, the proper way is:</p>\n<pre><code>function project_dequeue_unnecessary_scripts() {\n wp_dequeue_style( 'bootstrap-map' );\n wp_dequeue_script( 'modernizr-js' );\n}\nadd_action( 'wp_enqueue_scripts', 'project_dequeue_unnecessary_scripts', 100 );\n</code></pre>\n<p>Don't forget to use the priority. Without priority, it won't work.</p>\n" }, { "answer_id": 397265, "author": "Chandra Shekhar Pandey", "author_id": 128347, "author_profile": "https://wordpress.stackexchange.com/users/128347", "pm_score": 2, "selected": false, "text": "<p>For Dequeue Scripts, don't add the last &quot;-js&quot; or &quot;-css&quot; on ID part. I was using WordPress 5.8. It works for me.</p>\n<p>ABOVE CODE:</p>\n<pre><code>//Dequeue JavaScripts\nfunction project_dequeue_unnecessary_scripts() {\n wp_dequeue_script( 'modernizr-js' );\n wp_deregister_script( 'modernizr-js' );\n wp_dequeue_script( 'project-js' );\n wp_deregister_script( 'project-js' );\n}\nadd_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );\n\n</code></pre>\n<p>WORKING CODE:</p>\n<pre><code>//Dequeue JavaScripts\nfunction project_dequeue_unnecessary_scripts() {\n wp_dequeue_script( 'modernizr' );\n wp_deregister_script( 'modernizr' );\n wp_dequeue_script( 'project' );\n wp_deregister_script( 'project' );\n}\nadd_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );\n</code></pre>\n<p>Make sure to see the page source for script id first to remove the &quot;-js&quot; part. Remove last -js only.</p>\n<p>For eg:\nIf your Script ID is project-js-js then remove last <strong>-js</strong> only and use project-js on dequeue action. Same for CSS as well remove last <strong>&quot;-css&quot;</strong> part.</p>\n" } ]
2015/05/31
[ "https://wordpress.stackexchange.com/questions/189985", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
I made a parent theme and a child theme in one of my project. I enqueued CSS and JavaScripts in my parent theme like below: ``` function project_necessary_scripts() { //Stylesheets wp_register_style( 'bootstrap-css', get_template_directory_uri() .'/css/bootstrap.min.css' ); wp_register_style( 'bootstrap-map', get_template_directory_uri() .'/css/bootstrap.css.map' ); wp_register_style( 'project-css', get_stylesheet_uri() ); wp_enqueue_style( 'bootstrap-css' ); wp_enqueue_style( 'bootstrap-map' ); wp_enqueue_style( 'project-css' ); //JavaScripts wp_register_script( 'modernizr-js', get_template_directory_uri() .'/js/modernizr-2.8.3.min.js', array(), '2.8.3' ); wp_register_script( 'project-js', get_template_directory_uri() .'/js/project.min.js', array('jquery'), '20150401', true ); wp_enqueue_script( 'modernizr-js' ); wp_enqueue_script( 'project-js' ); } add_action( 'wp_enqueue_scripts', 'project_necessary_scripts' ); ``` Now, in my **Child theme** I want to dequeue some stylesheets and javascripts. So I used the following code: ``` function project_dequeue_unnecessary_scripts() { wp_dequeue_style( 'bootstrap-map' ); wp_dequeue_script( 'modernizr-js' ); wp_dequeue_script( 'project-js' ); } add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' ); ``` But actually the `bootstrap.css.map` file is still enqueuing, but the modernizr-js project-js is not loading, so it's working partially. How can I solve that? I even tried action priorities: ``` add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts', 11 ); ```
You are very nearer to the solution, because you are on the right path. Just to tweak a little bit: There are two such action hooks: 1. [`wp_print_scripts`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_print_scripts), and 2. [`wp_print_styles`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_print_styles) So the way you can do it, is: hook 'em differently: ``` //Dequeue Styles function project_dequeue_unnecessary_styles() { wp_dequeue_style( 'bootstrap-map' ); wp_deregister_style( 'bootstrap-map' ); } add_action( 'wp_print_styles', 'project_dequeue_unnecessary_styles' ); //Dequeue JavaScripts function project_dequeue_unnecessary_scripts() { wp_dequeue_script( 'modernizr-js' ); wp_deregister_script( 'modernizr-js' ); wp_dequeue_script( 'project-js' ); wp_deregister_script( 'project-js' ); } add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' ); ``` And the correct way is to deregister them beside dequeuing. So first dequeue them, and then deregister them accordingly.
189,999
<p>I know I am not supposed to use query_posts</p> <p>The thing is I have a program that already do that.</p> <pre><code>query_posts(""); echo "is_search():" . is_search(); query_posts("s=kucing"); echo "is_search after():" . is_search(); </code></pre> <p>Now the first echo returns empty.</p> <p>The second returns 1</p> <p>I wonder if there is some global variable I can set to 0 so that is_search() will return false even though I did </p> <pre><code>query_posts("s=kucing"); </code></pre>
[ { "answer_id": 190001, "author": "sakibmoon", "author_id": 23214, "author_profile": "https://wordpress.stackexchange.com/users/23214", "pm_score": 2, "selected": false, "text": "<p>You can use <code>global $wp_query</code> and set the <code>is_search</code> to false;</p>\n\n<pre><code>global $wp_query;\nquery_posts(\"\"); //is_search is false now\nquery_posts(\"s=kucing\"); //is_search is set to true\n$wp_query-&gt;is_search = false; //is_search is set to false\n</code></pre>\n" }, { "answer_id": 190007, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>Your real big problem here <strong>is</strong> the use of <code>query_posts</code>. It breaks the main query object, and sets the main query object to the query made by <code>query_posts</code>. What you are seeing is quite normal. </p>\n\n<p>Your real solution here with the use of <code>query_posts</code> would be is to reset the main query back to what it should be. This is where <code>wp_reset_query()</code> comes in. If this is a normal page, <code>is_search()</code> will return <code>false</code> after <code>wp_reset_query()</code> as the main query is reset to the page's main query.</p>\n\n<pre><code>query_posts( '&amp;s=crap' );\n// Do your loop as normal\nwp_reset_query(); // Add this after your loop\nvar_dump( is_search() ); // Will return bool ( false )\n</code></pre>\n\n<p>Remember, use of <code>query_posts</code> is highly discouraged. You should be using <code>WP_Query</code></p>\n" } ]
2015/05/31
[ "https://wordpress.stackexchange.com/questions/189999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73908/" ]
I know I am not supposed to use query\_posts The thing is I have a program that already do that. ``` query_posts(""); echo "is_search():" . is_search(); query_posts("s=kucing"); echo "is_search after():" . is_search(); ``` Now the first echo returns empty. The second returns 1 I wonder if there is some global variable I can set to 0 so that is\_search() will return false even though I did ``` query_posts("s=kucing"); ```
Your real big problem here **is** the use of `query_posts`. It breaks the main query object, and sets the main query object to the query made by `query_posts`. What you are seeing is quite normal. Your real solution here with the use of `query_posts` would be is to reset the main query back to what it should be. This is where `wp_reset_query()` comes in. If this is a normal page, `is_search()` will return `false` after `wp_reset_query()` as the main query is reset to the page's main query. ``` query_posts( '&s=crap' ); // Do your loop as normal wp_reset_query(); // Add this after your loop var_dump( is_search() ); // Will return bool ( false ) ``` Remember, use of `query_posts` is highly discouraged. You should be using `WP_Query`
190,000
<p>I noticed that if I don't explicitely enqueue my theme's main stylesheet and jQuery in my functions.php, these are loaded anyway. But perhaps it's better for some reason to enqueue them ? What is the right way of doing it ?</p>
[ { "answer_id": 190001, "author": "sakibmoon", "author_id": 23214, "author_profile": "https://wordpress.stackexchange.com/users/23214", "pm_score": 2, "selected": false, "text": "<p>You can use <code>global $wp_query</code> and set the <code>is_search</code> to false;</p>\n\n<pre><code>global $wp_query;\nquery_posts(\"\"); //is_search is false now\nquery_posts(\"s=kucing\"); //is_search is set to true\n$wp_query-&gt;is_search = false; //is_search is set to false\n</code></pre>\n" }, { "answer_id": 190007, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": false, "text": "<p>Your real big problem here <strong>is</strong> the use of <code>query_posts</code>. It breaks the main query object, and sets the main query object to the query made by <code>query_posts</code>. What you are seeing is quite normal. </p>\n\n<p>Your real solution here with the use of <code>query_posts</code> would be is to reset the main query back to what it should be. This is where <code>wp_reset_query()</code> comes in. If this is a normal page, <code>is_search()</code> will return <code>false</code> after <code>wp_reset_query()</code> as the main query is reset to the page's main query.</p>\n\n<pre><code>query_posts( '&amp;s=crap' );\n// Do your loop as normal\nwp_reset_query(); // Add this after your loop\nvar_dump( is_search() ); // Will return bool ( false )\n</code></pre>\n\n<p>Remember, use of <code>query_posts</code> is highly discouraged. You should be using <code>WP_Query</code></p>\n" } ]
2015/05/31
[ "https://wordpress.stackexchange.com/questions/190000", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11634/" ]
I noticed that if I don't explicitely enqueue my theme's main stylesheet and jQuery in my functions.php, these are loaded anyway. But perhaps it's better for some reason to enqueue them ? What is the right way of doing it ?
Your real big problem here **is** the use of `query_posts`. It breaks the main query object, and sets the main query object to the query made by `query_posts`. What you are seeing is quite normal. Your real solution here with the use of `query_posts` would be is to reset the main query back to what it should be. This is where `wp_reset_query()` comes in. If this is a normal page, `is_search()` will return `false` after `wp_reset_query()` as the main query is reset to the page's main query. ``` query_posts( '&s=crap' ); // Do your loop as normal wp_reset_query(); // Add this after your loop var_dump( is_search() ); // Will return bool ( false ) ``` Remember, use of `query_posts` is highly discouraged. You should be using `WP_Query`
190,055
<p>I don't know where the mistake is. My code is not creating a table in WAMP:</p> <pre><code>function subscribe_table() { global $wpdb; $table_name = $wpdb-&gt;prefix.'_databasesubs'; $charset_collate = $wpdb-&gt;get_charset_collate(); if ( $wpdb-&gt;get_var( 'SHOW TABLES LIKE '. $table_name ) != $table_name ) { $sql = "CREATE TABLE $table_name ( sno int(2) NOT NULL AUTO_INCREMENT, email varchar(25), name varchar(25), contact int(10) ) $charset_collate;"; } require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'subscribe_table' ); </code></pre>
[ { "answer_id": 190061, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 0, "selected": false, "text": "<p>Ramamoorthy,</p>\n\n<p>I reviewed your comment and there is no issue in code but check following details.</p>\n\n<p>Please deactive and again active your plugin. If you still encounter issue then follow the further steps from: <a href=\"http://premium.wpmudev.org/blog/creating-database-tables-for-plugins/\" rel=\"nofollow\">http://premium.wpmudev.org/blog/creating-database-tables-for-plugins/</a></p>\n\n<p>PS: If this stuff helps you please leave me a comment and support :) </p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 190064, "author": "Jaroslav Svetlik", "author_id": 67086, "author_profile": "https://wordpress.stackexchange.com/users/67086", "pm_score": 1, "selected": false, "text": "<p>Try edit Privileges for your wordpress database user from phpMyAdmin.</p>\n\n<p><img src=\"https://i.stack.imgur.com/bhMGY.png\" alt=\"enter image description here\"></p>\n" } ]
2015/06/01
[ "https://wordpress.stackexchange.com/questions/190055", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73934/" ]
I don't know where the mistake is. My code is not creating a table in WAMP: ``` function subscribe_table() { global $wpdb; $table_name = $wpdb->prefix.'_databasesubs'; $charset_collate = $wpdb->get_charset_collate(); if ( $wpdb->get_var( 'SHOW TABLES LIKE '. $table_name ) != $table_name ) { $sql = "CREATE TABLE $table_name ( sno int(2) NOT NULL AUTO_INCREMENT, email varchar(25), name varchar(25), contact int(10) ) $charset_collate;"; } require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'subscribe_table' ); ```
Try edit Privileges for your wordpress database user from phpMyAdmin. ![enter image description here](https://i.stack.imgur.com/bhMGY.png)
190,062
<p>I know you can easily display custom content if a certain logged in user is a certain role using </p> <pre><code>&lt;?php if ( current_user_can('contributor') ) : ?&gt; media files loop &lt;?php endif; ?&gt; </code></pre> <p>However, I want to do the same thing, but for a specific username, not the logged in user.</p> <p>I have user profiles in my wordpress website, some of them are artists, and If the profile being viewed is an artist I want to display their uploaded media. (and nothing to be returned if that profile being viewed is another role.)</p> <p>I have the variable to get the currently viewed profiles username, I just need the if statement.</p> <p>Something like: </p> media files loop
[ { "answer_id": 190066, "author": "Sebas", "author_id": 73266, "author_profile": "https://wordpress.stackexchange.com/users/73266", "pm_score": 0, "selected": false, "text": "<p>are you trying to check the \"username\"? if so:</p>\n\n<pre><code>&lt;?php \n$user = wp_get_current_user();\n$user = $user-&gt;user_login; ?&gt;\n\n&lt;?php if($user == \"John\"): ?&gt;\n media files loop\n&lt;?php endiif; ?&gt;\n</code></pre>\n" }, { "answer_id": 190078, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 3, "selected": true, "text": "<p>Chris Haugen,</p>\n\n<p>You need to check user role who have 'artist' role and then you need to act on some video loop stuff. </p>\n\n<p>Here's the solution:</p>\n\n<pre><code>$user = get_user_by('login', $username );\n\nif ( !empty( $user-&gt;roles ) &amp;&amp; is_array( $user-&gt;roles ) ) {\n foreach ( $user-&gt;roles as $role ){ \n if($role == 'artist')\n media files loop\n }\n}\n</code></pre>\n\n<p>get_user_by() is return user data of passed 'username'.</p>\n\n<p>Thanks!</p>\n" } ]
2015/06/01
[ "https://wordpress.stackexchange.com/questions/190062", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70950/" ]
I know you can easily display custom content if a certain logged in user is a certain role using ``` <?php if ( current_user_can('contributor') ) : ?> media files loop <?php endif; ?> ``` However, I want to do the same thing, but for a specific username, not the logged in user. I have user profiles in my wordpress website, some of them are artists, and If the profile being viewed is an artist I want to display their uploaded media. (and nothing to be returned if that profile being viewed is another role.) I have the variable to get the currently viewed profiles username, I just need the if statement. Something like: media files loop
Chris Haugen, You need to check user role who have 'artist' role and then you need to act on some video loop stuff. Here's the solution: ``` $user = get_user_by('login', $username ); if ( !empty( $user->roles ) && is_array( $user->roles ) ) { foreach ( $user->roles as $role ){ if($role == 'artist') media files loop } } ``` get\_user\_by() is return user data of passed 'username'. Thanks!
190,091
<p>Added a custom font as follows</p> <ol> <li><p>Uploaded web-font files and given them the 777 permission</p> <p><code>http://example.com/wp-content/themes/mytheme/css/fonts/</code></p></li> <li><p>Added rules to the css file </p> <p><code>@font-face { font-family: 'museo_sans700'; src: url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.eot'); src: url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.eot?#iefix') format('embedded-opentype'), url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.woff') format('woff'), url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.ttf') format('truetype'), url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.svg#museo_sans700') format('svg'); font-weight: normal; font-style: normal; } </code></p></li> </ol> <p>However, while using/accessing the font family, it gives a 404 error </p> <p>Attached snap <img src="https://i.stack.imgur.com/fjvAt.png" alt="enter image description here"></p> <p>Any clue?? Why this is happening??</p>
[ { "answer_id": 190092, "author": "sohan", "author_id": 69017, "author_profile": "https://wordpress.stackexchange.com/users/69017", "pm_score": 0, "selected": false, "text": "<p>404 stands for file are not available at the URL you are trying to access it. check your file path and files in your given directory.</p>\n\n<p>also check permissions:\npermission for file:644\ndirectory: 755</p>\n" }, { "answer_id": 190097, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 2, "selected": false, "text": "<p>Please use short path file url rather then absolute path.</p>\n\n<p>So code is like:</p>\n\n<pre><code>@font-face{ /* for IE */\nfont-family:FontFamily;\nsrc:url(Font.eot);\n}\n@font-face { /* for non-IE */\nfont-family:FontFamily;\nsrc:url(http://) format(\"No-IE-404\"),url(Font.ttf) format(\"truetype\");\n}\n</code></pre>\n\n<p>Make sure that readable web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily.</p>\n\n<p>If this is not your solution then you need to check <a href=\"https://stackoverflow.com/questions/4015816/why-is-font-face-throwing-a-404-error-on-woff-files\">https://stackoverflow.com/questions/4015816/why-is-font-face-throwing-a-404-error-on-woff-files</a>.</p>\n" }, { "answer_id": 403027, "author": "JonSnow", "author_id": 193127, "author_profile": "https://wordpress.stackexchange.com/users/193127", "pm_score": 1, "selected": false, "text": "<p>Seems like your server is not allowing to load woff and woff2 fonts.</p>\n<p>Please check this documentation. It has server config to enable woff and woff in Azure. <a href=\"https://base16solutions.wordpress.com/2017/11/09/issue-of-fonts-not-loading-on-azure-sites/\" rel=\"nofollow noreferrer\">https://base16solutions.wordpress.com/2017/11/09/issue-of-fonts-not-loading-on-azure-sites/</a></p>\n" } ]
2015/06/01
[ "https://wordpress.stackexchange.com/questions/190091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54871/" ]
Added a custom font as follows 1. Uploaded web-font files and given them the 777 permission `http://example.com/wp-content/themes/mytheme/css/fonts/` 2. Added rules to the css file `@font-face { font-family: 'museo_sans700'; src: url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.eot'); src: url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.eot?#iefix') format('embedded-opentype'), url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.woff') format('woff'), url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.ttf') format('truetype'), url('http://example.com/wp-content/themes/mytheme/css/fonts/museosans_700-webfont.svg#museo_sans700') format('svg'); font-weight: normal; font-style: normal; }` However, while using/accessing the font family, it gives a 404 error Attached snap ![enter image description here](https://i.stack.imgur.com/fjvAt.png) Any clue?? Why this is happening??
Please use short path file url rather then absolute path. So code is like: ``` @font-face{ /* for IE */ font-family:FontFamily; src:url(Font.eot); } @font-face { /* for non-IE */ font-family:FontFamily; src:url(http://) format("No-IE-404"),url(Font.ttf) format("truetype"); } ``` Make sure that readable web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily. If this is not your solution then you need to check <https://stackoverflow.com/questions/4015816/why-is-font-face-throwing-a-404-error-on-woff-files>.
190,094
<p>Is possible to create a child theme using various parents themes as template, instead of only a single parent?</p> <p><strong>Example:</strong> The child theme will be called 'Light', and his parents will be the theme 'Sky', the theme 'Color' and the theme 'Star'. It's possible call these three other themes in standard way to be the cores of the child theme?</p>
[ { "answer_id": 190092, "author": "sohan", "author_id": 69017, "author_profile": "https://wordpress.stackexchange.com/users/69017", "pm_score": 0, "selected": false, "text": "<p>404 stands for file are not available at the URL you are trying to access it. check your file path and files in your given directory.</p>\n\n<p>also check permissions:\npermission for file:644\ndirectory: 755</p>\n" }, { "answer_id": 190097, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 2, "selected": false, "text": "<p>Please use short path file url rather then absolute path.</p>\n\n<p>So code is like:</p>\n\n<pre><code>@font-face{ /* for IE */\nfont-family:FontFamily;\nsrc:url(Font.eot);\n}\n@font-face { /* for non-IE */\nfont-family:FontFamily;\nsrc:url(http://) format(\"No-IE-404\"),url(Font.ttf) format(\"truetype\");\n}\n</code></pre>\n\n<p>Make sure that readable web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily.</p>\n\n<p>If this is not your solution then you need to check <a href=\"https://stackoverflow.com/questions/4015816/why-is-font-face-throwing-a-404-error-on-woff-files\">https://stackoverflow.com/questions/4015816/why-is-font-face-throwing-a-404-error-on-woff-files</a>.</p>\n" }, { "answer_id": 403027, "author": "JonSnow", "author_id": 193127, "author_profile": "https://wordpress.stackexchange.com/users/193127", "pm_score": 1, "selected": false, "text": "<p>Seems like your server is not allowing to load woff and woff2 fonts.</p>\n<p>Please check this documentation. It has server config to enable woff and woff in Azure. <a href=\"https://base16solutions.wordpress.com/2017/11/09/issue-of-fonts-not-loading-on-azure-sites/\" rel=\"nofollow noreferrer\">https://base16solutions.wordpress.com/2017/11/09/issue-of-fonts-not-loading-on-azure-sites/</a></p>\n" } ]
2015/06/01
[ "https://wordpress.stackexchange.com/questions/190094", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63486/" ]
Is possible to create a child theme using various parents themes as template, instead of only a single parent? **Example:** The child theme will be called 'Light', and his parents will be the theme 'Sky', the theme 'Color' and the theme 'Star'. It's possible call these three other themes in standard way to be the cores of the child theme?
Please use short path file url rather then absolute path. So code is like: ``` @font-face{ /* for IE */ font-family:FontFamily; src:url(Font.eot); } @font-face { /* for non-IE */ font-family:FontFamily; src:url(http://) format("No-IE-404"),url(Font.ttf) format("truetype"); } ``` Make sure that readable web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily. If this is not your solution then you need to check <https://stackoverflow.com/questions/4015816/why-is-font-face-throwing-a-404-error-on-woff-files>.
190,122
<p>Got my brain scratching round a wee issue here.</p> <p>In short... </p> <ol> <li><p>If home page, then do nothing</p></li> <li><p>if page has a thumbnail then run code that pops the page title on top of full width thumbnail with suitable CSS</p></li> <li><p>If no thumbnail then show normal entry title</p></li> </ol> <p>Got so far but no further. Any help would be greatly appreciated.</p> <pre><code>&lt;header class="entry-header"&gt; &lt;?php if ( is_front_page() ) { // This is the home page and do nothing } else { // if thumbnail show it and add title if ( has_post_thumbnail()) : the_post_thumbnail('full'); ?&gt; &lt;div class="single-featured-image"&gt; &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;/div&gt; &lt;?php } else { // if no thumbnail then just print title as usual ?&gt; &lt;div class="entry-title"&gt; &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;/div&gt; &lt;?php } } ?&gt; </code></pre>
[ { "answer_id": 190123, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Write it out in english and be clear about your logic, aka if you say that X should happen when Y is true, what happens if Y is false? AKA <code>else</code>. If X then Y, else Z</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>If we're on the home page,\n then do nothing\notherwise\n if the page has a thumbnail then\n run code that pops the page title on top of full width thumbnail with suitable CSS\n otherwise,\n just show normal entry title\n</code></pre>\n\n<p>Also notice the consistent indentation, keeping code indented properly is extremely important and prevents a huge raft of obvious bugs. Good editors will auto-indent for you.</p>\n\n<p>Your code doesn't indent correctly, it also mixes 2 types of if statement together, <code>if() { }</code> and <code>if () : endif;</code>, resulting in <code>if() : }</code> which is a syntax error. So put your opening if statement on its own line, and the closing part on its own line so it's really obvious what's happening. A good editor will automatically write out the <code>{</code> and <code>}</code> for you, saving you the effort. If your editor doesn't do these things, you need to switch, there are numerous free editors and paid editors that will do this and more as standard</p>\n" }, { "answer_id": 190124, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 2, "selected": true, "text": "<p>If I understood you correctly:</p>\n\n<pre><code>&lt;?php\n//if home, do nothing\nif( ! is_home() || ! front_page() ) {\n\n //if has post thumbnail\n if( has_post_thumbnail() ) { \n the_post_thumbnail( 'full' );\n echo '&lt;h1 class=\"entry-title\"&gt;'. get_the_title() .'&lt;/h1&gt;';\n } else { \n //no post thumbnail, show normal entry title\n echo '&lt;h1 class=\"entry-title\"&gt;'. get_the_title() .'&lt;/h1&gt;';\n }\n\n}\n</code></pre>\n\n<p>or, it can be done easily:</p>\n\n<pre><code>&lt;?php\nif( ! is_home() || ! is_front_page() ) {\n\n if( has_post_thumbnail() )\n the_post_thumbnail( 'full' );\n echo '&lt;h1 class=\"entry-title\"&gt;'. get_the_title() .'&lt;/h1&gt;';\n\n}\n</code></pre>\n" } ]
2015/06/01
[ "https://wordpress.stackexchange.com/questions/190122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73976/" ]
Got my brain scratching round a wee issue here. In short... 1. If home page, then do nothing 2. if page has a thumbnail then run code that pops the page title on top of full width thumbnail with suitable CSS 3. If no thumbnail then show normal entry title Got so far but no further. Any help would be greatly appreciated. ``` <header class="entry-header"> <?php if ( is_front_page() ) { // This is the home page and do nothing } else { // if thumbnail show it and add title if ( has_post_thumbnail()) : the_post_thumbnail('full'); ?> <div class="single-featured-image"> <h1><?php the_title(); ?></h1> </div> <?php } else { // if no thumbnail then just print title as usual ?> <div class="entry-title"> <h1><?php the_title(); ?></h1> </div> <?php } } ?> ```
If I understood you correctly: ``` <?php //if home, do nothing if( ! is_home() || ! front_page() ) { //if has post thumbnail if( has_post_thumbnail() ) { the_post_thumbnail( 'full' ); echo '<h1 class="entry-title">'. get_the_title() .'</h1>'; } else { //no post thumbnail, show normal entry title echo '<h1 class="entry-title">'. get_the_title() .'</h1>'; } } ``` or, it can be done easily: ``` <?php if( ! is_home() || ! is_front_page() ) { if( has_post_thumbnail() ) the_post_thumbnail( 'full' ); echo '<h1 class="entry-title">'. get_the_title() .'</h1>'; } ```
190,147
<p>I can't figure out why the media uploader doesn't show. I'm trying to do a media upload window so the user can upload a file. The problem is, when I click on the Upload button, nothing happens, the window is not shown and I don't know why. I think it has something to do that the submenu in which I want to add the uploader is in a custom post type. The js code for the media upload:</p> <pre><code> $('#csv_file_button').click(function() { formfield = $('#csv_file').attr('name'); tb_show('', 'media-upload.php?type=file&amp;amp;TB_iframe=true'); return false; }); window.send_to_editor = function(html) { // Send WP media uploader response url = $(html).attr('href'); $('#csv_file').val(url); tb_remove(); } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 190168, "author": "dea", "author_id": 73049, "author_profile": "https://wordpress.stackexchange.com/users/73049", "pm_score": 2, "selected": false, "text": "<p>I couldn't find what was wrong with the code, so I used a different code which I found on the internet and now the window is opening. </p>\n\n<pre><code>var file_frame;\n$('#csv_file_button').on('click', function(event){\n event.preventDefault();\n if ( file_frame ) {\n file_frame.open();\n return;\n}\n// Create the media frame.\nfile_frame = wp.media.frames.file_frame = wp.media({\n title: $( this ).data( 'File upload' ),\n button: {\n text: $( this ).data( 'Upload' ),\n },\n multiple: false // Set to true to allow multiple files to be selected\n});\n// When an image is selected, run a callback.\nfile_frame.on( 'select', function() {\n // We set multiple to false so only get one image from the uploader\n attachment = file_frame.state().get('selection').first().toJSON();\n $('#csv_file').attr('value',attachment.url);\n});\n\n// Finally, open the modal\nfile_frame.open();\n});\n</code></pre>\n" }, { "answer_id": 190186, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 1, "selected": false, "text": "<p>Unable to identify where the issue is. So we need to trace your code and for that you need to replace below JS code with your first one:</p>\n\n<pre><code>$('#csv_file_button').click(function() {\n alert('Button clicked');\n formfield = $('#csv_file').attr('name');\n alert('formfield name is &gt;&gt; ' + formfield);\n tb_show('', 'media-upload.php?type=file&amp;amp;TB_iframe=true');\n alert('Finally thick box randered..! No issue here');\n return false;\n}); \n</code></pre>\n\n<p>Let me know what you facing after replacing this code and click on Upload button..!</p>\n\n<p>Feel free to contact me if you still face the same issue.</p>\n\n<p>Thanks!</p>\n" }, { "answer_id": 223244, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 1, "selected": false, "text": "<p>First you need to include thickbox into your theme to use tb_show popup</p>\n\n<pre><code>function include_thickbox_scripts() \n{\n // include the javascript \n wp_enqueue_script('thickbox', null, array('jquery'));\n\n // include the thickbox styles \n wp_enqueue_style('thickbox.css', '/'.WPINC.'/js/thickbox/thickbox.css', null, '1.0');\n\n}\n\nadd_action('wp_enqueue_scripts', 'include_thickbox_scripts');\n</code></pre>\n" } ]
2015/06/01
[ "https://wordpress.stackexchange.com/questions/190147", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73049/" ]
I can't figure out why the media uploader doesn't show. I'm trying to do a media upload window so the user can upload a file. The problem is, when I click on the Upload button, nothing happens, the window is not shown and I don't know why. I think it has something to do that the submenu in which I want to add the uploader is in a custom post type. The js code for the media upload: ``` $('#csv_file_button').click(function() { formfield = $('#csv_file').attr('name'); tb_show('', 'media-upload.php?type=file&amp;TB_iframe=true'); return false; }); window.send_to_editor = function(html) { // Send WP media uploader response url = $(html).attr('href'); $('#csv_file').val(url); tb_remove(); } ``` Any ideas?
I couldn't find what was wrong with the code, so I used a different code which I found on the internet and now the window is opening. ``` var file_frame; $('#csv_file_button').on('click', function(event){ event.preventDefault(); if ( file_frame ) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: $( this ).data( 'File upload' ), button: { text: $( this ).data( 'Upload' ), }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected, run a callback. file_frame.on( 'select', function() { // We set multiple to false so only get one image from the uploader attachment = file_frame.state().get('selection').first().toJSON(); $('#csv_file').attr('value',attachment.url); }); // Finally, open the modal file_frame.open(); }); ```
190,170
<p>I am trying to remove background and header from appearance menu, but they don't seem to go away! I think it's because I have activated customize, but can I remove them anyway without using CSS or JS?</p> <p>Here is my code:</p> <pre><code>add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999); function remove_unnecessary_wordpress_menus(){ remove_menu_page('themes.php?page=custom-background'); remove_submenu_page('themes.php', 'custom-background'); remove_submenu_page('themes.php', 'custom-header'); } </code></pre> <p>Thanks in advance!</p>
[ { "answer_id": 190175, "author": "James Cushing", "author_id": 67327, "author_profile": "https://wordpress.stackexchange.com/users/67327", "pm_score": 3, "selected": true, "text": "<p>As overcomplicated as it sounds, I always find the best way to handle admin menu modifications is to overlook the given wordpress <code>remove_</code> functions and go straight to the <code>$menu</code> and <code>$submenu</code> globals. In the case you've specified here, you'd want to change your code to:</p>\n\n<pre><code>add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999);\n\nfunction remove_unnecessary_wordpress_menus(){\n global $submenu;\n unset($submenu['themes.php'][20]);\n unset($submenu['themes.php'][22]);\n}\n</code></pre>\n\n<p>The indices of the pages in the <code>themes.php</code> array seem strange, but what isn't when you try to hack WP?! A good reference for using these globals can be found <a href=\"http://code.tutsplus.com/articles/customizing-your-wordpress-admin--wp-24941\" rel=\"nofollow\">here</a>.</p>\n\n<p>EDIT: Just a thought, given the varying amounts of plugins etc. which could (potentially, but not definitely) change the index of a given menu/submenu item in the array, it'd be a good idea to check the numbers required if the snippet I've provided doesn't work. You can do that by modifying the code slightly to this:</p>\n\n<pre><code>add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999);\n\nfunction remove_unnecessary_wordpress_menus(){\n global $submenu;\n //Left margin is to account for the admin sidebar menu\n echo '&lt;pre style=\"margin-left:11em\"&gt;';\n print_r($submenu);\n echo '&lt;/pre&gt;';\n}\n</code></pre>\n\n<p>This will 'pretty' print the <code>$submenu</code> array, from which you can find the exact numbers you need.</p>\n\n<p>EDIT: Since I don't have the rep to comment on this community yet, it's worth pointing out that @Fredrik did a good job of generalisation. +1.</p>\n" }, { "answer_id": 190184, "author": "Fredrik", "author_id": 74011, "author_profile": "https://wordpress.stackexchange.com/users/74011", "pm_score": 3, "selected": false, "text": "<p>Here is my final of the code. Thanks for the fast answer!</p>\n\n<pre><code>add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999);\n\nfunction remove_unnecessary_wordpress_menus(){\n global $submenu;\n foreach($submenu['themes.php'] as $menu_index =&gt; $theme_menu){\n if($theme_menu[0] == 'Header' || $theme_menu[0] == 'Background')\n unset($submenu['themes.php'][$menu_index]);\n }\n}\n</code></pre>\n" }, { "answer_id": 192536, "author": "Paal Joachim Romdahl", "author_id": 75194, "author_profile": "https://wordpress.stackexchange.com/users/75194", "pm_score": 1, "selected": false, "text": "<p>Here is another option to remove header and background (<a href=\"https://wordpress.org/support/topic/remove-header-and-background-option-pages-in-twenty-eleven-child-theme?replies=11\" rel=\"nofollow\">source</a>):</p>\n\n<pre><code>//Remove the custom options provided by the default twentyeleven theme. \nadd_action( 'after_setup_theme','remove_twentyeleven_options', 100 );\nfunction remove_twentyeleven_options() { \n remove_custom_background();\n remove_custom_image_header();\n remove_action('admin_menu', 'twentyeleven_theme_options_add_page'); \n}\n</code></pre>\n" }, { "answer_id": 315267, "author": "Yutaro Ikeda", "author_id": 151333, "author_profile": "https://wordpress.stackexchange.com/users/151333", "pm_score": 2, "selected": false, "text": "<p>Thanks all! Here is the code within WordPress 4.9.8.</p>\n\n<pre><code>function remove_header_and_bg(){\n global $submenu;\n unset($submenu['themes.php'][6]); // customize\n unset($submenu['themes.php'][15]); // header_image\n unset($submenu['themes.php'][20]); // background_image\n}\nadd_action( 'admin_menu', 'remove_header_and_bg', 999 );\n</code></pre>\n" }, { "answer_id": 344658, "author": "KittMedia", "author_id": 137048, "author_profile": "https://wordpress.stackexchange.com/users/137048", "pm_score": 0, "selected": false, "text": "<p>Another version without need to use a loop is to use the correct identifier, which can be displayed by <code>var_dump</code> the global <code>$submenu</code>.</p>\n\n<pre><code>function remove_unnecessary_wordpress_menus(){\n remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwp-admin%2Findex.php&amp;#038;autofocus%5Bcontrol%5D=header_image' );\n remove_submenu_page( 'themes.php', 'customize.php?return=%2Fwp-admin%2Findex.php&amp;#038;autofocus%5Bcontrol%5D=background_image' );\n}\n\nadd_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999);\n</code></pre>\n\n<p>This works only if the path to the website is <code>/</code>, otherwise you need to add the path after <code>customize.php?return=</code>, e. g. <code>customize.php?return=%2Fwordpress%2F</code> if the path is <code>/wordpress/</code>.</p>\n\n<p>It’s also possible to handle the path automatically:</p>\n\n<pre><code>function remove_unnecessary_wordpress_menus(){\n $site_path = rawurlencode( get_blog_details()-&gt;path );\n\n remove_submenu_page( 'themes.php', 'customize.php?return=' . $site_path . 'wp-admin%2Findex.php&amp;#038;autofocus%5Bcontrol%5D=header_image' );\n remove_submenu_page( 'themes.php', 'customize.php?return=' . $site_path . 'wp-admin%2Findex.php&amp;#038;autofocus%5Bcontrol%5D=background_image' );\n}\n\nadd_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999);\n</code></pre>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190170", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74011/" ]
I am trying to remove background and header from appearance menu, but they don't seem to go away! I think it's because I have activated customize, but can I remove them anyway without using CSS or JS? Here is my code: ``` add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999); function remove_unnecessary_wordpress_menus(){ remove_menu_page('themes.php?page=custom-background'); remove_submenu_page('themes.php', 'custom-background'); remove_submenu_page('themes.php', 'custom-header'); } ``` Thanks in advance!
As overcomplicated as it sounds, I always find the best way to handle admin menu modifications is to overlook the given wordpress `remove_` functions and go straight to the `$menu` and `$submenu` globals. In the case you've specified here, you'd want to change your code to: ``` add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999); function remove_unnecessary_wordpress_menus(){ global $submenu; unset($submenu['themes.php'][20]); unset($submenu['themes.php'][22]); } ``` The indices of the pages in the `themes.php` array seem strange, but what isn't when you try to hack WP?! A good reference for using these globals can be found [here](http://code.tutsplus.com/articles/customizing-your-wordpress-admin--wp-24941). EDIT: Just a thought, given the varying amounts of plugins etc. which could (potentially, but not definitely) change the index of a given menu/submenu item in the array, it'd be a good idea to check the numbers required if the snippet I've provided doesn't work. You can do that by modifying the code slightly to this: ``` add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999); function remove_unnecessary_wordpress_menus(){ global $submenu; //Left margin is to account for the admin sidebar menu echo '<pre style="margin-left:11em">'; print_r($submenu); echo '</pre>'; } ``` This will 'pretty' print the `$submenu` array, from which you can find the exact numbers you need. EDIT: Since I don't have the rep to comment on this community yet, it's worth pointing out that @Fredrik did a good job of generalisation. +1.
190,194
<p>I want to use Wordpress multisite with subdomain and directory simultaneously like</p> <pre>http://site1.wp.com http://site2.wp.com http://wp.com/site3</pre> <p>All of the sub sites will be using same database and code. Is there any way to use subdomain and directory at the same time?</p>
[ { "answer_id": 190216, "author": "Jan Beck", "author_id": 18760, "author_profile": "https://wordpress.stackexchange.com/users/18760", "pm_score": 1, "selected": false, "text": "<p>It can be done, I'm actually using it for my private multisite installation.</p>\n\n<ol>\n<li>Install WP multisite and set it up in \"subdirectory-mode\"</li>\n<li>Install and setup the <a href=\"https://premium.wpmudev.org/project/domain-mapping/\" rel=\"nofollow\">Domain Mapping plugin</a> by WPMU</li>\n<li>Create a subdomain and point it to your installation. Add this subdomain via the Domain Mapping plugin. </li>\n</ol>\n\n<p>By default your new sub-sites are accessible in a subdirectory but if you apply step 3 it can be accessed via the subdomain as well. </p>\n" }, { "answer_id": 408973, "author": "Derin Tolu", "author_id": 225248, "author_profile": "https://wordpress.stackexchange.com/users/225248", "pm_score": 0, "selected": false, "text": "<p>There is no need for the plugin anymore. Domain mapping is native.</p>\n<p>Once the site is created you can change the domain to anything you like. the base domain will still follow the intial configuration, but once created, you can change it easily.</p>\n<p><a href=\"https://wordpress.org/support/article/wordpress-multisite-domain-mapping/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/wordpress-multisite-domain-mapping/</a></p>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190194", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74028/" ]
I want to use Wordpress multisite with subdomain and directory simultaneously like ``` http://site1.wp.com http://site2.wp.com http://wp.com/site3 ``` All of the sub sites will be using same database and code. Is there any way to use subdomain and directory at the same time?
It can be done, I'm actually using it for my private multisite installation. 1. Install WP multisite and set it up in "subdirectory-mode" 2. Install and setup the [Domain Mapping plugin](https://premium.wpmudev.org/project/domain-mapping/) by WPMU 3. Create a subdomain and point it to your installation. Add this subdomain via the Domain Mapping plugin. By default your new sub-sites are accessible in a subdirectory but if you apply step 3 it can be accessed via the subdomain as well.
190,242
<p>I'm trying to fetch both the first_name and last_name of all users at the same time, using the wpdb-object and the wp_usermeta table. I can't seem to figure out how to get both in the same query. Below is what I've got so far.</p> <pre><code>global $wpdb; $ansatte = $wpdb-&gt;get_results("SELECT user_id, meta_value AS first_name FROM wp_usermeta WHERE meta_key='first_name'"); foreach ($ansatte as $ansatte) { echo $ansatte-&gt;first_name; } </code></pre> <p>Using the above code I'm able to echo out the first names of all users, but i would like for the last_name to be available aswell, like so;</p> <pre><code>foreach ($ansatte as $ansatte) { echo $ansatte-&gt;first_name . ' ' $ansatte-&gt;last_name; } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 190244, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 4, "selected": true, "text": "<p>I can't find a clean, native way to pull this data. There are a couple of ways I can think of to do this: First, something like:</p>\n\n<pre><code>$sql = \"\n SELECT user_id,meta_key,meta_value\n FROM {$wpdb-&gt;usermeta} \n WHERE ({$wpdb-&gt;usermeta}.meta_key = 'first_name' OR {$wpdb-&gt;usermeta}.meta_key = 'last_name')\";\n$ansatte = $wpdb-&gt;get_results($sql);\nvar_dump($sql);\n$users = array();\nforeach ($ansatte as $a) {\n $users[$a-&gt;user_id][$a-&gt;meta_key] = $a-&gt;meta_value;\n}\nvar_dump($users);\n</code></pre>\n\n<p>You can then do:</p>\n\n<pre><code>foreach ($users as $u) {\n echo $u['first_name'].' '.$u['last_name'];\n}\n</code></pre>\n\n<p>... to <code>echo</code> your user names.</p>\n\n<p>The second way, a more pure SQL way, is what you were attempting:</p>\n\n<pre><code>$sql = \"\n SELECT {$wpdb-&gt;usermeta}.user_id,{$wpdb-&gt;usermeta}.meta_value as first_name,m2.meta_value as last_name\n FROM {$wpdb-&gt;usermeta} \n INNER JOIN {$wpdb-&gt;usermeta} as m2 ON {$wpdb-&gt;usermeta}.user_id = m2.user_id\n WHERE ({$wpdb-&gt;usermeta}.meta_key = 'first_name' \n AND m2.meta_key = 'last_name')\";\n$ansatte = $wpdb-&gt;get_results($sql);\n\nforeach ($ansatte as $ansatte) {\n echo $ansatte-&gt;first_name . ' ' . $ansatte-&gt;last_name;\n}\n</code></pre>\n\n<p>You could also use <code>get_users()</code> or <code>WP_User_Query</code> to pull users but the meta_data you want isn't in the data returned and it would take more work to retrieve it.</p>\n" }, { "answer_id": 259230, "author": "Willy Richardson", "author_id": 114942, "author_profile": "https://wordpress.stackexchange.com/users/114942", "pm_score": 3, "selected": false, "text": "<p>This is a straight MySQL pivot answer for phpMyAdmin assuming your Wordpress table prefix is \"wp_\";</p>\n\n<pre><code>SELECT\n t1.id, t1.user_email,\n MAX(CASE WHEN t2.meta_key = 'first_name' THEN meta_value END) AS first_name,\n MAX(CASE WHEN t2.meta_key = 'last_name' THEN meta_value END) AS last_name \nFROM wp_users AS t1 \nINNER JOIN wp_usermeta AS t2 ON t1.id = t2.user_id\nGROUP BY t1.id, t1.user_email;\n</code></pre>\n" }, { "answer_id": 379512, "author": "William Entriken", "author_id": 34194, "author_profile": "https://wordpress.stackexchange.com/users/34194", "pm_score": 0, "selected": false, "text": "<p>This is the correct approach using just SQL:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT id\n , (SELECT MAX(meta_value) FROM wp_usermeta WHERE ID = wp_usermeta.user_id AND meta_key = 'first_name') first_name\n , (SELECT MAX(meta_value) FROM wp_usermeta WHERE ID = wp_usermeta.user_id AND meta_key = 'last_name') last_name\n FROM wp_users\n</code></pre>\n<p>Here are approaches that don't work:</p>\n<ul>\n<li>JOIN once for each metadata field does not work because there is no UNIQUE key on wp_usermeta(user_id, meta_key)</li>\n<li>Using subquery SELECT without MAX fails because there is no UNIQUE key on wp_usermeta(user_id, meta_key)</li>\n</ul>\n<p>And for some reason this is faster than using a single select and join.</p>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190242", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68915/" ]
I'm trying to fetch both the first\_name and last\_name of all users at the same time, using the wpdb-object and the wp\_usermeta table. I can't seem to figure out how to get both in the same query. Below is what I've got so far. ``` global $wpdb; $ansatte = $wpdb->get_results("SELECT user_id, meta_value AS first_name FROM wp_usermeta WHERE meta_key='first_name'"); foreach ($ansatte as $ansatte) { echo $ansatte->first_name; } ``` Using the above code I'm able to echo out the first names of all users, but i would like for the last\_name to be available aswell, like so; ``` foreach ($ansatte as $ansatte) { echo $ansatte->first_name . ' ' $ansatte->last_name; } ``` Any ideas?
I can't find a clean, native way to pull this data. There are a couple of ways I can think of to do this: First, something like: ``` $sql = " SELECT user_id,meta_key,meta_value FROM {$wpdb->usermeta} WHERE ({$wpdb->usermeta}.meta_key = 'first_name' OR {$wpdb->usermeta}.meta_key = 'last_name')"; $ansatte = $wpdb->get_results($sql); var_dump($sql); $users = array(); foreach ($ansatte as $a) { $users[$a->user_id][$a->meta_key] = $a->meta_value; } var_dump($users); ``` You can then do: ``` foreach ($users as $u) { echo $u['first_name'].' '.$u['last_name']; } ``` ... to `echo` your user names. The second way, a more pure SQL way, is what you were attempting: ``` $sql = " SELECT {$wpdb->usermeta}.user_id,{$wpdb->usermeta}.meta_value as first_name,m2.meta_value as last_name FROM {$wpdb->usermeta} INNER JOIN {$wpdb->usermeta} as m2 ON {$wpdb->usermeta}.user_id = m2.user_id WHERE ({$wpdb->usermeta}.meta_key = 'first_name' AND m2.meta_key = 'last_name')"; $ansatte = $wpdb->get_results($sql); foreach ($ansatte as $ansatte) { echo $ansatte->first_name . ' ' . $ansatte->last_name; } ``` You could also use `get_users()` or `WP_User_Query` to pull users but the meta\_data you want isn't in the data returned and it would take more work to retrieve it.
190,248
<p>I want to to get the Author name of the Parent theme.</p> <p>I can get the theme name using wp_get_theme() to get the theme object of the current (child) theme. From this I can get the parent theme name. </p> <p>Next I think I need to get the object of the parent theme, but unsure how best to approach this. Here is my code so far:</p> <pre><code>$style_parent_theme = wp_get_theme(); $style_parent_theme_dir = $style_parent_theme-&gt;get( 'Template' ); $style_parent_theme_name = wp_get_theme($parent_theme_dir); $style_parent_theme_author = $style_parent_theme_name-&gt;get( 'Author' ); if ($style_parent_theme_author == "WooThemes") { </code></pre>
[ { "answer_id": 190285, "author": "JediTricks007", "author_id": 49017, "author_profile": "https://wordpress.stackexchange.com/users/49017", "pm_score": 0, "selected": false, "text": "<p>This works for me.</p>\n\n<pre><code> &lt;?php\n $my_theme = wp_get_theme('parentThemeName');\n echo $my_theme-&gt;get( 'Author' );\n ?&gt;\n</code></pre>\n" }, { "answer_id": 190287, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": false, "text": "<p>Line 3 of your code reads:</p>\n\n<p><code>$style_parent_theme_name = wp_get_theme($parent_theme_dir);</code></p>\n\n<p>it should be:</p>\n\n<p><code>$style_parent_theme_name = wp_get_theme($style_parent_theme_dir);</code></p>\n\n<p>otherwise the code is correct.</p>\n" }, { "answer_id": 190296, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>You can get this value about the child theme. At first get your child theme date. The simplest way is the function <code>wp_get_theme()</code>, see <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_theme\" rel=\"nofollow\">codex</a> for the parameters and more information. You get a object with all relevant information about the current theme. In step two check, if is a child theme and then get his parent information, like the follow source.</p>\n\n<pre><code>// Current WP_Theme object.\n// Get this data via hook or class WP_Theme\n// As wrapper, simple to sue is the function wp_get_theme()\n$theme_data = wp_get_theme();\n$is_child = $this-&gt;is_child( $theme_data );\n\nif ( $is_child ) {\n $parent_name = $theme_data-&gt;parent()-&gt;Name;\n}\n</code></pre>\n\n<p>The method <code>is_child</code> is simple:</p>\n\n<pre><code>function is_child( $theme_data ) {\n // For limitation of empty() write in var\n $parent = $theme_data-&gt;parent();\n if ( ! empty( $parent ) ) {\n return TRUE;\n }\n return FALSE;\n}\n</code></pre>\n" }, { "answer_id": 190298, "author": "ejntaylor", "author_id": 38077, "author_profile": "https://wordpress.stackexchange.com/users/38077", "pm_score": 3, "selected": false, "text": "<p>Thanks for all the help which pointed me in the right direction. In the end I used the following:</p>\n\n<pre><code>$style_parent_theme = wp_get_theme(get_template());\n$style_parent_theme_author = $style_parent_theme-&gt;get( 'Author' );\n</code></pre>\n\n<p>I use get_template() to recover the folder name of the parent theme.</p>\n\n<p>wp_get_theme then get's the theme object.</p>\n\n<p>Once we have that we can manipulate the object to get the author name.</p>\n" }, { "answer_id": 240241, "author": "Benn", "author_id": 67176, "author_profile": "https://wordpress.stackexchange.com/users/67176", "pm_score": 0, "selected": false, "text": "<p>simple function </p>\n\n<pre><code>function show_theme_author(){\n\n $theme = wp_get_theme();\n\n return $theme-&gt;get('Author');\n\n}\n</code></pre>\n" }, { "answer_id": 250769, "author": "Web-Entwickler", "author_id": 92649, "author_profile": "https://wordpress.stackexchange.com/users/92649", "pm_score": 2, "selected": false, "text": "<p>I was searching for getting the name of the parent theme and stumbled over this post.</p>\n\n<p>I think the best solution is not mentioned here:</p>\n\n<pre><code>wp_get_theme()-&gt;parent()-&gt;get( 'Author' );\n</code></pre>\n\n<p>or what I needed:</p>\n\n<pre><code>wp_get_theme()-&gt;parent()-&gt;get( 'Name' )\n</code></pre>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190248", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38077/" ]
I want to to get the Author name of the Parent theme. I can get the theme name using wp\_get\_theme() to get the theme object of the current (child) theme. From this I can get the parent theme name. Next I think I need to get the object of the parent theme, but unsure how best to approach this. Here is my code so far: ``` $style_parent_theme = wp_get_theme(); $style_parent_theme_dir = $style_parent_theme->get( 'Template' ); $style_parent_theme_name = wp_get_theme($parent_theme_dir); $style_parent_theme_author = $style_parent_theme_name->get( 'Author' ); if ($style_parent_theme_author == "WooThemes") { ```
Thanks for all the help which pointed me in the right direction. In the end I used the following: ``` $style_parent_theme = wp_get_theme(get_template()); $style_parent_theme_author = $style_parent_theme->get( 'Author' ); ``` I use get\_template() to recover the folder name of the parent theme. wp\_get\_theme then get's the theme object. Once we have that we can manipulate the object to get the author name.
190,254
<p>I have to write my own MySQL query since I haven't found a good way to do it within wordpress functionality.</p> <p>I want the search query to search trough post_title / post_content &amp; meta_key description in pages &amp; CPT transit_routes it also need to get those results in a specific language (copied filter from WPML) then finally order the result by posts_type and posts_date. So here is my function : </p> <pre><code>function search_query_with_trips( ) { global $wpdb; $search_string = esc_sql($_GET['s']); $sql = "SELECT SQL_CALC_FOUND_ROWS {$wpdb-&gt;base_prefix}posts.ID FROM {$wpdb-&gt;base_prefix}posts LEFT JOIN {$wpdb-&gt;base_prefix}icl_translations t ON {$wpdb-&gt;base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\_%' LEFT JOIN {$wpdb-&gt;base_prefix}postmeta m ON m.post_id={$wpdb-&gt;base_prefix}posts.ID LEFT JOIN {$wpdb-&gt;base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1 AND ( ( {$wpdb-&gt;base_prefix}posts.post_title LIKE '%".$search_string."%') OR ({$wpdb-&gt;base_prefix}posts.post_content LIKE '%".$search_string."%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%".$search_string."%')) ) AND {$wpdb-&gt;base_prefix}posts.post_type IN ('page','transit_routes') AND ({$wpdb-&gt;base_prefix}posts.post_status = 'publish') AND (t.language_code='".ICL_LANGUAGE_CODE."' OR t.language_code IS NULL ) ORDER BY {$wpdb-&gt;base_prefix}posts.post_type DESC, {$wpdb-&gt;base_prefix}posts.post_date DESC"; $query=$wpdb-&gt;get_results($sql); return $query; } </code></pre> <p>The first part work well since i've tested it and it return me ids of posts that match my criteria. The problem is when it come for the loop i've tried in search.php to add before my while (have_posts()) { ... } </p> <pre><code>$search_result = search_query_with_trips(); /* $search_result = array ( 0 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 1 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 2 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 3 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 4 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 5 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 6 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 7 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 8 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), 9 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2224', )), ... 26 =&gt; stdClass::__set_state(array( 'ID' =&gt; '2223', )), 27 =&gt; stdClass::__set_state(array( 'ID' =&gt; '217', )), 28 =&gt; stdClass::__set_state(array( 'ID' =&gt; '217', )), 29 =&gt; stdClass::__set_state(array( 'ID' =&gt; '217', )), ) */ setup_postdata($search_result); </code></pre> <p>But it's not working like that as I can see but I can't figure out how to do it... </p>
[ { "answer_id": 190258, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 0, "selected": false, "text": "<p>I believe you need to setup the post data for each post.\nTry: </p>\n\n<pre><code>$search_result = search_query_with_trips();\n\nforeach( $search_result as $post ) :\n setup_postdata($post); ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;\n&lt;?php endforeach; \n</code></pre>\n\n<p>You may need <code>global $post</code> before the foreach loop. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/setup_postdata</a></p>\n" }, { "answer_id": 190275, "author": "Jonathan Lafleur", "author_id": 10501, "author_profile": "https://wordpress.stackexchange.com/users/10501", "pm_score": 1, "selected": false, "text": "<p>I got it ! Here is my final code for people who will search for similar problem :)</p>\n\n<p>in functions.php :</p>\n\n<pre><code>function se190254_custom_sql_for_search( ) {\n global $wpdb;\n //For security escape the search parameter \n $search_string = esc_sql($_GET['s']);\n\n //Build the SQL request with $wpdb-&gt;base_prefix for \"portability\" \n $sql = \"SELECT SQL_CALC_FOUND_ROWS {$wpdb-&gt;base_prefix}posts.ID FROM {$wpdb-&gt;base_prefix}posts\n LEFT JOIN {$wpdb-&gt;base_prefix}icl_translations t ON {$wpdb-&gt;base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\\_%'\n LEFT JOIN {$wpdb-&gt;base_prefix}postmeta m ON m.post_id={$wpdb-&gt;base_prefix}posts.ID\n LEFT JOIN {$wpdb-&gt;base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1\n AND ( ( {$wpdb-&gt;base_prefix}posts.post_title LIKE '%\".$search_string.\"%') OR ({$wpdb-&gt;base_prefix}posts.post_content LIKE '%\".$search_string.\"%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%\".$search_string.\"%')) )\n AND {$wpdb-&gt;base_prefix}posts.post_type IN ('page','transit_routes')\n AND ({$wpdb-&gt;base_prefix}posts.post_status = 'publish')\n AND (t.language_code='\".ICL_LANGUAGE_CODE.\"' OR t.language_code IS NULL )\n ORDER BY {$wpdb-&gt;base_prefix}posts.post_type DESC, {$wpdb-&gt;base_prefix}posts.post_date DESC\";\n\n //Get results of the SQL request (save in object by default, array_a or array_n is not needed here)\n $query=$wpdb-&gt;get_results($sql);\n\n //Loop trough each result and create a array with unique value and change it from array of object too simple array\n foreach ($query as $post) {\n $result[$post-&gt;ID] = $post-&gt;ID;\n }\n\n return $result;\n}\n</code></pre>\n\n<p>in your template file : </p>\n\n<pre><code> $search_result = se190254_custom_sql_for_search();\n if ( count($search_result) &gt; 0 ) { ?&gt;\n &lt;header class=\"page-header\"&gt;\n &lt;h1 class=\"page-title\"&gt;&lt;?php printf(__('Search Results for: %s', 'se190254'), '&lt;span&gt;' . get_search_query() . '&lt;/span&gt;'); ?&gt;&lt;/h1&gt;\n &lt;/header&gt;&lt;!-- .page-header --&gt;\n &lt;ul&gt;&lt;?php\n foreach( $search_result as $post ) {\n $post = get_post($post-&gt;ID);\n setup_postdata($post); ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;&lt;?php\n } ?&gt;\n &lt;/ul&gt;&lt;?php\n } else { ?&gt;\n &lt;p&gt;Sorry nothing match your search query&lt;/p&gt;&lt;?php\n } ?&gt;\n</code></pre>\n\n<p>In hope that it will help someone out there ! </p>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190254", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10501/" ]
I have to write my own MySQL query since I haven't found a good way to do it within wordpress functionality. I want the search query to search trough post\_title / post\_content & meta\_key description in pages & CPT transit\_routes it also need to get those results in a specific language (copied filter from WPML) then finally order the result by posts\_type and posts\_date. So here is my function : ``` function search_query_with_trips( ) { global $wpdb; $search_string = esc_sql($_GET['s']); $sql = "SELECT SQL_CALC_FOUND_ROWS {$wpdb->base_prefix}posts.ID FROM {$wpdb->base_prefix}posts LEFT JOIN {$wpdb->base_prefix}icl_translations t ON {$wpdb->base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\_%' LEFT JOIN {$wpdb->base_prefix}postmeta m ON m.post_id={$wpdb->base_prefix}posts.ID LEFT JOIN {$wpdb->base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1 AND ( ( {$wpdb->base_prefix}posts.post_title LIKE '%".$search_string."%') OR ({$wpdb->base_prefix}posts.post_content LIKE '%".$search_string."%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%".$search_string."%')) ) AND {$wpdb->base_prefix}posts.post_type IN ('page','transit_routes') AND ({$wpdb->base_prefix}posts.post_status = 'publish') AND (t.language_code='".ICL_LANGUAGE_CODE."' OR t.language_code IS NULL ) ORDER BY {$wpdb->base_prefix}posts.post_type DESC, {$wpdb->base_prefix}posts.post_date DESC"; $query=$wpdb->get_results($sql); return $query; } ``` The first part work well since i've tested it and it return me ids of posts that match my criteria. The problem is when it come for the loop i've tried in search.php to add before my while (have\_posts()) { ... } ``` $search_result = search_query_with_trips(); /* $search_result = array ( 0 => stdClass::__set_state(array( 'ID' => '2224', )), 1 => stdClass::__set_state(array( 'ID' => '2224', )), 2 => stdClass::__set_state(array( 'ID' => '2224', )), 3 => stdClass::__set_state(array( 'ID' => '2224', )), 4 => stdClass::__set_state(array( 'ID' => '2224', )), 5 => stdClass::__set_state(array( 'ID' => '2224', )), 6 => stdClass::__set_state(array( 'ID' => '2224', )), 7 => stdClass::__set_state(array( 'ID' => '2224', )), 8 => stdClass::__set_state(array( 'ID' => '2224', )), 9 => stdClass::__set_state(array( 'ID' => '2224', )), ... 26 => stdClass::__set_state(array( 'ID' => '2223', )), 27 => stdClass::__set_state(array( 'ID' => '217', )), 28 => stdClass::__set_state(array( 'ID' => '217', )), 29 => stdClass::__set_state(array( 'ID' => '217', )), ) */ setup_postdata($search_result); ``` But it's not working like that as I can see but I can't figure out how to do it...
I got it ! Here is my final code for people who will search for similar problem :) in functions.php : ``` function se190254_custom_sql_for_search( ) { global $wpdb; //For security escape the search parameter $search_string = esc_sql($_GET['s']); //Build the SQL request with $wpdb->base_prefix for "portability" $sql = "SELECT SQL_CALC_FOUND_ROWS {$wpdb->base_prefix}posts.ID FROM {$wpdb->base_prefix}posts LEFT JOIN {$wpdb->base_prefix}icl_translations t ON {$wpdb->base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\_%' LEFT JOIN {$wpdb->base_prefix}postmeta m ON m.post_id={$wpdb->base_prefix}posts.ID LEFT JOIN {$wpdb->base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1 AND ( ( {$wpdb->base_prefix}posts.post_title LIKE '%".$search_string."%') OR ({$wpdb->base_prefix}posts.post_content LIKE '%".$search_string."%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%".$search_string."%')) ) AND {$wpdb->base_prefix}posts.post_type IN ('page','transit_routes') AND ({$wpdb->base_prefix}posts.post_status = 'publish') AND (t.language_code='".ICL_LANGUAGE_CODE."' OR t.language_code IS NULL ) ORDER BY {$wpdb->base_prefix}posts.post_type DESC, {$wpdb->base_prefix}posts.post_date DESC"; //Get results of the SQL request (save in object by default, array_a or array_n is not needed here) $query=$wpdb->get_results($sql); //Loop trough each result and create a array with unique value and change it from array of object too simple array foreach ($query as $post) { $result[$post->ID] = $post->ID; } return $result; } ``` in your template file : ``` $search_result = se190254_custom_sql_for_search(); if ( count($search_result) > 0 ) { ?> <header class="page-header"> <h1 class="page-title"><?php printf(__('Search Results for: %s', 'se190254'), '<span>' . get_search_query() . '</span>'); ?></h1> </header><!-- .page-header --> <ul><?php foreach( $search_result as $post ) { $post = get_post($post->ID); setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php } ?> </ul><?php } else { ?> <p>Sorry nothing match your search query</p><?php } ?> ``` In hope that it will help someone out there !
190,259
<p>I'm working on a client's fresh install and server. Every time I attempt to save a post or page, I'm immediately sent a connection reset error (<code>This webpage is not available - ERR_CONNECTION_RESET</code>). <code>admin-ajax.php</code> is also triggering a connection reset when autosaving drafts.</p> <p>This install is unremarkable (WP 4.2.2, 2015 Theme, no plugins active) and is on a very capable machine: 2 CPU / 32 gb ram. </p> <p>The only thing that is out of the ordinary is that it is behind a SSL load balancer that isn't reporting SSL to Apache. I added <code>$_SERVER['HTTPS']='on'</code> to wp-config.php manually to avoid mixed content errors when serving JS/CSS resources.</p> <p>I've checked the logs and tried a number of things but I'm at my wit's end.</p>
[ { "answer_id": 190258, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 0, "selected": false, "text": "<p>I believe you need to setup the post data for each post.\nTry: </p>\n\n<pre><code>$search_result = search_query_with_trips();\n\nforeach( $search_result as $post ) :\n setup_postdata($post); ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;\n&lt;?php endforeach; \n</code></pre>\n\n<p>You may need <code>global $post</code> before the foreach loop. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/setup_postdata</a></p>\n" }, { "answer_id": 190275, "author": "Jonathan Lafleur", "author_id": 10501, "author_profile": "https://wordpress.stackexchange.com/users/10501", "pm_score": 1, "selected": false, "text": "<p>I got it ! Here is my final code for people who will search for similar problem :)</p>\n\n<p>in functions.php :</p>\n\n<pre><code>function se190254_custom_sql_for_search( ) {\n global $wpdb;\n //For security escape the search parameter \n $search_string = esc_sql($_GET['s']);\n\n //Build the SQL request with $wpdb-&gt;base_prefix for \"portability\" \n $sql = \"SELECT SQL_CALC_FOUND_ROWS {$wpdb-&gt;base_prefix}posts.ID FROM {$wpdb-&gt;base_prefix}posts\n LEFT JOIN {$wpdb-&gt;base_prefix}icl_translations t ON {$wpdb-&gt;base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\\_%'\n LEFT JOIN {$wpdb-&gt;base_prefix}postmeta m ON m.post_id={$wpdb-&gt;base_prefix}posts.ID\n LEFT JOIN {$wpdb-&gt;base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1\n AND ( ( {$wpdb-&gt;base_prefix}posts.post_title LIKE '%\".$search_string.\"%') OR ({$wpdb-&gt;base_prefix}posts.post_content LIKE '%\".$search_string.\"%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%\".$search_string.\"%')) )\n AND {$wpdb-&gt;base_prefix}posts.post_type IN ('page','transit_routes')\n AND ({$wpdb-&gt;base_prefix}posts.post_status = 'publish')\n AND (t.language_code='\".ICL_LANGUAGE_CODE.\"' OR t.language_code IS NULL )\n ORDER BY {$wpdb-&gt;base_prefix}posts.post_type DESC, {$wpdb-&gt;base_prefix}posts.post_date DESC\";\n\n //Get results of the SQL request (save in object by default, array_a or array_n is not needed here)\n $query=$wpdb-&gt;get_results($sql);\n\n //Loop trough each result and create a array with unique value and change it from array of object too simple array\n foreach ($query as $post) {\n $result[$post-&gt;ID] = $post-&gt;ID;\n }\n\n return $result;\n}\n</code></pre>\n\n<p>in your template file : </p>\n\n<pre><code> $search_result = se190254_custom_sql_for_search();\n if ( count($search_result) &gt; 0 ) { ?&gt;\n &lt;header class=\"page-header\"&gt;\n &lt;h1 class=\"page-title\"&gt;&lt;?php printf(__('Search Results for: %s', 'se190254'), '&lt;span&gt;' . get_search_query() . '&lt;/span&gt;'); ?&gt;&lt;/h1&gt;\n &lt;/header&gt;&lt;!-- .page-header --&gt;\n &lt;ul&gt;&lt;?php\n foreach( $search_result as $post ) {\n $post = get_post($post-&gt;ID);\n setup_postdata($post); ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;&lt;?php\n } ?&gt;\n &lt;/ul&gt;&lt;?php\n } else { ?&gt;\n &lt;p&gt;Sorry nothing match your search query&lt;/p&gt;&lt;?php\n } ?&gt;\n</code></pre>\n\n<p>In hope that it will help someone out there ! </p>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190259", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24582/" ]
I'm working on a client's fresh install and server. Every time I attempt to save a post or page, I'm immediately sent a connection reset error (`This webpage is not available - ERR_CONNECTION_RESET`). `admin-ajax.php` is also triggering a connection reset when autosaving drafts. This install is unremarkable (WP 4.2.2, 2015 Theme, no plugins active) and is on a very capable machine: 2 CPU / 32 gb ram. The only thing that is out of the ordinary is that it is behind a SSL load balancer that isn't reporting SSL to Apache. I added `$_SERVER['HTTPS']='on'` to wp-config.php manually to avoid mixed content errors when serving JS/CSS resources. I've checked the logs and tried a number of things but I'm at my wit's end.
I got it ! Here is my final code for people who will search for similar problem :) in functions.php : ``` function se190254_custom_sql_for_search( ) { global $wpdb; //For security escape the search parameter $search_string = esc_sql($_GET['s']); //Build the SQL request with $wpdb->base_prefix for "portability" $sql = "SELECT SQL_CALC_FOUND_ROWS {$wpdb->base_prefix}posts.ID FROM {$wpdb->base_prefix}posts LEFT JOIN {$wpdb->base_prefix}icl_translations t ON {$wpdb->base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\_%' LEFT JOIN {$wpdb->base_prefix}postmeta m ON m.post_id={$wpdb->base_prefix}posts.ID LEFT JOIN {$wpdb->base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1 AND ( ( {$wpdb->base_prefix}posts.post_title LIKE '%".$search_string."%') OR ({$wpdb->base_prefix}posts.post_content LIKE '%".$search_string."%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%".$search_string."%')) ) AND {$wpdb->base_prefix}posts.post_type IN ('page','transit_routes') AND ({$wpdb->base_prefix}posts.post_status = 'publish') AND (t.language_code='".ICL_LANGUAGE_CODE."' OR t.language_code IS NULL ) ORDER BY {$wpdb->base_prefix}posts.post_type DESC, {$wpdb->base_prefix}posts.post_date DESC"; //Get results of the SQL request (save in object by default, array_a or array_n is not needed here) $query=$wpdb->get_results($sql); //Loop trough each result and create a array with unique value and change it from array of object too simple array foreach ($query as $post) { $result[$post->ID] = $post->ID; } return $result; } ``` in your template file : ``` $search_result = se190254_custom_sql_for_search(); if ( count($search_result) > 0 ) { ?> <header class="page-header"> <h1 class="page-title"><?php printf(__('Search Results for: %s', 'se190254'), '<span>' . get_search_query() . '</span>'); ?></h1> </header><!-- .page-header --> <ul><?php foreach( $search_result as $post ) { $post = get_post($post->ID); setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php } ?> </ul><?php } else { ?> <p>Sorry nothing match your search query</p><?php } ?> ``` In hope that it will help someone out there !
190,261
<p>This may be a 'noob' question, but...</p> <p>It doesn't seem possible to modify the WP-Login page via PHP (eg. add the get_header() code or new DIVs) to match the site theme. That is, without hacking the core, of course. (If there -is- a way to do this, please let me know!) And -yes- I am aware you can create a login template, but you can never get -rid- of WP-Login because it seems necessary for various core login/logout functions. (Again, if this has changed with WP4, please let me know!)</p> <p>So, I've taken to simply adding the DIVs I want via jQuery(). Nothing extravagant... just a 'header' and 'footer' to match the site theme.</p> <p>My question is: are there any reasons to -not- do this? ie. security concerns or other problems I haven't considered? I ask because there must be a good reason why this is the -one- place in WP where you can't use a 'template' page and that seems odd to me.</p> <p>TIA</p>
[ { "answer_id": 190258, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": 0, "selected": false, "text": "<p>I believe you need to setup the post data for each post.\nTry: </p>\n\n<pre><code>$search_result = search_query_with_trips();\n\nforeach( $search_result as $post ) :\n setup_postdata($post); ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;\n&lt;?php endforeach; \n</code></pre>\n\n<p>You may need <code>global $post</code> before the foreach loop. </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/setup_postdata</a></p>\n" }, { "answer_id": 190275, "author": "Jonathan Lafleur", "author_id": 10501, "author_profile": "https://wordpress.stackexchange.com/users/10501", "pm_score": 1, "selected": false, "text": "<p>I got it ! Here is my final code for people who will search for similar problem :)</p>\n\n<p>in functions.php :</p>\n\n<pre><code>function se190254_custom_sql_for_search( ) {\n global $wpdb;\n //For security escape the search parameter \n $search_string = esc_sql($_GET['s']);\n\n //Build the SQL request with $wpdb-&gt;base_prefix for \"portability\" \n $sql = \"SELECT SQL_CALC_FOUND_ROWS {$wpdb-&gt;base_prefix}posts.ID FROM {$wpdb-&gt;base_prefix}posts\n LEFT JOIN {$wpdb-&gt;base_prefix}icl_translations t ON {$wpdb-&gt;base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\\_%'\n LEFT JOIN {$wpdb-&gt;base_prefix}postmeta m ON m.post_id={$wpdb-&gt;base_prefix}posts.ID\n LEFT JOIN {$wpdb-&gt;base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1\n AND ( ( {$wpdb-&gt;base_prefix}posts.post_title LIKE '%\".$search_string.\"%') OR ({$wpdb-&gt;base_prefix}posts.post_content LIKE '%\".$search_string.\"%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%\".$search_string.\"%')) )\n AND {$wpdb-&gt;base_prefix}posts.post_type IN ('page','transit_routes')\n AND ({$wpdb-&gt;base_prefix}posts.post_status = 'publish')\n AND (t.language_code='\".ICL_LANGUAGE_CODE.\"' OR t.language_code IS NULL )\n ORDER BY {$wpdb-&gt;base_prefix}posts.post_type DESC, {$wpdb-&gt;base_prefix}posts.post_date DESC\";\n\n //Get results of the SQL request (save in object by default, array_a or array_n is not needed here)\n $query=$wpdb-&gt;get_results($sql);\n\n //Loop trough each result and create a array with unique value and change it from array of object too simple array\n foreach ($query as $post) {\n $result[$post-&gt;ID] = $post-&gt;ID;\n }\n\n return $result;\n}\n</code></pre>\n\n<p>in your template file : </p>\n\n<pre><code> $search_result = se190254_custom_sql_for_search();\n if ( count($search_result) &gt; 0 ) { ?&gt;\n &lt;header class=\"page-header\"&gt;\n &lt;h1 class=\"page-title\"&gt;&lt;?php printf(__('Search Results for: %s', 'se190254'), '&lt;span&gt;' . get_search_query() . '&lt;/span&gt;'); ?&gt;&lt;/h1&gt;\n &lt;/header&gt;&lt;!-- .page-header --&gt;\n &lt;ul&gt;&lt;?php\n foreach( $search_result as $post ) {\n $post = get_post($post-&gt;ID);\n setup_postdata($post); ?&gt;\n &lt;li&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;&lt;?php\n } ?&gt;\n &lt;/ul&gt;&lt;?php\n } else { ?&gt;\n &lt;p&gt;Sorry nothing match your search query&lt;/p&gt;&lt;?php\n } ?&gt;\n</code></pre>\n\n<p>In hope that it will help someone out there ! </p>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17248/" ]
This may be a 'noob' question, but... It doesn't seem possible to modify the WP-Login page via PHP (eg. add the get\_header() code or new DIVs) to match the site theme. That is, without hacking the core, of course. (If there -is- a way to do this, please let me know!) And -yes- I am aware you can create a login template, but you can never get -rid- of WP-Login because it seems necessary for various core login/logout functions. (Again, if this has changed with WP4, please let me know!) So, I've taken to simply adding the DIVs I want via jQuery(). Nothing extravagant... just a 'header' and 'footer' to match the site theme. My question is: are there any reasons to -not- do this? ie. security concerns or other problems I haven't considered? I ask because there must be a good reason why this is the -one- place in WP where you can't use a 'template' page and that seems odd to me. TIA
I got it ! Here is my final code for people who will search for similar problem :) in functions.php : ``` function se190254_custom_sql_for_search( ) { global $wpdb; //For security escape the search parameter $search_string = esc_sql($_GET['s']); //Build the SQL request with $wpdb->base_prefix for "portability" $sql = "SELECT SQL_CALC_FOUND_ROWS {$wpdb->base_prefix}posts.ID FROM {$wpdb->base_prefix}posts LEFT JOIN {$wpdb->base_prefix}icl_translations t ON {$wpdb->base_prefix}posts.ID = t.element_id AND t.element_type LIKE 'post\_%' LEFT JOIN {$wpdb->base_prefix}postmeta m ON m.post_id={$wpdb->base_prefix}posts.ID LEFT JOIN {$wpdb->base_prefix}icl_languages l ON t.language_code=l.code AND l.active=1 WHERE 1=1 AND ( ( {$wpdb->base_prefix}posts.post_title LIKE '%".$search_string."%') OR ({$wpdb->base_prefix}posts.post_content LIKE '%".$search_string."%') OR ((m.meta_key = 'description') AND (m.meta_value LIKE '%".$search_string."%')) ) AND {$wpdb->base_prefix}posts.post_type IN ('page','transit_routes') AND ({$wpdb->base_prefix}posts.post_status = 'publish') AND (t.language_code='".ICL_LANGUAGE_CODE."' OR t.language_code IS NULL ) ORDER BY {$wpdb->base_prefix}posts.post_type DESC, {$wpdb->base_prefix}posts.post_date DESC"; //Get results of the SQL request (save in object by default, array_a or array_n is not needed here) $query=$wpdb->get_results($sql); //Loop trough each result and create a array with unique value and change it from array of object too simple array foreach ($query as $post) { $result[$post->ID] = $post->ID; } return $result; } ``` in your template file : ``` $search_result = se190254_custom_sql_for_search(); if ( count($search_result) > 0 ) { ?> <header class="page-header"> <h1 class="page-title"><?php printf(__('Search Results for: %s', 'se190254'), '<span>' . get_search_query() . '</span>'); ?></h1> </header><!-- .page-header --> <ul><?php foreach( $search_result as $post ) { $post = get_post($post->ID); setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php } ?> </ul><?php } else { ?> <p>Sorry nothing match your search query</p><?php } ?> ``` In hope that it will help someone out there !
190,264
<p>I would like to display my categories with a thumbnail in woocommerce. I am able to list the child terms as a link but i would like to add additional content. I have added the code below in which I use to display the child terms for "product_cat" as a link on my template home-page.php. But I would also like to add the category image. I would really appreciate the help THANKS. </p> <pre><code>&lt;?php $taxonomyName = "product_cat"; //This gets top layer terms only. This is done by setting parent to 0. $parent_terms = get_terms($taxonomyName, array('parent' =&gt; 0, 'orderby' =&gt; 'slug', 'hide_empty' =&gt; false)); echo '&lt;ul&gt;'; foreach ($parent_terms as $pterm) { //Get the Child terms $terms = get_terms($taxonomyName, array('parent' =&gt; $pterm-&gt;term_id, 'orderby' =&gt; 'slug', 'hide_empty' =&gt; false)); foreach ($terms as $term) { echo '&lt;li&gt;&lt;a href="' . get_term_link( $term-&gt;name, $taxonomyName ) . '"&gt;' . $term-&gt;name . '&lt;/a&gt;&lt;/li&gt;'; } } echo '&lt;/ul&gt;'; ?&gt; </code></pre>
[ { "answer_id": 192643, "author": "Domain", "author_id": 26523, "author_profile": "https://wordpress.stackexchange.com/users/26523", "pm_score": 3, "selected": true, "text": "<p>Have did some customization. This will help you show parent and child category images. You can later customize this code as per your requirements.</p>\n\n<pre><code> $taxonomyName = \"product_cat\";\n//This gets top layer terms only. This is done by setting parent to 0. \n $parent_terms = get_terms($taxonomyName, array('parent' =&gt; 0, 'orderby' =&gt; 'slug', 'hide_empty' =&gt; false));\n\n echo '&lt;ul&gt;';\n foreach ($parent_terms as $pterm) {\n\n //show parent categories\n echo '&lt;li&gt;&lt;a href=\"' . get_term_link($pterm-&gt;name, $taxonomyName) . '\"&gt;' . $pterm-&gt;name . '&lt;/a&gt;&lt;/li&gt;';\n\n $thumbnail_id = get_woocommerce_term_meta($pterm-&gt;term_id, 'thumbnail_id', true);\n // get the image URL for parent category\n $image = wp_get_attachment_url($thumbnail_id);\n // print the IMG HTML for parent category\n echo \"&lt;img src='{$image}' alt='' width='400' height='400' /&gt;\";\n\n //Get the Child terms\n $terms = get_terms($taxonomyName, array('parent' =&gt; $pterm-&gt;term_id, 'orderby' =&gt; 'slug', 'hide_empty' =&gt; false));\n foreach ($terms as $term) {\n\n echo '&lt;li&gt;&lt;a href=\"' . get_term_link($term-&gt;name, $taxonomyName) . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;&lt;/li&gt;';\n $thumbnail_id = get_woocommerce_term_meta($pterm-&gt;term_id, 'thumbnail_id', true);\n // get the image URL for child category\n $image = wp_get_attachment_url($thumbnail_id);\n // print the IMG HTML for child category\n echo \"&lt;img src='{$image}' alt='' width='400' height='400' /&gt;\";\n }\n }\n echo '&lt;/ul&gt;';\n</code></pre>\n\n<p>Let me know if it fulfills your requirement.</p>\n" }, { "answer_id": 192709, "author": "steamfunk", "author_id": 67512, "author_profile": "https://wordpress.stackexchange.com/users/67512", "pm_score": 2, "selected": false, "text": "<p>Hello @Wisdmlabs Thank you for your help. I have found this to work very well incase anyone else is wondering how to do so. </p>\n\n<pre><code>$taxonomyName = \"product_cat\";\n$prod_categories = get_terms($taxonomyName, array(\n 'orderby'=&gt; 'name',\n 'order' =&gt; 'ASC',\n 'hide_empty' =&gt; 1\n)); \n\nforeach( $prod_categories as $prod_cat ) :\n if ( $prod_cat-&gt;parent != 0 )\n continue;\n $cat_thumb_id = get_woocommerce_term_meta( $prod_cat-&gt;term_id, 'thumbnail_id', true );\n $cat_thumb_url = wp_get_attachment_thumb_url( $cat_thumb_id );\n $term_link = get_term_link( $prod_cat, 'product_cat' );\n ?&gt;\n\n &lt;img src=\"&lt;?php echo $cat_thumb_url; ?&gt;\" alt=\"\" /&gt; \n &lt;a class=\"button\" href=\"&lt;?php echo $term_link; ?&gt;\"&gt; &lt;?php echo $prod_cat-&gt;name; ?&gt; &lt;/a&gt; \n &lt;?php endforeach; \nwp_reset_query(); ?&gt;\n</code></pre>\n" }, { "answer_id": 248036, "author": "jgangso", "author_id": 104184, "author_profile": "https://wordpress.stackexchange.com/users/104184", "pm_score": 1, "selected": false, "text": "<p>To further optimize the @Wisdmlabs's answer above, replace this line</p>\n\n<pre><code>$cat_thumb_url = wp_get_attachment_thumb_url( $cat_thumb_id );\n</code></pre>\n\n<p>with</p>\n\n<pre><code>$cat_thumb_url = wp_get_attachment_image_src( $cat_thumb_id, 'thumbnail-size' )[0]; // Change to desired 'thumbnail-size'\n</code></pre>\n\n<p>This way the images are cropped to suitable size on the server to reduce bandwidth load.</p>\n" } ]
2015/06/02
[ "https://wordpress.stackexchange.com/questions/190264", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67512/" ]
I would like to display my categories with a thumbnail in woocommerce. I am able to list the child terms as a link but i would like to add additional content. I have added the code below in which I use to display the child terms for "product\_cat" as a link on my template home-page.php. But I would also like to add the category image. I would really appreciate the help THANKS. ``` <?php $taxonomyName = "product_cat"; //This gets top layer terms only. This is done by setting parent to 0. $parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false)); echo '<ul>'; foreach ($parent_terms as $pterm) { //Get the Child terms $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false)); foreach ($terms as $term) { echo '<li><a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</a></li>'; } } echo '</ul>'; ?> ```
Have did some customization. This will help you show parent and child category images. You can later customize this code as per your requirements. ``` $taxonomyName = "product_cat"; //This gets top layer terms only. This is done by setting parent to 0. $parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false)); echo '<ul>'; foreach ($parent_terms as $pterm) { //show parent categories echo '<li><a href="' . get_term_link($pterm->name, $taxonomyName) . '">' . $pterm->name . '</a></li>'; $thumbnail_id = get_woocommerce_term_meta($pterm->term_id, 'thumbnail_id', true); // get the image URL for parent category $image = wp_get_attachment_url($thumbnail_id); // print the IMG HTML for parent category echo "<img src='{$image}' alt='' width='400' height='400' />"; //Get the Child terms $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false)); foreach ($terms as $term) { echo '<li><a href="' . get_term_link($term->name, $taxonomyName) . '">' . $term->name . '</a></li>'; $thumbnail_id = get_woocommerce_term_meta($pterm->term_id, 'thumbnail_id', true); // get the image URL for child category $image = wp_get_attachment_url($thumbnail_id); // print the IMG HTML for child category echo "<img src='{$image}' alt='' width='400' height='400' />"; } } echo '</ul>'; ``` Let me know if it fulfills your requirement.
190,286
<p>I am trying to switch my current custom theme to <code>twenty fifteen</code> theme if the visitor is admin. So I put following code into my <code>custom theme functions.php</code></p> <pre><code>/*** Switching theme to Admin ***/ add_action( 'setup_theme', 'switch_user_theme' ); function switch_user_theme() { if ( current_user_can( 'manage_options' ) ) { $user_theme = 'Twenty Fifteen'; add_filter( 'template', create_function( '$t', 'return "' . $user_theme . '";' ) ); add_filter( 'stylesheet', create_function( '$s', 'return "' . $user_theme . '";' ) ); } } </code></pre> <p>But when an admin visit to the site, still it shows custom theme not the <code>twenty fifteen</code> Why it is not switched to <code>twenty fifteen</code> theme when an admin visit to the site?</p>
[ { "answer_id": 190288, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": true, "text": "<p>You are sort of doing this in a roundabout way. WordPress has a function called <a href=\"https://codex.wordpress.org/Function_Reference/switch_theme\" rel=\"nofollow\"><code>switch_theme()</code></a>:</p>\n\n<pre><code>add_action( 'setup_theme', 'switch_user_theme' );\nfunction switch_user_theme() {\n if ( current_user_can( 'manage_options' ) ) {\n switch_theme('twentytwelve');\n } else {\n switch_theme('twentythirteen');\n }\n}\n</code></pre>\n\n<p>The argument is the directory of the theme you want.</p>\n\n<p>I can't help but think this is a bad idea though. Surely you can do what you need without switching themes constantly?</p>\n" }, { "answer_id": 190300, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 1, "selected": false, "text": "<p>The current WordPress theme name is saved in the wp_options table of your WordPress database. The easy way to do it is to use the update_option() function, as shown in the function below. Paste it in your functions.php file.</p>\n\n<pre><code>function updateTheme($theme){\n update_option('template', $theme);\n update_option('stylesheet', $theme);\n update_option('current_theme', $theme);\n}\n</code></pre>\n\n<p>Call to the function can be made the following way into your custom theme functions.php: </p>\n\n<pre><code>add_action( 'setup_theme', 'switch_user_theme' );\nfunction switch_user_theme() {\n if ( current_user_can( 'manage_options' ) ) {\n $theme = \"twentyfifteen\";\n }\n else {\n $theme = \"default\";\n }\n updateTheme($theme);\n}\n</code></pre>\n\n<p>Hope this helps you out easily.</p>\n\n<p>Thanks!</p>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190286", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43764/" ]
I am trying to switch my current custom theme to `twenty fifteen` theme if the visitor is admin. So I put following code into my `custom theme functions.php` ``` /*** Switching theme to Admin ***/ add_action( 'setup_theme', 'switch_user_theme' ); function switch_user_theme() { if ( current_user_can( 'manage_options' ) ) { $user_theme = 'Twenty Fifteen'; add_filter( 'template', create_function( '$t', 'return "' . $user_theme . '";' ) ); add_filter( 'stylesheet', create_function( '$s', 'return "' . $user_theme . '";' ) ); } } ``` But when an admin visit to the site, still it shows custom theme not the `twenty fifteen` Why it is not switched to `twenty fifteen` theme when an admin visit to the site?
You are sort of doing this in a roundabout way. WordPress has a function called [`switch_theme()`](https://codex.wordpress.org/Function_Reference/switch_theme): ``` add_action( 'setup_theme', 'switch_user_theme' ); function switch_user_theme() { if ( current_user_can( 'manage_options' ) ) { switch_theme('twentytwelve'); } else { switch_theme('twentythirteen'); } } ``` The argument is the directory of the theme you want. I can't help but think this is a bad idea though. Surely you can do what you need without switching themes constantly?
190,297
<p>I am trying to create a ajaxform on the front side. I am using the code</p> <pre><code> jQuery.ajax( { type: "post", dataType: "json", url: ajaxurl, data: formData, success: function(msg){ console.log(msg); } }); </code></pre> <p>for which I am getting error</p> <pre><code>Uncaught ReferenceError: ajaxurl is not definedworklorAjaxBookForm @ ?page_id=2:291onclick @ ?page_id=2:202 </code></pre> <p>While using similar code on the admin backend works. What url must I use to process the ajax request?</p>
[ { "answer_id": 190299, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 7, "selected": true, "text": "<p>In backend there is global <code>ajaxurl</code> variable defined by WordPress itself.</p>\n\n<p>This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself.</p>\n\n<p>Good way to do this is to use <code>wp_localize_script</code>.</p>\n\n<p>Let's assume your AJAX calls are in <code>my-ajax-script.js</code> file, then add wp_localize_script for this JS file like so:</p>\n\n<pre><code>function my_enqueue() {\n\n wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );\n\n wp_localize_script( 'ajax-script', 'my_ajax_object',\n array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) ) );\n}\nadd_action( 'wp_enqueue_scripts', 'my_enqueue' );\n</code></pre>\n\n<p>After localizing your JS file, you can use <code>my_ajax_object</code> object in your JS file:</p>\n\n<pre><code>jQuery.ajax(\n {\n type: \"post\",\n dataType: \"json\",\n url: my_ajax_object.ajax_url,\n data: formData,\n success: function(msg){\n console.log(msg);\n }\n });\n</code></pre>\n" }, { "answer_id": 203475, "author": "R T", "author_id": 75838, "author_profile": "https://wordpress.stackexchange.com/users/75838", "pm_score": 6, "selected": false, "text": "<p>to use ajaxurl directly, in your plugin file add this:</p>\n\n<pre><code>add_action('wp_head', 'myplugin_ajaxurl');\n\nfunction myplugin_ajaxurl() {\n\n echo '&lt;script type=\"text/javascript\"&gt;\n var ajaxurl = \"' . admin_url('admin-ajax.php') . '\";\n &lt;/script&gt;';\n}\n</code></pre>\n\n<p>you can then use the <code>ajaxurl</code> for ajax request. </p>\n" }, { "answer_id": 357318, "author": "Amit Joshi", "author_id": 174350, "author_profile": "https://wordpress.stackexchange.com/users/174350", "pm_score": 0, "selected": false, "text": "<p>i have use below code in wordpress site.<br>\nwe can use below code for setup ajaxurl like this. </p>\n\n<pre><code>&lt;?php echo esc_url(admin_url('admin-ajax.php')); ?&gt; \n</code></pre>\n\n<p>i have also added ajax example were we can use above line. </p>\n\n<pre><code> function setNotificationRead() {\n fetch('&lt;?php echo esc_url(admin_url('admin-ajax.php')); ?&gt;', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'\n },\n body: `action=yourFunctionsAction`,\n credentials: 'same-origin'\n }).then(response =&gt; {\n return response.json();\n }).then(data =&gt; {\n if (data.status === 'true') {\n console.log('Do something...');\n }\n });\n }\n</code></pre>\n" }, { "answer_id": 385593, "author": "Gabriel Reguly", "author_id": 18886, "author_profile": "https://wordpress.stackexchange.com/users/18886", "pm_score": 2, "selected": false, "text": "<p>The 2021 way is a bit different ;-)</p>\n<pre><code>function my_enqueue() {\n\n wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );\n\n wp_add_inline_script( 'ajax-script', \n 'const myVariables = ' . json_encode( \n array(\n 'ajaxUrl' =&gt; admin_url( 'admin-ajax.php' ),\n ) ),\n 'before' );\n\n}\nadd_action( 'wp_enqueue_scripts', 'my_enqueue' );\n</code></pre>\n<p>Source: <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/#comment-4632\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_add_inline_script/#comment-4632</a></p>\n" }, { "answer_id": 398831, "author": "plainlyresults", "author_id": 215501, "author_profile": "https://wordpress.stackexchange.com/users/215501", "pm_score": 0, "selected": false, "text": "<p>I got this to work after many hours...and trials and errors. So, I do share how to make ajax work in wordpress with an example (started with <a href=\"https://www.tweaking4all.com/web-development/wordpress/wordpress-ajax-example/#comment-562814\" rel=\"nofollow noreferrer\">https://www.tweaking4all.com/web-development/wordpress/wordpress-ajax-example/#comment-562814</a> and adapted the example)</p>\n<p>--use chrome developer tools and take off cache from network tab\n--look to console if you get any errors, first goal is to get to console &quot;ready!&quot; when you click the button and if all works you get some nice output too!</p>\n<p>--add to wordpress website as custom html block:</p>\n<pre><code>&lt;div id=&quot;receiving_div_id&quot;&gt;\n &lt;p&gt;Nothing loaded yet&lt;/p&gt;\n&lt;/div&gt;\n&lt;button id=&quot;button_to_load_data&quot;&gt;Get Ajax Content&lt;/button&gt;\n</code></pre>\n<p>--add to theme/js/button.js (create js folder):</p>\n<pre><code> jQuery(&quot;#button_to_load_data&quot;).click(function() {\n console.log( &quot;ready!&quot; );\n var data = {\n 'action' : 't4a_ajax_call', // the name of your PHP function!\n 'function' : 'show_files', // a random value we'd like to pass\n 'fileid' : '7' // another random value we'd like to pass\n };\n \n jQuery.post(my_ajax_object.ajax_url, data, function(response) {\n jQuery(&quot;#receiving_div_id&quot;).html(response);\n });\n });\n</code></pre>\n<p>--add to theme functions.php:</p>\n<pre><code> /* custom script in theme functions.php */\n\n/* read button.js (-&gt;my-script) and localize admin-ajax.php for my-script */\nfunction add_my_script() {\n\n wp_enqueue_script( 'my-script', \n get_template_directory_uri() . '/js/button.js', \n array ( 'jquery' ), \n false,\n true\n );\n \n wp_localize_script( 'my-script', 'my_ajax_object',\n array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) ) );\n\n}\nadd_action( 'wp_enqueue_scripts', 'add_my_script' );\n\n\n\n/*ajax result */\n\nadd_action('wp_ajax_t4a_ajax_call', 't4a_ajax_call'); // for logged in users only\nadd_action('wp_ajax_nopriv_t4a_ajax_call', 't4a_ajax_call'); // for ALL users\n\nfunction t4a_ajax_call(){\n\n echo 'Ajax call output:';\n\n echo '&lt;pre&gt;';\n var_dump($_POST);\n echo '&lt;/pre&gt;';\n\n wp_die();// this is required to terminate immediately and return a proper response\n}\n\n</code></pre>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74079/" ]
I am trying to create a ajaxform on the front side. I am using the code ``` jQuery.ajax( { type: "post", dataType: "json", url: ajaxurl, data: formData, success: function(msg){ console.log(msg); } }); ``` for which I am getting error ``` Uncaught ReferenceError: ajaxurl is not definedworklorAjaxBookForm @ ?page_id=2:291onclick @ ?page_id=2:202 ``` While using similar code on the admin backend works. What url must I use to process the ajax request?
In backend there is global `ajaxurl` variable defined by WordPress itself. This variable is not created by WP in frontend. It means that if you want to use AJAX calls in frontend, then you have to define such variable by yourself. Good way to do this is to use `wp_localize_script`. Let's assume your AJAX calls are in `my-ajax-script.js` file, then add wp\_localize\_script for this JS file like so: ``` function my_enqueue() { wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') ); wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'my_enqueue' ); ``` After localizing your JS file, you can use `my_ajax_object` object in your JS file: ``` jQuery.ajax( { type: "post", dataType: "json", url: my_ajax_object.ajax_url, data: formData, success: function(msg){ console.log(msg); } }); ```
190,303
<p>I am implementing a section in my website to get the top 5 authors using this code.</p> <pre><code>function ranked_authors(){ $usrs = get_users('role=contributor'); $countarr = array(); foreach ($usrs as $usr) { $post_views = total_no_of_post_views($usr-&gt;ID); $countarr[$usr-&gt;ID] = $post_views; } arsort($countarr); $i=1; foreach($countarr as $id =&gt; $pcount){ if($i&lt;=5){ $div_media = '&lt;div class="media clearfix"&gt; &lt;div class="media-left"&gt;'; $author_link = get_author_posts_url($id); $author_name = get_the_author_meta('display_name',$id); $avatar = get_avatar_url( $id, 'size=50' ); $div_media .= '&lt;a href="'.$author_link.'"&gt;'.get_avatar($id, 'size=50').' &lt;span class="rank"&gt;'.$i.'&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="media-body"&gt;'; $div_media .= '&lt;h4 class="media-heading"&gt;&lt;a href="'.$author_link.'"&gt;'.$author_name.'&lt;/a&gt;&lt;/h4&gt;'.$pcount.' Total Views&lt;/div&gt; &lt;/div&gt;'; echo $div_media; $i++; } } } </code></pre> <p>I am having more than 4000 post on my blog so this query is taking so much time to execute and it almost taking 10 second to process and return the data from the server. Then i thought of Doing it in ajax way. But there is a problem in my code that it doesn't return me any data in ajax request when i am <code>returning(return)</code> the result but if i <code>echo</code> this function then it returns me the data through ajax request. I don't know but is wrong i am doing. </p> <p>I want to sort the authors according to the total no of post views.this is the function i am using to count total no of post views.</p> <pre><code>function total_no_of_post_views($author_id){ $sumViews = 0; $args = array( 'author' =&gt; $author_id, 'post_type' =&gt; array('communityposts','post','video'), 'posts_per_page'=&gt; -1 ); $author_query = new WP_Query( $args ); if( $author_query-&gt;have_posts() ) : while( $author_query-&gt;have_posts() ) : $author_query-&gt;the_post(); $sumViews += get_post_meta( get_the_ID(), 'cv_post_views_count', true ); endwhile; endif; wp_reset_postdata(); return $sumViews; } </code></pre> <p>My final requirements is to calculate top 5 authors sorted according to the total no. of post views value of their published posts.</p>
[ { "answer_id": 190319, "author": "Syed", "author_id": 24599, "author_profile": "https://wordpress.stackexchange.com/users/24599", "pm_score": 1, "selected": false, "text": "<p>I am not sure what approach you are using to send ajax request, but if you are using WordPress standard code for Ajax requests. Source: <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n\n<p>There are two issues with your current code.</p>\n\n<p>1) You are echoing inside the loop, don't do it, concat all the author html inside loop, and once loop ends only than echo it.</p>\n\n<p>2) Use die(); at the end of this function, it's necessary for Ajax request to be successfully completed.</p>\n\n<p>and you can't return the content, you will have to echo it.</p>\n" }, { "answer_id": 190321, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 0, "selected": false, "text": "<p>What you're doing is extremely inefficient - I'm guessing <code>total_no_of_post_views</code> runs a count query on the posts table for just one user?</p>\n\n<p>Instead, use the arguments available for <code>get_users</code> to get the top 5 authors <em>during</em> the query (instead of looping over <em>all</em> of them and counting each user's posts):</p>\n\n<pre><code>get_users(\n array(\n 'role' =&gt; 'contributor',\n 'number' =&gt; 5, // Number of users to retrieve\n 'count_total' =&gt; false, // Don't SQL_CALC_FOUND_ROWS\n 'meta_key' =&gt; 'cv_post_views_count',\n 'orderby' =&gt; 'meta_value_num',\n 'order' =&gt; 'DESC',\n )\n);\n</code></pre>\n" }, { "answer_id": 190361, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 1, "selected": true, "text": "<p>You need a custom query - this will join the posts, postmeta and usermeta table together and then count all <code>communityposts</code>, <code>post</code> and <code>video</code> views, grouped by author:</p>\n\n<pre><code>function wpse_190303_get_popular_users( $number = 5 ) {\n if ( ! $number = absint( $number ) )\n return;\n\n global $wpdb;\n\n $query = \"\nSELECT\n SUM( $wpdb-&gt;postmeta.meta_value+0 ) AS `post_views`,\n $wpdb-&gt;usermeta.user_id AS `user_id`\nFROM\n $wpdb-&gt;posts\nINNER JOIN\n $wpdb-&gt;postmeta ON $wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id\nINNER JOIN\n $wpdb-&gt;usermeta ON $wpdb-&gt;posts.post_author = $wpdb-&gt;usermeta.user_id\nWHERE\n $wpdb-&gt;posts.post_type IN( 'communityposts', 'post', 'video' ) AND\n $wpdb-&gt;posts.post_status = 'publish' AND\n $wpdb-&gt;postmeta.meta_key = 'cv_post_views_count' AND\n $wpdb-&gt;usermeta.meta_key = '{$wpdb-&gt;prefix}capabilities' AND\n $wpdb-&gt;usermeta.meta_value LIKE '%\\\\\\\"contributor\\\\\\\"%'\nGROUP BY\n $wpdb-&gt;usermeta.user_id\nORDER BY\n post_views DESC\nLIMIT\n $number\n\";\n\n if ( $result = $wpdb-&gt;get_results( $query ) )\n cache_users( wp_list_pluck( $result, 'user_id' ) );\n\n return $result;\n}\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>if ( $data = wpse_190303_get_popular_users() ) {\n foreach ( $data as $item ) {\n $user_id = $item-&gt;user_id;\n $views = $item-&gt;post_views;\n\n // Your code to output the popular authors\n }\n}\n</code></pre>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190303", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56650/" ]
I am implementing a section in my website to get the top 5 authors using this code. ``` function ranked_authors(){ $usrs = get_users('role=contributor'); $countarr = array(); foreach ($usrs as $usr) { $post_views = total_no_of_post_views($usr->ID); $countarr[$usr->ID] = $post_views; } arsort($countarr); $i=1; foreach($countarr as $id => $pcount){ if($i<=5){ $div_media = '<div class="media clearfix"> <div class="media-left">'; $author_link = get_author_posts_url($id); $author_name = get_the_author_meta('display_name',$id); $avatar = get_avatar_url( $id, 'size=50' ); $div_media .= '<a href="'.$author_link.'">'.get_avatar($id, 'size=50').' <span class="rank">'.$i.'</span> </a> </div> <div class="media-body">'; $div_media .= '<h4 class="media-heading"><a href="'.$author_link.'">'.$author_name.'</a></h4>'.$pcount.' Total Views</div> </div>'; echo $div_media; $i++; } } } ``` I am having more than 4000 post on my blog so this query is taking so much time to execute and it almost taking 10 second to process and return the data from the server. Then i thought of Doing it in ajax way. But there is a problem in my code that it doesn't return me any data in ajax request when i am `returning(return)` the result but if i `echo` this function then it returns me the data through ajax request. I don't know but is wrong i am doing. I want to sort the authors according to the total no of post views.this is the function i am using to count total no of post views. ``` function total_no_of_post_views($author_id){ $sumViews = 0; $args = array( 'author' => $author_id, 'post_type' => array('communityposts','post','video'), 'posts_per_page'=> -1 ); $author_query = new WP_Query( $args ); if( $author_query->have_posts() ) : while( $author_query->have_posts() ) : $author_query->the_post(); $sumViews += get_post_meta( get_the_ID(), 'cv_post_views_count', true ); endwhile; endif; wp_reset_postdata(); return $sumViews; } ``` My final requirements is to calculate top 5 authors sorted according to the total no. of post views value of their published posts.
You need a custom query - this will join the posts, postmeta and usermeta table together and then count all `communityposts`, `post` and `video` views, grouped by author: ``` function wpse_190303_get_popular_users( $number = 5 ) { if ( ! $number = absint( $number ) ) return; global $wpdb; $query = " SELECT SUM( $wpdb->postmeta.meta_value+0 ) AS `post_views`, $wpdb->usermeta.user_id AS `user_id` FROM $wpdb->posts INNER JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id INNER JOIN $wpdb->usermeta ON $wpdb->posts.post_author = $wpdb->usermeta.user_id WHERE $wpdb->posts.post_type IN( 'communityposts', 'post', 'video' ) AND $wpdb->posts.post_status = 'publish' AND $wpdb->postmeta.meta_key = 'cv_post_views_count' AND $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE '%\\\"contributor\\\"%' GROUP BY $wpdb->usermeta.user_id ORDER BY post_views DESC LIMIT $number "; if ( $result = $wpdb->get_results( $query ) ) cache_users( wp_list_pluck( $result, 'user_id' ) ); return $result; } ``` To use: ``` if ( $data = wpse_190303_get_popular_users() ) { foreach ( $data as $item ) { $user_id = $item->user_id; $views = $item->post_views; // Your code to output the popular authors } } ```
190,328
<p>I have a custom database table within wordpress database.. I filled this database with data and wordpress posts table with matching ids</p> <p>an example would be...</p> <p><strong>wp-posts table has</strong></p> <pre><code> id - title 1 - record1 title 2 - record2 title </code></pre> <p><strong>custom table has</strong></p> <pre><code> id - title - data1 - data2 - data3 1 - record1 title - 20g - good - 200USD 2 - record2 title - 30g - fine - 100USD </code></pre> <p>I can reach data with custom php coding and sql queries when i open a post</p> <p>lets say if i go www.demo.com?p=2 I can display,</p> <pre><code>Title -&gt; record2 **with the_title()** details -&gt; 30g - good - 200USD **with php+mysql** </code></pre> <p>what i want to do is connect them with custom fileds so that i will be able to edit them in backend and display them more easily without writing custom php+mysql coding..</p> <p>I checked ACF and several custom field plugins.. they seem to create their own tables or store data in postmeta</p> <p>This wont work with me since i am using this external table with other php coding other than wp.</p> <p>I looked at some frameworks also.. Couldnt find the best answer yet..</p> <p>since i have same id's for wordpress posts and custom tables records is there an easy way to do it without writing code.. Or less coding..</p> <p>Thanx</p>
[ { "answer_id": 190369, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 0, "selected": false, "text": "<p>There are filters in <a href=\"https://codex.wordpress.org/Function_Reference/get_metadata#Notes\" rel=\"nofollow\"><code>get_metadata()</code></a> and <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Filters\" rel=\"nofollow\"><code>WP_Query</code></a> that you can use to alter the SQL, but I am sure that is not an exhaustive list of the filters that you would need to worry about. What you are attempting, or seem to be attempting, is a big project. Be warned. And it is much to big to tackle here from scratch.</p>\n" }, { "answer_id": 190500, "author": "kutlus", "author_id": 62148, "author_profile": "https://wordpress.stackexchange.com/users/62148", "pm_score": 1, "selected": false, "text": "<p>After long searches and tries I ended up with <strong>\"Pods Framework\"</strong>.</p>\n\n<p>It gives me a choice to store my custom field values to a custom table within wordpress database.</p>\n\n<p>Now i am able to query them with other sources (such as other web apps that shares the same database).</p>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190328", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62148/" ]
I have a custom database table within wordpress database.. I filled this database with data and wordpress posts table with matching ids an example would be... **wp-posts table has** ``` id - title 1 - record1 title 2 - record2 title ``` **custom table has** ``` id - title - data1 - data2 - data3 1 - record1 title - 20g - good - 200USD 2 - record2 title - 30g - fine - 100USD ``` I can reach data with custom php coding and sql queries when i open a post lets say if i go www.demo.com?p=2 I can display, ``` Title -> record2 **with the_title()** details -> 30g - good - 200USD **with php+mysql** ``` what i want to do is connect them with custom fileds so that i will be able to edit them in backend and display them more easily without writing custom php+mysql coding.. I checked ACF and several custom field plugins.. they seem to create their own tables or store data in postmeta This wont work with me since i am using this external table with other php coding other than wp. I looked at some frameworks also.. Couldnt find the best answer yet.. since i have same id's for wordpress posts and custom tables records is there an easy way to do it without writing code.. Or less coding.. Thanx
After long searches and tries I ended up with **"Pods Framework"**. It gives me a choice to store my custom field values to a custom table within wordpress database. Now i am able to query them with other sources (such as other web apps that shares the same database).
190,335
<p>I know there is a possibility to change the structure/design of the product page by editing the file <code>single-product-php</code> - in a child-theme.</p> <p>The changes made of that file will affect all the product pages. </p> <p>But how do I change the template file for specific product pages? Like I can with a custom page template? From scratch there is no template dropdown on a single product page like there is for a page (the image).</p> <p>How do I change the template of a specific product page?</p> <p><img src="https://i.stack.imgur.com/X7nJt.jpg" alt=""></p>
[ { "answer_id": 190342, "author": "sohan", "author_id": 69017, "author_profile": "https://wordpress.stackexchange.com/users/69017", "pm_score": 2, "selected": false, "text": "<p>You need to check WordPress <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">template-hierarchy</a> how it works.</p>\n\n<p>Single Post #</p>\n\n<p>The single post template file is used to render a single post. WordPress uses the following path:</p>\n\n<pre><code>1.single-{post-type}.php – First, WordPress looks for a template for the specific post type. For example, post type is product, WordPress would look for single-product.php.\n2.single.php – WordPress then falls back to single.php.\n3.index.php – Finally, as mentioned above, WordPress ultimately falls back to index.php.\n</code></pre>\n\n<p>Page #</p>\n\n<p>The template file used to render a static page (page post-type). Note that unlike other post-types, page is special to WordPress and uses the following patch:</p>\n\n<pre><code> 1. custom template file – The page template assigned to the page. See get_page_templates().\n 2. page-{slug}.php – If the page slug is recent-news, WordPress will look to use page-recent-news.php.\n 3.page-{id}.php – If the page ID is 6, WordPress will look to use page-6.php.\n 4. page.php\n 5. index.php\n</code></pre>\n\n<p>For specific id you can use <code>page-{id}.php</code> template.</p>\n" }, { "answer_id": 190367, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 3, "selected": false, "text": "<p>Woo Commerce is off topic as its a plugin and not specifically related to WordPress but what you can do is copy over the single-product.php template to a WooCommerce folder in your child theme. change the file name and modify the file, then use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template\"><code>single_template</code></a> or <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\"><code>template_include</code></a> with the correct conditional tag.</p>\n\n<p><strong>single_template</strong></p>\n\n<pre><code>function get_custom_post_type_template($single_template) {\n global $post;\n\n if ($post-&gt;post_type == 'product') {\n $single_template = dirname( __FILE__ ) . '/single-template.php';\n }\n return $single_template;\n}\nadd_filter( 'single_template', 'get_custom_post_type_template' );\n</code></pre>\n\n<p><strong>template_include</strong></p>\n\n<pre><code>add_filter( 'template_include', 'portfolio_page_template', 99 );\n\nfunction portfolio_page_template( $template ) {\n\n if ( is_page( 'slug' ) ) {\n $new_template = locate_template( array( 'single-template.php' ) );\n if ( '' != $new_template ) {\n return $new_template ;\n }\n }\n\n return $template;\n}\n</code></pre>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54836/" ]
I know there is a possibility to change the structure/design of the product page by editing the file `single-product-php` - in a child-theme. The changes made of that file will affect all the product pages. But how do I change the template file for specific product pages? Like I can with a custom page template? From scratch there is no template dropdown on a single product page like there is for a page (the image). How do I change the template of a specific product page? ![](https://i.stack.imgur.com/X7nJt.jpg)
Woo Commerce is off topic as its a plugin and not specifically related to WordPress but what you can do is copy over the single-product.php template to a WooCommerce folder in your child theme. change the file name and modify the file, then use [`single_template`](https://codex.wordpress.org/Plugin_API/Filter_Reference/single_template) or [`template_include`](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) with the correct conditional tag. **single\_template** ``` function get_custom_post_type_template($single_template) { global $post; if ($post->post_type == 'product') { $single_template = dirname( __FILE__ ) . '/single-template.php'; } return $single_template; } add_filter( 'single_template', 'get_custom_post_type_template' ); ``` **template\_include** ``` add_filter( 'template_include', 'portfolio_page_template', 99 ); function portfolio_page_template( $template ) { if ( is_page( 'slug' ) ) { $new_template = locate_template( array( 'single-template.php' ) ); if ( '' != $new_template ) { return $new_template ; } } return $template; } ```
190,344
<p>I have a Wordpress child-themed site at <a href="http://mrme.me/utahcountyhiking" rel="nofollow noreferrer">http://mrme.me/utahcountyhiking</a>, and I'm trying to get it so that when you click on the featured image it goes to the associated post. Right now it goes to the media page for the featured image instead of the post.</p> <p>What I've tried</p> <ul> <li><p>I figured out how to get the child theme to load some JavaScript, but the JS was being run before the PHP added content to the page, so I wasn't able to change things with JS.</p></li> <li><p>I tried adding these <a href="https://wordpress.stackexchange.com/questions/34249/add-link-option-to-featured-image">PHP functions</a> to my child themes functions.php file, but that didn't change anything.</p></li> </ul> <p>Edit: The featured image is getting set with the Wordpress function <a href="https://codex.wordpress.org/Function_Reference/wp_get_attachment_link" rel="nofollow noreferrer">wp_get_attachment_link()</a> which returns html containing an image that is linked to the image's attachment page.</p> <p>The code that sets the featured image is</p> <pre><code>&lt;?php if(get_post_thumbnail_id(get_the_ID())) { $besty_featured_image = wp_get_attachment_link( get_post_thumbnail_id(get_the_ID()), 'besty-thumbnail', true ); echo $besty_featured_image; } ?&gt; &lt;a href="&lt;?php echo esc_url( get_permalink() ); ?&gt;" class="blog-title"&gt;&lt;?php the_title();?&gt;&lt;/a&gt; </code></pre>
[ { "answer_id": 190360, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 3, "selected": true, "text": "<p>Theme customisation is off topic however the default themes are exempt so lets look at an example of how its done in Twenty Fifteen.</p>\n\n<pre><code>if ( ! function_exists( 'twentyfifteen_post_thumbnail' ) ) :\nfunction twentyfifteen_post_thumbnail() {\n if ( post_password_required() || is_attachment() || ! has_post_thumbnail() ) {\n return;\n }\n\n if ( is_singular() ) :\n ?&gt;\n\n &lt;div class=\"post-thumbnail\"&gt;\n &lt;?php the_post_thumbnail(); ?&gt;\n &lt;/div&gt;&lt;!-- .post-thumbnail --&gt;\n\n &lt;?php else : ?&gt;\n\n &lt;a class=\"post-thumbnail\" href=\"&lt;?php the_permalink(); ?&gt;\" aria-hidden=\"true\"&gt;\n &lt;?php\n the_post_thumbnail( 'post-thumbnail', array( 'alt' =&gt; get_the_title() ) );\n ?&gt;\n &lt;/a&gt;\n\n &lt;?php endif; // End is_singular()\n}\nendif;\n</code></pre>\n\n<p>You can see this line includes <a href=\"https://codex.wordpress.org/Function_Reference/the_permalink\" rel=\"nofollow\"><code>the_permalink</code></a> and its all wrapped in the <code>&lt;a&gt;</code> tag which links the post thumbnail to the post permalink.</p>\n\n<pre><code>&lt;a class=\"post-thumbnail\" href=\"&lt;?php the_permalink(); ?&gt;\" aria-hidden=\"true\"&gt;\n</code></pre>\n" }, { "answer_id": 190382, "author": "wp-overwatch.com", "author_id": 73963, "author_profile": "https://wordpress.stackexchange.com/users/73963", "pm_score": 0, "selected": false, "text": "<p>Going off of Brad's answer, I was able to fix it by using the following code in the theme's index.html file</p>\n\n<pre><code>&lt;div class=\"post-box article\"&gt;\n &lt;a href=\"&lt;?php echo esc_url( get_permalink() ); ?&gt;\" class=\"blog-title\"&gt;\n\n &lt;?php the_post_thumbnail( 'post-thumbnail', array( 'alt' =&gt; get_the_title() ) ); ?&gt;\n &lt;div class=\"myTitleClass\"&gt;&lt;?php echo the_title(); ?&gt;&lt;/div&gt;\n\n &lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>I do realize it would have been better to use the child theme instead of editing the file directly, but this will work good enough for now. </p>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190344", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73963/" ]
I have a Wordpress child-themed site at <http://mrme.me/utahcountyhiking>, and I'm trying to get it so that when you click on the featured image it goes to the associated post. Right now it goes to the media page for the featured image instead of the post. What I've tried * I figured out how to get the child theme to load some JavaScript, but the JS was being run before the PHP added content to the page, so I wasn't able to change things with JS. * I tried adding these [PHP functions](https://wordpress.stackexchange.com/questions/34249/add-link-option-to-featured-image) to my child themes functions.php file, but that didn't change anything. Edit: The featured image is getting set with the Wordpress function [wp\_get\_attachment\_link()](https://codex.wordpress.org/Function_Reference/wp_get_attachment_link) which returns html containing an image that is linked to the image's attachment page. The code that sets the featured image is ``` <?php if(get_post_thumbnail_id(get_the_ID())) { $besty_featured_image = wp_get_attachment_link( get_post_thumbnail_id(get_the_ID()), 'besty-thumbnail', true ); echo $besty_featured_image; } ?> <a href="<?php echo esc_url( get_permalink() ); ?>" class="blog-title"><?php the_title();?></a> ```
Theme customisation is off topic however the default themes are exempt so lets look at an example of how its done in Twenty Fifteen. ``` if ( ! function_exists( 'twentyfifteen_post_thumbnail' ) ) : function twentyfifteen_post_thumbnail() { if ( post_password_required() || is_attachment() || ! has_post_thumbnail() ) { return; } if ( is_singular() ) : ?> <div class="post-thumbnail"> <?php the_post_thumbnail(); ?> </div><!-- .post-thumbnail --> <?php else : ?> <a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true"> <?php the_post_thumbnail( 'post-thumbnail', array( 'alt' => get_the_title() ) ); ?> </a> <?php endif; // End is_singular() } endif; ``` You can see this line includes [`the_permalink`](https://codex.wordpress.org/Function_Reference/the_permalink) and its all wrapped in the `<a>` tag which links the post thumbnail to the post permalink. ``` <a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true"> ```
190,357
<p>Hi I have a simple website that displays every post title in a list, I'm trying to change the active post title to be different when its being viewed. I have tried this but it's not working.</p> <pre><code>&lt;ul class="students"&gt; &lt;?php $IDOutsideLoop = $post-&gt;ID; global $post; $myposts = wp_get_archives('type=alpha'); foreach($myposts as $post) : ?&gt; &lt;li &lt;?php if(is_single() &amp;&amp; $IDOutsideLoop == $post-&gt;ID) print 'style="font-weight:bold";' ?&gt;&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 190358, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>Your current code relies on time travel to work:</p>\n\n<pre><code>$IDOutsideLoop = $post-&gt;ID;\nglobal $post;\n</code></pre>\n\n<p>Specifically the first line is peering into the future, how can it know what <code>$post-&gt;ID</code> is if it's undeclared? The fix is <code>global $post;</code>, but when the computer gets to that line, it's too late</p>\n\n<pre><code>global $post;\n$IDOutsideLoop = $post-&gt;ID;\n</code></pre>\n\n<p>If you want to list posts, you should consider <code>WP_Query</code> or <code>get_posts</code>. It may be faster in your case to use <code>pre_get_posts</code></p>\n" }, { "answer_id": 190368, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 0, "selected": false, "text": "<p>These lines are superfluous:</p>\n\n<pre><code>$IDOutsideLoop = $post-&gt;ID;\nglobal $post;\n</code></pre>\n\n<p>You don't need them. Try just <code>var_dump($post-&gt;ID);</code> and you will see that the variable is already available.</p>\n\n<p>Now, from the Codex:</p>\n\n<blockquote>\n <p>This function <strong>displays</strong> a date-based archives list. This tag can be\n used anywhere within a template.</p>\n</blockquote>\n\n<p>By default, <code>wp_list_archives()</code> echoes content. Your <code>$myposts</code> variable isn't set. Altering your code like this...</p>\n\n<pre><code>$args = array(\n 'type' =&gt; 'alpha',\n 'echo' =&gt; false,\n);\n$myposts = wp_get_archives($args);\n</code></pre>\n\n<p>... will fix that problem, but you get a string, not an array that you can iterate over. And, <code>wp_get_archives()</code> already generates an HTML list by default. </p>\n\n<p>Sadly, the filters available for manipulating the output are frustratingly limited. You'd need to get into dicey <code>regex</code> on markup, and the pattern would change with permalink structure, or you could do a resource intensive search for posts based on the url:</p>\n\n<pre><code>function alter_list_output_wpse_190357($link) {\n global $post;\n\n $pat = \"|(&lt;li[^&gt;]*&gt;).* href='([^']*)'(.*&gt;)|\";\n preg_match($pat,$link,$matches);\n $id = url_to_postid($matches[2]);\n if ($post-&gt;ID === $id) {\n $link = preg_replace($pat,\"&lt;li style=\\\"font-weight:bold\\\"&gt;&lt;a href='$2' $3\",$link);\n }\n return $link;\n}\nadd_filter( 'get_archives_link', 'alter_list_output_wpse_190357' );\n</code></pre>\n\n<p>You are probably better off using <code>WP_Query</code> or <code>get_posts</code> as already suggested in an answer by Tom J Nowell, but I wanted to explain the project. </p>\n" }, { "answer_id": 190492, "author": "BritishSam", "author_id": 67730, "author_profile": "https://wordpress.stackexchange.com/users/67730", "pm_score": 0, "selected": false, "text": "<p>I used this in the end that worked </p>\n\n<pre><code>&lt;?php\n\nglobal $post;\n$IDOutsideLoop = $post-&gt;ID;\n$args = array( 'posts_per_page' =&gt; 999, 'orderby'=&gt; 'title', 'order' =&gt; 'ASC' );\n\n$myposts = get_posts( $args );\nforeach($myposts as $post) :\n?&gt;\n\n &lt;li &lt;?php if(is_single() &amp;&amp; $IDOutsideLoop == $post-&gt;ID) print 'class=\"viewing\"'; ?&gt;&gt; \n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;\n\n&lt;?php endforeach; ?&gt;\n\n&lt;/ul&gt;\n</code></pre>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190357", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67730/" ]
Hi I have a simple website that displays every post title in a list, I'm trying to change the active post title to be different when its being viewed. I have tried this but it's not working. ``` <ul class="students"> <?php $IDOutsideLoop = $post->ID; global $post; $myposts = wp_get_archives('type=alpha'); foreach($myposts as $post) : ?> <li <?php if(is_single() && $IDOutsideLoop == $post->ID) print 'style="font-weight:bold";' ?>><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ul> ```
Your current code relies on time travel to work: ``` $IDOutsideLoop = $post->ID; global $post; ``` Specifically the first line is peering into the future, how can it know what `$post->ID` is if it's undeclared? The fix is `global $post;`, but when the computer gets to that line, it's too late ``` global $post; $IDOutsideLoop = $post->ID; ``` If you want to list posts, you should consider `WP_Query` or `get_posts`. It may be faster in your case to use `pre_get_posts`
190,359
<p>Well I should qualify that title. The shortcode is fine in itself, and no doubt nothing to do with the guys at CF7 causing this issue. I am sure it's me, but it just isn't working after I've added another shortcode directly after it. Here's the story:</p> <p>I have a page which should appear with some text to non logged-in users, and then a submission form appears (on the same page) when the user is logged in. I used some code for this in my <code>functions.php</code> which looks like this:</p> <pre><code>add_shortcode( 'visitor', 'visitor_check_shortcode' ); function visitor_check_shortcode( $atts, $content = null ) { if ( ( !is_user_logged_in() &amp;&amp; !is_null( $content ) ) || is_feed() ) return $content; return ''; } add_shortcode( 'member', 'member_check_shortcode' ); function member_check_shortcode( $atts, $content = null ) { if ( is_user_logged_in() &amp;&amp; !is_null( $content ) &amp;&amp; !is_feed() ) return $content; return ''; }` </code></pre> <p>and then I have wrapped the appropriate text on the page with the shortcodes as follows:</p> <pre><code>[visitor] the text that appears to non logged-in users [/visitor] [member] the text that appears to logged-in users and this form: [contact-form-7 id="26" title="Submit your work"] [/member] </code></pre> <p>The problem is that with the <code>[/member]</code> shortcode in place, it disables the contact form 7 shortcode. So that it appears on the page exactly as it does above (i.e. a string of shortcode), and doesn't display the form. If I remove the <code>[/member]</code> shortcode, the contact form works again. But I need the <code>[/member]</code> shortcode! Any ideas what I've done wrong?</p>
[ { "answer_id": 190364, "author": "gdaniel", "author_id": 30984, "author_profile": "https://wordpress.stackexchange.com/users/30984", "pm_score": 1, "selected": false, "text": "<p>From the <a href=\"http://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">codex</a>: </p>\n\n<blockquote>\n <p>The shortcode parser uses a single pass on the post content. This\n means that if the $content parameter of a shortcode handler contains\n another shortcode, it won't be parsed.\n <a href=\"http://codex.wordpress.org/Shortcode_API\" rel=\"nofollow\">http://codex.wordpress.org/Shortcode_API</a></p>\n</blockquote>\n\n<p>The codex also provides the solution to your issue, which is to use the funciton do_shortcode()</p>\n\n<blockquote>\n <p>If the enclosing shortcode is intended to permit other shortcodes in\n its output, the handler function can call do_shortcode() recursively:</p>\n</blockquote>\n\n<pre><code>function caption_shortcode( $atts, $content = null ) {\n return '&lt;span class=\"caption\"&gt;' . do_shortcode($content) . '&lt;/span&gt;';\n}\n</code></pre>\n\n<p>So, in your case you would need to edit the members function to include the form shortcode in it. Probably something along these lines:</p>\n\n<pre><code>function member_check_shortcode( $atts, $content = null ) {\n if ( is_user_logged_in() &amp;&amp; !is_null( $content ) &amp;&amp; !is_feed() )\n return $content . do_shortcode([contact-form-7 id=\"26\" title=\"Submit your work\"]);\n return '';\n}`\n</code></pre>\n\n<p>If you need to change the form ID or title on the fly, you could pass those parameters via the members shortcode.</p>\n" }, { "answer_id": 190365, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 0, "selected": false, "text": "<p>The comment from gdaniel is right on the money. In order to handle nested shortcodes properly, you can wrap your <code>$content</code> with do_shortcode(). </p>\n\n<p>Your MEMBER handler would become:</p>\n\n<pre><code>function member_check_shortcode( $atts, $content = null ) {\n if ( is_user_logged_in() &amp;&amp; !is_null( $content ) &amp;&amp; !is_feed() )\n return do_shortcode($content);\nreturn '';\n</code></pre>\n\n<p>}`</p>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74104/" ]
Well I should qualify that title. The shortcode is fine in itself, and no doubt nothing to do with the guys at CF7 causing this issue. I am sure it's me, but it just isn't working after I've added another shortcode directly after it. Here's the story: I have a page which should appear with some text to non logged-in users, and then a submission form appears (on the same page) when the user is logged in. I used some code for this in my `functions.php` which looks like this: ``` add_shortcode( 'visitor', 'visitor_check_shortcode' ); function visitor_check_shortcode( $atts, $content = null ) { if ( ( !is_user_logged_in() && !is_null( $content ) ) || is_feed() ) return $content; return ''; } add_shortcode( 'member', 'member_check_shortcode' ); function member_check_shortcode( $atts, $content = null ) { if ( is_user_logged_in() && !is_null( $content ) && !is_feed() ) return $content; return ''; }` ``` and then I have wrapped the appropriate text on the page with the shortcodes as follows: ``` [visitor] the text that appears to non logged-in users [/visitor] [member] the text that appears to logged-in users and this form: [contact-form-7 id="26" title="Submit your work"] [/member] ``` The problem is that with the `[/member]` shortcode in place, it disables the contact form 7 shortcode. So that it appears on the page exactly as it does above (i.e. a string of shortcode), and doesn't display the form. If I remove the `[/member]` shortcode, the contact form works again. But I need the `[/member]` shortcode! Any ideas what I've done wrong?
From the [codex](http://codex.wordpress.org/Shortcode_API): > > The shortcode parser uses a single pass on the post content. This > means that if the $content parameter of a shortcode handler contains > another shortcode, it won't be parsed. > <http://codex.wordpress.org/Shortcode_API> > > > The codex also provides the solution to your issue, which is to use the funciton do\_shortcode() > > If the enclosing shortcode is intended to permit other shortcodes in > its output, the handler function can call do\_shortcode() recursively: > > > ``` function caption_shortcode( $atts, $content = null ) { return '<span class="caption">' . do_shortcode($content) . '</span>'; } ``` So, in your case you would need to edit the members function to include the form shortcode in it. Probably something along these lines: ``` function member_check_shortcode( $atts, $content = null ) { if ( is_user_logged_in() && !is_null( $content ) && !is_feed() ) return $content . do_shortcode([contact-form-7 id="26" title="Submit your work"]); return ''; }` ``` If you need to change the form ID or title on the fly, you could pass those parameters via the members shortcode.
190,381
<p>I am trying to write a plugin that copies a custom post type "event" from one blog to another. The code for copying I already have working but I cannot seem to get this "add_action" hook to work when an event is published.</p> <pre><code>add_action('publish_event', 'copy_event_to_mini_site' ); function copy_event_to_mini_site() { code in here to copy relevant data from one blog to the other } </code></pre> <p>I also tried: <code>add_action('publish_post', 'copy_event_to_mini_site' );</code></p> <p>That did not work either.</p>
[ { "answer_id": 264381, "author": "Syndyloo", "author_id": 118138, "author_profile": "https://wordpress.stackexchange.com/users/118138", "pm_score": 3, "selected": false, "text": "<p>Read the codex, that's where i finally found the answer :</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post</a></p>\n\n<p>in the end :</p>\n\n<p><strong>Custom Post Types</strong></p>\n\n<p>To trigger this action for a custom post type, use publish_{$custom_post_type}. e.g. if your post type is 'book' use:</p>\n\n<pre><code>add_action( 'publish_book', 'post_published_notification', 10, 2 );\n</code></pre>\n" }, { "answer_id": 265144, "author": "Kvvaradha", "author_id": 43308, "author_profile": "https://wordpress.stackexchange.com/users/43308", "pm_score": 2, "selected": false, "text": "<p><code>transition_post_status</code> helps you to perform for all post types and change from one status to other,say for example, pending to publish. or new publishing post.</p>\n\n<p>Here is official <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">WordPress Codec Page</a>\n.</p>\n\n<pre><code>function on_all_status_transitions( $new_status, $old_status, $post ) \n{\n if ( $new_status != $old_status ) {\n // A function to perform actions any time any post changes status.\n }\n if ( $new_status != 'publish' ) {\n // A function to perform action when new post published.\n }\n}\nadd_action( 'transition_post_status', 'on_all_status_transitions', 10, 3 );\n</code></pre>\n\n<p>I hope this will help universally for all custom post types and default post types.</p>\n" }, { "answer_id": 332021, "author": "Pravin Work", "author_id": 120969, "author_profile": "https://wordpress.stackexchange.com/users/120969", "pm_score": 0, "selected": false, "text": "<ul>\n<li>{old_status}<em>to</em>{new_status} </li>\n<li>{status}_{post_type}</li>\n</ul>\n\n<p>The available post statuses are:</p>\n\n<ul>\n<li>new – When there’s no previous status (this means these hooks are\nalways run whenever \"save_post\" runs.</li>\n<li>publish – A published post or page.</li>\n<li>pending – A post pending review.</li>\n<li>draft – A post in draft status.</li>\n<li>auto-draft – A newly created post with no content.</li>\n<li>future – A post scheduled to publish in the future.</li>\n<li>private – Not visible to users who are not logged in.</li>\n<li>inherit – A revision or attachment (see get_children()).</li>\n<li>trash – Post is in the trash (added with Version 2.9).</li>\n</ul>\n\n<p>You can create events per post status transitions as you need.</p>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190381", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69258/" ]
I am trying to write a plugin that copies a custom post type "event" from one blog to another. The code for copying I already have working but I cannot seem to get this "add\_action" hook to work when an event is published. ``` add_action('publish_event', 'copy_event_to_mini_site' ); function copy_event_to_mini_site() { code in here to copy relevant data from one blog to the other } ``` I also tried: `add_action('publish_post', 'copy_event_to_mini_site' );` That did not work either.
Read the codex, that's where i finally found the answer : <https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post> in the end : **Custom Post Types** To trigger this action for a custom post type, use publish\_{$custom\_post\_type}. e.g. if your post type is 'book' use: ``` add_action( 'publish_book', 'post_published_notification', 10, 2 ); ```
190,395
<p>I'm developing a new theme and plugins for it. Unfortunately, the comment reply link is broken. Instead of moving the comment reply textarea, the page is reloaded by adding e.g. ?replytocom=2#respond to the URL (corresponding to the value of the href attribute).</p> <p><s>Here's a link to see what I mean: ...</s> (No longer necessary to view link)</p> <p>Thanks in advance for your help!</p> <p>Best joschi81</p> <p>EDIT: I found out that it's caused by my "dirty" hack to modify the #reply-title. Which I do like this: functions.php.</p> <pre><code>// add variable to change comment form title function add_comment_title_variable($content) { $output = $content; if(is_single() &amp;&amp; comments_open()) $output .='&lt;script type="text/javascript"&gt; var commentFormTitle = "'.__('Leave a comment','theme-text-domain').'"; &lt;/script&gt;'; return $output; } add_filter('the_content','add_comment_title_variable'); </code></pre> <p>Main JS file of my theme:</p> <pre><code>$(document).ready(function(){ // [...] if(typeof(commentFormTitle) != 'undefined') $('#reply-title').html(commentFormTitle); }); </code></pre> <p>So, any hints how I can "individualize" the translation/textoutput of the comment form title without such dirty hack?</p> <p>I kept it within the same question as other people who have the same problem with the comment reply link might be causing it the same way.</p> <p>Thanks joschi81</p>
[ { "answer_id": 264381, "author": "Syndyloo", "author_id": 118138, "author_profile": "https://wordpress.stackexchange.com/users/118138", "pm_score": 3, "selected": false, "text": "<p>Read the codex, that's where i finally found the answer :</p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post</a></p>\n\n<p>in the end :</p>\n\n<p><strong>Custom Post Types</strong></p>\n\n<p>To trigger this action for a custom post type, use publish_{$custom_post_type}. e.g. if your post type is 'book' use:</p>\n\n<pre><code>add_action( 'publish_book', 'post_published_notification', 10, 2 );\n</code></pre>\n" }, { "answer_id": 265144, "author": "Kvvaradha", "author_id": 43308, "author_profile": "https://wordpress.stackexchange.com/users/43308", "pm_score": 2, "selected": false, "text": "<p><code>transition_post_status</code> helps you to perform for all post types and change from one status to other,say for example, pending to publish. or new publishing post.</p>\n\n<p>Here is official <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">WordPress Codec Page</a>\n.</p>\n\n<pre><code>function on_all_status_transitions( $new_status, $old_status, $post ) \n{\n if ( $new_status != $old_status ) {\n // A function to perform actions any time any post changes status.\n }\n if ( $new_status != 'publish' ) {\n // A function to perform action when new post published.\n }\n}\nadd_action( 'transition_post_status', 'on_all_status_transitions', 10, 3 );\n</code></pre>\n\n<p>I hope this will help universally for all custom post types and default post types.</p>\n" }, { "answer_id": 332021, "author": "Pravin Work", "author_id": 120969, "author_profile": "https://wordpress.stackexchange.com/users/120969", "pm_score": 0, "selected": false, "text": "<ul>\n<li>{old_status}<em>to</em>{new_status} </li>\n<li>{status}_{post_type}</li>\n</ul>\n\n<p>The available post statuses are:</p>\n\n<ul>\n<li>new – When there’s no previous status (this means these hooks are\nalways run whenever \"save_post\" runs.</li>\n<li>publish – A published post or page.</li>\n<li>pending – A post pending review.</li>\n<li>draft – A post in draft status.</li>\n<li>auto-draft – A newly created post with no content.</li>\n<li>future – A post scheduled to publish in the future.</li>\n<li>private – Not visible to users who are not logged in.</li>\n<li>inherit – A revision or attachment (see get_children()).</li>\n<li>trash – Post is in the trash (added with Version 2.9).</li>\n</ul>\n\n<p>You can create events per post status transitions as you need.</p>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190395", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40934/" ]
I'm developing a new theme and plugins for it. Unfortunately, the comment reply link is broken. Instead of moving the comment reply textarea, the page is reloaded by adding e.g. ?replytocom=2#respond to the URL (corresponding to the value of the href attribute). ~~Here's a link to see what I mean: ...~~ (No longer necessary to view link) Thanks in advance for your help! Best joschi81 EDIT: I found out that it's caused by my "dirty" hack to modify the #reply-title. Which I do like this: functions.php. ``` // add variable to change comment form title function add_comment_title_variable($content) { $output = $content; if(is_single() && comments_open()) $output .='<script type="text/javascript"> var commentFormTitle = "'.__('Leave a comment','theme-text-domain').'"; </script>'; return $output; } add_filter('the_content','add_comment_title_variable'); ``` Main JS file of my theme: ``` $(document).ready(function(){ // [...] if(typeof(commentFormTitle) != 'undefined') $('#reply-title').html(commentFormTitle); }); ``` So, any hints how I can "individualize" the translation/textoutput of the comment form title without such dirty hack? I kept it within the same question as other people who have the same problem with the comment reply link might be causing it the same way. Thanks joschi81
Read the codex, that's where i finally found the answer : <https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post> in the end : **Custom Post Types** To trigger this action for a custom post type, use publish\_{$custom\_post\_type}. e.g. if your post type is 'book' use: ``` add_action( 'publish_book', 'post_published_notification', 10, 2 ); ```
190,408
<p>I bought a WP-Theme which defines a custom image-size in his theme-functions.php like this:</p> <pre><code>if ( function_exists( 'add_image_size' ) ){ add_image_size( 'tie-small', 70, 70, true ); } </code></pre> <p>As you can see the third-parameter is true, which results in hard crop mode (see <a href="https://codex.wordpress.org/Function_Reference/add_image_size" rel="nofollow">Wordpress Documentation for add_image_size</a>). This mode isn't taking care of the proportions so some of my thumbnails are resized very badly. I did some tests and changing the crop-Parameter to FALSE will create better results. </p> <p>I want to overwrite this image-size by using a plugin so that I can update my theme without changing the value above to FALSE on every update. The add_image_size function storing his data in a array with $name as key. So multiplice calls of this function will overwrite the values up to the last call. </p> <p>My plugin is very simple and looks like the following:</p> <pre><code>class My_Plugin { public function __construct() { add_action( 'after_setup_theme', array( $this, 'overwrite_wptheme_settings' ) ); } public function overwrite_wptheme_settings() { add_image_size( 'tie-small', 70, 70, false ); } } </code></pre> <p>Its not working, I reuploaded a test-image and it looks like crop is set to true. I cant figure out why because the value was overwritten! I could verify this by going to the function tie_last_posts in the theme-functions.php of the theme. This function is generating the widget with the post-thumbnail image:</p> <pre><code>[...] function tie_last_posts($numberOfPosts = 5 , $thumb = true) { // [...] &lt;?php global $_wp_additional_image_sizes; var_dump($_wp_additional_image_sizes); ?&gt; &lt;?php the_post_thumbnail( 'tie-small' ) ; ?&gt; </code></pre> <p>This will output the following before the widget: </p> <pre><code>array(3) { ["tie-small"]=&gt; array(3) { ["width"]=&gt; int(70) ["height"]=&gt; int(70) ["crop"]=&gt; bool(false) } ["tie-large"]=&gt; array(3) { ["width"]=&gt; int(300) ["height"]=&gt; int(160) ["crop"]=&gt; bool(true) } ["slider"]=&gt; array(3) { ["width"]=&gt; int(620) ["height"]=&gt; int(330) ["crop"]=&gt; bool(true) } } </code></pre> <p>As you can see, the attribute <strong>crop</strong> is set to false in the index <strong>tie-small</strong>. So it was overwritten by my plugin. But the thumbnail get cropped. I verified this by using a testimage which is getting clearly bad when it gets cropped by wordpress. I always reuploaded the image in the article. AND I have verified that the overwriting itself is working: I inserted add_image_size( 'tie-small', 70, 70, false ); at the end of the theme-functions.php and it worked, but in my plugin it isnt. Whats wrong here? </p>
[ { "answer_id": 190419, "author": "Benito Lopez", "author_id": 73915, "author_profile": "https://wordpress.stackexchange.com/users/73915", "pm_score": 1, "selected": false, "text": "<p>Change the action to 'init':</p>\n\n<pre><code>class My_Plugin {\n public function __construct() {\n add_action( 'init', array( $this, 'overwrite_wptheme_settings' ) );\n }\n\n public function overwrite_wptheme_settings() {\n add_image_size( 'tie-small', 70, 70, false );\n }\n}\n</code></pre>\n" }, { "answer_id": 190496, "author": "Lion", "author_id": 65411, "author_profile": "https://wordpress.stackexchange.com/users/65411", "pm_score": 0, "selected": false, "text": "<p>Solved this by creating a child-theme. In the action <strong>after_setup_theme</strong> I overwrite the image-size and it works, thumbnails aren't cropped anymore. Not sure why it isn't possible to do this in a plugin, but for me it seems that creating a childtheme instead of a plugin is the better solution anyway. The WP-Doc itself says that this is the recommended way to modify a theme, so I will move my changes made by my plugin to the child-theme I created. </p>\n" } ]
2015/06/03
[ "https://wordpress.stackexchange.com/questions/190408", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65411/" ]
I bought a WP-Theme which defines a custom image-size in his theme-functions.php like this: ``` if ( function_exists( 'add_image_size' ) ){ add_image_size( 'tie-small', 70, 70, true ); } ``` As you can see the third-parameter is true, which results in hard crop mode (see [Wordpress Documentation for add\_image\_size](https://codex.wordpress.org/Function_Reference/add_image_size)). This mode isn't taking care of the proportions so some of my thumbnails are resized very badly. I did some tests and changing the crop-Parameter to FALSE will create better results. I want to overwrite this image-size by using a plugin so that I can update my theme without changing the value above to FALSE on every update. The add\_image\_size function storing his data in a array with $name as key. So multiplice calls of this function will overwrite the values up to the last call. My plugin is very simple and looks like the following: ``` class My_Plugin { public function __construct() { add_action( 'after_setup_theme', array( $this, 'overwrite_wptheme_settings' ) ); } public function overwrite_wptheme_settings() { add_image_size( 'tie-small', 70, 70, false ); } } ``` Its not working, I reuploaded a test-image and it looks like crop is set to true. I cant figure out why because the value was overwritten! I could verify this by going to the function tie\_last\_posts in the theme-functions.php of the theme. This function is generating the widget with the post-thumbnail image: ``` [...] function tie_last_posts($numberOfPosts = 5 , $thumb = true) { // [...] <?php global $_wp_additional_image_sizes; var_dump($_wp_additional_image_sizes); ?> <?php the_post_thumbnail( 'tie-small' ) ; ?> ``` This will output the following before the widget: ``` array(3) { ["tie-small"]=> array(3) { ["width"]=> int(70) ["height"]=> int(70) ["crop"]=> bool(false) } ["tie-large"]=> array(3) { ["width"]=> int(300) ["height"]=> int(160) ["crop"]=> bool(true) } ["slider"]=> array(3) { ["width"]=> int(620) ["height"]=> int(330) ["crop"]=> bool(true) } } ``` As you can see, the attribute **crop** is set to false in the index **tie-small**. So it was overwritten by my plugin. But the thumbnail get cropped. I verified this by using a testimage which is getting clearly bad when it gets cropped by wordpress. I always reuploaded the image in the article. AND I have verified that the overwriting itself is working: I inserted add\_image\_size( 'tie-small', 70, 70, false ); at the end of the theme-functions.php and it worked, but in my plugin it isnt. Whats wrong here?
Change the action to 'init': ``` class My_Plugin { public function __construct() { add_action( 'init', array( $this, 'overwrite_wptheme_settings' ) ); } public function overwrite_wptheme_settings() { add_image_size( 'tie-small', 70, 70, false ); } } ```
190,449
<p>I have installed the Beauty Contact Popup Form Wordpress Plugin on my website, and want to use the raw source code (or a better way to access the form) in a mysql_fetch_array loop like this:</p> <pre><code>&lt;?php // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into tabs echo "&lt;div class='tab-tall'&gt;&lt;ul id='tab"; echo htmlspecialchars($row['layouttype']); echo "'&gt; &lt;li&gt;&lt;a style='font-size:;' class='textBig heading'&gt;"; echo htmlspecialchars($row['heading']); echo "&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a style='font-size:;' class='textBig supplier'&gt;"; echo htmlspecialchars($row['supplier']); echo "&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a style='font-size:;' class='url' target='_blank'&gt;"; echo htmlspecialchars($row['url']); echo "&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a style='font-size:;' class='email' target='_top'&gt;"; echo htmlspecialchars($row['email']); echo "&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a style='font-size:;' class='summary''&gt;"; echo htmlspecialchars($row['summary']); echo "&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class='img relink'&gt;&lt;img src='"; echo htmlspecialchars($row['linked_image']); echo "' /&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/div&gt;"; } ?&gt; </code></pre> <p>I am thinking, adapt the raw html that the plugin spits out like is, then add it to the fetch email ['email'] somehow -</p> <pre><code>&lt;a class='email' href='javascript:TagPopup_OpenForm("TagPopup_FormContainer","TagPopup_FormContainerBody","TagPopup_FormContainerFooter");'&gt;&lt;?php htmlspecialchars($row['email']); ?&gt;&lt;/a&gt;&lt;div style="display: none;" id="TagPopup_FormContainer"&gt;&lt;div id="TagPopup_FormContainerHeader"&gt;&lt;div id="TagPopup_FormClose"&gt;&lt;a href="javascript:TagPopup_HideForm('TagPopup_FormContainer','TagPopup_FormContainerFooter');"&gt;X&lt;/a&gt;&lt;/div&gt;&lt;div id="TagPopup_FormTitle"&gt; Wanted Ad Reply &lt;/div&gt;&lt;/div&gt;&lt;div id="TagPopup_FormContainerBody"&gt;&lt;form action="#" name="TagPopup_Form" id="TagPopup_Form"&gt;&lt;div id="TagPopup_FormAlert"&gt; &lt;span id="TagPopup_alertmessage"&gt;&lt;/span&gt; &lt;/div&gt;&lt;div id="TagPopup_FormLabel_Page"&gt;&lt;input name="TagPopup_name" class="TagPopup_TextForm" type="text" id="TagPopup_name" Placeholder="Your Name" maxlength="120"&gt;&lt;/div&gt;&lt;div id="TagPopup_FormLabel_Page"&gt;&lt;input name="TagPopup_mail" class="TagPopup_TextForm" type="text" id="TagPopup_mail" Placeholder="Your Email" maxlength="120"&gt;&lt;/div&gt;&lt;div id="TagPopup_FormLabel_Page"&gt;&lt;textarea name="TagPopup_message" class="TagPopup_TextArea" rows="3" id="TagPopup_message" Placeholder="Enter Your Message"&gt;&lt;/textarea&gt;&lt;/div&gt;&lt;input type="hidden" id="TagCorrectsum" name="TagCorrectsum" value="11"/&gt;&lt;div id="TagPopup_FormLabel_Page" class="TagPopup_Human" &gt; Verify Human: 3 + 8 = &lt;/div&gt;&lt;input name="TagPopup_captcha" class="TagPopup_TextForm" type="text" id="TagPopup_captcha" Placeholder="Enter the sum eg: 1+1=2" maxlength="120"&gt;&lt;div id="TagPopup_FormLabel_Page"&gt;&lt;input type="button" name="button" class="TagPopup_Button" value="Submit" onClick="javascript:TagPopup_Submit(this.parentNode,'http://www.mewanted.com');"&gt;&lt;/div&gt;&lt;/form&gt;&lt;/div&gt;&lt;/div&gt;&lt;div style="display: none;" id="TagPopup_FormContainerFooter"&gt;&lt;/div&gt;&lt;/a&gt; </code></pre>
[ { "answer_id": 190419, "author": "Benito Lopez", "author_id": 73915, "author_profile": "https://wordpress.stackexchange.com/users/73915", "pm_score": 1, "selected": false, "text": "<p>Change the action to 'init':</p>\n\n<pre><code>class My_Plugin {\n public function __construct() {\n add_action( 'init', array( $this, 'overwrite_wptheme_settings' ) );\n }\n\n public function overwrite_wptheme_settings() {\n add_image_size( 'tie-small', 70, 70, false );\n }\n}\n</code></pre>\n" }, { "answer_id": 190496, "author": "Lion", "author_id": 65411, "author_profile": "https://wordpress.stackexchange.com/users/65411", "pm_score": 0, "selected": false, "text": "<p>Solved this by creating a child-theme. In the action <strong>after_setup_theme</strong> I overwrite the image-size and it works, thumbnails aren't cropped anymore. Not sure why it isn't possible to do this in a plugin, but for me it seems that creating a childtheme instead of a plugin is the better solution anyway. The WP-Doc itself says that this is the recommended way to modify a theme, so I will move my changes made by my plugin to the child-theme I created. </p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190449", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74151/" ]
I have installed the Beauty Contact Popup Form Wordpress Plugin on my website, and want to use the raw source code (or a better way to access the form) in a mysql\_fetch\_array loop like this: ``` <?php // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into tabs echo "<div class='tab-tall'><ul id='tab"; echo htmlspecialchars($row['layouttype']); echo "'> <li><a style='font-size:;' class='textBig heading'>"; echo htmlspecialchars($row['heading']); echo "</a></li> <li><a style='font-size:;' class='textBig supplier'>"; echo htmlspecialchars($row['supplier']); echo "</a></li> <li><a style='font-size:;' class='url' target='_blank'>"; echo htmlspecialchars($row['url']); echo "</a></li> <li><a style='font-size:;' class='email' target='_top'>"; echo htmlspecialchars($row['email']); echo "</a></li> <li><a style='font-size:;' class='summary''>"; echo htmlspecialchars($row['summary']); echo "</a></li> <li><a class='img relink'><img src='"; echo htmlspecialchars($row['linked_image']); echo "' /></a></li> </ul></div>"; } ?> ``` I am thinking, adapt the raw html that the plugin spits out like is, then add it to the fetch email ['email'] somehow - ``` <a class='email' href='javascript:TagPopup_OpenForm("TagPopup_FormContainer","TagPopup_FormContainerBody","TagPopup_FormContainerFooter");'><?php htmlspecialchars($row['email']); ?></a><div style="display: none;" id="TagPopup_FormContainer"><div id="TagPopup_FormContainerHeader"><div id="TagPopup_FormClose"><a href="javascript:TagPopup_HideForm('TagPopup_FormContainer','TagPopup_FormContainerFooter');">X</a></div><div id="TagPopup_FormTitle"> Wanted Ad Reply </div></div><div id="TagPopup_FormContainerBody"><form action="#" name="TagPopup_Form" id="TagPopup_Form"><div id="TagPopup_FormAlert"> <span id="TagPopup_alertmessage"></span> </div><div id="TagPopup_FormLabel_Page"><input name="TagPopup_name" class="TagPopup_TextForm" type="text" id="TagPopup_name" Placeholder="Your Name" maxlength="120"></div><div id="TagPopup_FormLabel_Page"><input name="TagPopup_mail" class="TagPopup_TextForm" type="text" id="TagPopup_mail" Placeholder="Your Email" maxlength="120"></div><div id="TagPopup_FormLabel_Page"><textarea name="TagPopup_message" class="TagPopup_TextArea" rows="3" id="TagPopup_message" Placeholder="Enter Your Message"></textarea></div><input type="hidden" id="TagCorrectsum" name="TagCorrectsum" value="11"/><div id="TagPopup_FormLabel_Page" class="TagPopup_Human" > Verify Human: 3 + 8 = </div><input name="TagPopup_captcha" class="TagPopup_TextForm" type="text" id="TagPopup_captcha" Placeholder="Enter the sum eg: 1+1=2" maxlength="120"><div id="TagPopup_FormLabel_Page"><input type="button" name="button" class="TagPopup_Button" value="Submit" onClick="javascript:TagPopup_Submit(this.parentNode,'http://www.mewanted.com');"></div></form></div></div><div style="display: none;" id="TagPopup_FormContainerFooter"></div></a> ```
Change the action to 'init': ``` class My_Plugin { public function __construct() { add_action( 'init', array( $this, 'overwrite_wptheme_settings' ) ); } public function overwrite_wptheme_settings() { add_image_size( 'tie-small', 70, 70, false ); } } ```
190,461
<p>I wrote a plugin in which one of the PHP files itself opens and writes another small text file.</p> <p>How to grant this PHP file the right permissions?</p>
[ { "answer_id": 190419, "author": "Benito Lopez", "author_id": 73915, "author_profile": "https://wordpress.stackexchange.com/users/73915", "pm_score": 1, "selected": false, "text": "<p>Change the action to 'init':</p>\n\n<pre><code>class My_Plugin {\n public function __construct() {\n add_action( 'init', array( $this, 'overwrite_wptheme_settings' ) );\n }\n\n public function overwrite_wptheme_settings() {\n add_image_size( 'tie-small', 70, 70, false );\n }\n}\n</code></pre>\n" }, { "answer_id": 190496, "author": "Lion", "author_id": 65411, "author_profile": "https://wordpress.stackexchange.com/users/65411", "pm_score": 0, "selected": false, "text": "<p>Solved this by creating a child-theme. In the action <strong>after_setup_theme</strong> I overwrite the image-size and it works, thumbnails aren't cropped anymore. Not sure why it isn't possible to do this in a plugin, but for me it seems that creating a childtheme instead of a plugin is the better solution anyway. The WP-Doc itself says that this is the recommended way to modify a theme, so I will move my changes made by my plugin to the child-theme I created. </p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190461", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74155/" ]
I wrote a plugin in which one of the PHP files itself opens and writes another small text file. How to grant this PHP file the right permissions?
Change the action to 'init': ``` class My_Plugin { public function __construct() { add_action( 'init', array( $this, 'overwrite_wptheme_settings' ) ); } public function overwrite_wptheme_settings() { add_image_size( 'tie-small', 70, 70, false ); } } ```
190,465
<p>Quick simple question. How would I get the result of a rewrite in wordpress?</p> <p>For example I have:</p> <pre><code>www.some.website.com/some/parameter </code></pre> <p>How would I get the end result that WP processes? Aka, the</p> <pre><code>www.some.website.com/index.php?paramter1=some&amp;paramter2=parameter </code></pre> <p>Cheers</p>
[ { "answer_id": 190501, "author": "ncwhitehead", "author_id": 74168, "author_profile": "https://wordpress.stackexchange.com/users/74168", "pm_score": 0, "selected": false, "text": "<p>Use the function get_query_var: <a href=\"http://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow\">WordPress Codex Function Reference for get query var</a></p>\n\n<pre><code>$someVariable = get_query_var('paramter1'); \n</code></pre>\n" }, { "answer_id": 190544, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Have a look at the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">Action Reference</a> to see generally how requests are processed. After all the loading and init stuff happens, the <code>parse_request</code> action runs when the request is matched against the rewrite rules, and an object is passed containing all the registered query vars and the matched rule and query string.</p>\n\n<pre><code>function wpd_parse_request( $request ){\n echo $request-&gt;matched_query;\n}\nadd_action( 'parse_request', 'wpd_parse_request' );\n</code></pre>\n\n<p>After the <code>wp</code> action runs, that same object is stashed in the <code>wp</code> global.</p>\n\n<pre><code>global $wp;\necho $wp-&gt;matched_query;\n</code></pre>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67005/" ]
Quick simple question. How would I get the result of a rewrite in wordpress? For example I have: ``` www.some.website.com/some/parameter ``` How would I get the end result that WP processes? Aka, the ``` www.some.website.com/index.php?paramter1=some&paramter2=parameter ``` Cheers
Have a look at the [Action Reference](http://codex.wordpress.org/Plugin_API/Action_Reference) to see generally how requests are processed. After all the loading and init stuff happens, the `parse_request` action runs when the request is matched against the rewrite rules, and an object is passed containing all the registered query vars and the matched rule and query string. ``` function wpd_parse_request( $request ){ echo $request->matched_query; } add_action( 'parse_request', 'wpd_parse_request' ); ``` After the `wp` action runs, that same object is stashed in the `wp` global. ``` global $wp; echo $wp->matched_query; ```
190,474
<p>I need to have the ability to have Sticky posts for each category. The simplest way to do this appeared to be to just create two loops on the page. This is what I wrote:</p> <pre><code>&lt;?php //Custom "sticky" loop $sticky_posts = new WP_Query(array( 'post__in' =&gt; get_option('sticky_posts') )); if ($sticky_posts-&gt;have_posts()) : while ($sticky_posts-&gt;have_posts()) : $sticky_posts-&gt;the_post(); get_template_part('post-formats/content', 'sticky'); endwhile; endif; // CLEAR DATA wp_reset_postdata(); if (have_posts()) : // Normal loop while (have_posts()) : the_post(); $format = get_post_format(); if (false === $format) { $format = 'standard'; } get_template_part('post-formats/content', $format); endwhile; </code></pre> <p>Unfortunately it doesn't work as expected:</p> <ol> <li>This places stickied items at the top of ALL categories, whether they belong to that category or not.</li> <li>Most of strangely of all: If there's no stickied posts at, all posts are displayed by the "sticky" loop -- and then repeated below by the normal loop. Weird!</li> </ol> <p>What have I done wrong? I realise that stickied posts will appear twice (once at the top, and again in their normal postition) but other than that, what's causing these issues? :-/</p>
[ { "answer_id": 190483, "author": "Django Reinhardt", "author_id": 4109, "author_profile": "https://wordpress.stackexchange.com/users/4109", "pm_score": 2, "selected": false, "text": "<p>The answer to both issues was pretty simple.</p>\n\n<ol>\n<li>Simply add an argument to WP_Query to limit to the current category</li>\n<li>Make sure that WP_Query doesn't run unless there's actually some sticky posts</li>\n</ol>\n\n<p>Like so:</p>\n\n<pre><code>&lt;?php\n// Get sticky posts\n$sticky_ids = get_option( 'sticky_posts' );\n\n// BEGIN Custom \"sticky\" loop\n\n// If sticky posts found...\nif(!empty($sticky_ids)) {\n $args = array(\n 'post_type' =&gt; 'post',\n 'category__in' =&gt; get_query_var('cat'), // Get current category only\n 'post__in' =&gt; get_option('sticky_posts') // Get stickied posts\n );\n\n $sticky_posts = new WP_Query($args);\n\n if ($sticky_posts-&gt;have_posts()) :\n while ($sticky_posts-&gt;have_posts()) : $sticky_posts-&gt;the_post();\n\n get_template_part('post-formats/content', 'sticky');\n\n endwhile; endif;\n// END Custom \"sticky\" loop\n\n // Reset post data ready for next loop\n wp_reset_postdata();\n}\n\nif (have_posts()) :\n\n /* Start the Loop */\n while (have_posts()) : the_post();\n\n $format = get_post_format();\n if (false === $format) {\n $format = 'standard';\n }\n get_template_part('post-formats/content', $format);\n\n endwhile; endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 190485, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>To make this more complete, here is what I have said in comments in reply to the question on hand</p>\n\n<blockquote>\n <p>Just to quickly explain, <code>WP_Query</code> fails catastrophically in some cases where empty arrays are passed to some of its parameters, instead of also returning an empty array as we should expect, <code>WP_Query</code> returns all posts. As for getting the correct stickies, as I said before, you need to get the current category id and use that to filter the sticky posts. Remember, with your approach, you need remove sticky posts from the main query otherwise you will get duplicates</p>\n</blockquote>\n\n<p>As an alternative solution using hooks and filters on the main query, and working from a <a href=\"https://wordpress.stackexchange.com/a/183620/31545\">similar question/answer</a>, this is what I have come up with: (<em>Code is well commented so it can be followed. CAVEAT: This is untested though, and needs at least PHP 5.4+</em>)</p>\n\n<pre><code>function get_term_sticky_posts()\n{\n // First check if we are on a category page, if not, return false\n if ( !is_category() )\n return false;\n\n // Secondly, check if we have stickies, return false on failure\n $stickies = get_option( 'sticky_posts' );\n\n if ( !$stickies )\n return false;\n\n // OK, we have stickies and we are on a category page, continue to execute. Get current object (category) ID\n $current_object = get_queried_object_id();\n\n // Create the query to get category specific stickies, just get post ID's though\n $args = [\n 'nopaging' =&gt; true,\n 'post__in' =&gt; $stickies,\n 'cat' =&gt; $current_object,\n 'ignore_sticky_posts' =&gt; 1,\n 'fields' =&gt; 'ids'\n ];\n $q = get_posts( $args );\n\n return $q;\n}\n\nadd_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // IMPORTANT, make sure to target front end only\n &amp;&amp; $q-&gt;is_main_query() // IMPORTANT, make sure we only target the main query\n &amp;&amp; $q-&gt;is_category() // Only target category archives\n ) {\n // Check if our function to get term related stickies exists to avoid fatal errors\n if ( function_exists( 'get_term_sticky_posts' ) ) {\n // check if we have stickies\n $stickies = get_term_sticky_posts();\n\n if ( $stickies ) {\n // Remove stickies from the main query to avoid duplicates\n $q-&gt;set( 'post__not_in', $stickies );\n\n // Check that we add stickies on the first page only, remove this check if you need stickies on all paged pages\n if ( !$q-&gt;is_paged() ) {\n\n // Add stickies via the the_posts filter\n add_filter( 'the_posts', function ( $posts ) use ( $stickies )\n { \n $term_stickies = get_posts( ['post__in' =&gt; $stickies, 'nopaging' =&gt; true] );\n\n $posts = array_merge( $term_stickies, $posts );\n\n return $posts;\n }, 10, 1 );\n }\n }\n }\n }\n});\n</code></pre>\n\n<h2>FEW NOTES:</h2>\n\n<ul>\n<li><p>This only works with default <code>category</code> taxonomy. The code can be easily modified (please do that, modify to your needs) to use any taxonomy and its relevant terms</p></li>\n<li><p>You just add this to functions.php. No need to alter your template files or using custom queries. All you need is the main query with default loop</p></li>\n</ul>\n\n<h2>EDIT</h2>\n\n<p>The above code is now tested and working on Wordpress 4.2.1 and PHP 5.4+</p>\n" }, { "answer_id": 299957, "author": "bz-mof", "author_id": 141221, "author_profile": "https://wordpress.stackexchange.com/users/141221", "pm_score": 2, "selected": false, "text": "<p>I cannot comment Pieter Goosen's answer due to reputation rules /-:</p>\n\n<p>The current code has a side-effect on current wordpress 4.8 (March 2018), it shows sticky posts when accessing a non-existing page thta should give a 404 error instead. Like \"www.example.com/asd\" where \"asd\" does not exist. Same problem it \"wp-admin\". This is because in that case \"asd\" or \"wp-admin\" is saved in $q as category name, although that is not an existing category.</p>\n\n<p>Fix: Check if the passed category really exists by adding the last line of this code into the code posted above:</p>\n\n<pre><code>if ( !is_admin() // IMPORTANT, make sure to target front end only\n &amp;&amp; $q-&gt;is_main_query() // IMPORTANT, make sure we only target the main query\n &amp;&amp; $q-&gt;is_category() // Only target category archives \n &amp;&amp; $q-&gt;is_tax(get_query_var ( 'category_name')) // Only target existing category names \n</code></pre>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190474", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4109/" ]
I need to have the ability to have Sticky posts for each category. The simplest way to do this appeared to be to just create two loops on the page. This is what I wrote: ``` <?php //Custom "sticky" loop $sticky_posts = new WP_Query(array( 'post__in' => get_option('sticky_posts') )); if ($sticky_posts->have_posts()) : while ($sticky_posts->have_posts()) : $sticky_posts->the_post(); get_template_part('post-formats/content', 'sticky'); endwhile; endif; // CLEAR DATA wp_reset_postdata(); if (have_posts()) : // Normal loop while (have_posts()) : the_post(); $format = get_post_format(); if (false === $format) { $format = 'standard'; } get_template_part('post-formats/content', $format); endwhile; ``` Unfortunately it doesn't work as expected: 1. This places stickied items at the top of ALL categories, whether they belong to that category or not. 2. Most of strangely of all: If there's no stickied posts at, all posts are displayed by the "sticky" loop -- and then repeated below by the normal loop. Weird! What have I done wrong? I realise that stickied posts will appear twice (once at the top, and again in their normal postition) but other than that, what's causing these issues? :-/
To make this more complete, here is what I have said in comments in reply to the question on hand > > Just to quickly explain, `WP_Query` fails catastrophically in some cases where empty arrays are passed to some of its parameters, instead of also returning an empty array as we should expect, `WP_Query` returns all posts. As for getting the correct stickies, as I said before, you need to get the current category id and use that to filter the sticky posts. Remember, with your approach, you need remove sticky posts from the main query otherwise you will get duplicates > > > As an alternative solution using hooks and filters on the main query, and working from a [similar question/answer](https://wordpress.stackexchange.com/a/183620/31545), this is what I have come up with: (*Code is well commented so it can be followed. CAVEAT: This is untested though, and needs at least PHP 5.4+*) ``` function get_term_sticky_posts() { // First check if we are on a category page, if not, return false if ( !is_category() ) return false; // Secondly, check if we have stickies, return false on failure $stickies = get_option( 'sticky_posts' ); if ( !$stickies ) return false; // OK, we have stickies and we are on a category page, continue to execute. Get current object (category) ID $current_object = get_queried_object_id(); // Create the query to get category specific stickies, just get post ID's though $args = [ 'nopaging' => true, 'post__in' => $stickies, 'cat' => $current_object, 'ignore_sticky_posts' => 1, 'fields' => 'ids' ]; $q = get_posts( $args ); return $q; } add_action( 'pre_get_posts', function ( $q ) { if ( !is_admin() // IMPORTANT, make sure to target front end only && $q->is_main_query() // IMPORTANT, make sure we only target the main query && $q->is_category() // Only target category archives ) { // Check if our function to get term related stickies exists to avoid fatal errors if ( function_exists( 'get_term_sticky_posts' ) ) { // check if we have stickies $stickies = get_term_sticky_posts(); if ( $stickies ) { // Remove stickies from the main query to avoid duplicates $q->set( 'post__not_in', $stickies ); // Check that we add stickies on the first page only, remove this check if you need stickies on all paged pages if ( !$q->is_paged() ) { // Add stickies via the the_posts filter add_filter( 'the_posts', function ( $posts ) use ( $stickies ) { $term_stickies = get_posts( ['post__in' => $stickies, 'nopaging' => true] ); $posts = array_merge( $term_stickies, $posts ); return $posts; }, 10, 1 ); } } } } }); ``` FEW NOTES: ---------- * This only works with default `category` taxonomy. The code can be easily modified (please do that, modify to your needs) to use any taxonomy and its relevant terms * You just add this to functions.php. No need to alter your template files or using custom queries. All you need is the main query with default loop EDIT ---- The above code is now tested and working on Wordpress 4.2.1 and PHP 5.4+
190,478
<p>Good Day Everyone,</p> <p>I am trying my New User Registration form Plugin on a live site, but the emails are not being sent.</p> <p>I save the new user using:</p> <pre><code> if (empty($errors)) { $myplugin_newuser = wp_insert_user(array( 'user_login' =&gt; $user_login, 'user_email' =&gt; $user_email, 'nickname' =&gt; $user_nickname, 'user_pass' =&gt; $user_pass, 'first_name' =&gt; $user_firstname, 'last_name' =&gt; $user_lastname, 'description' =&gt; $user_bio, 'user_url' =&gt; $user_url, 'user_registered' =&gt; date('Y-m-d H:i:s'), 'role' =&gt; 'subscriber' )); </code></pre> <p>After that I follow the official way of WordPress to change the New User Notification found here: </p> <pre><code>// Redefine user notification function if ( !function_exists('wp_new_user_notification') ) { function wp_new_user_notification( $user_id, $plaintext_pass = '' ) { $user = new WP_User( $user_id ); $user_login = stripslashes( $user-&gt;user_login ); $user_email = stripslashes( $user-&gt;user_email ); $message = sprintf( __('New user registration on %s:'), get_option('blogname') ) . "\r\n\r\n"; $message .= sprintf( __('Username: %s'), $user_login ) . "\r\n\r\n"; $message .= sprintf( __('E-mail: %s'), $user_email ) . "\r\n"; @wp_mail( get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname') ), $message ); if ( empty( $plaintext_pass ) ) return; $message = __('Hi there,') . "\r\n\r\n"; $message .= sprintf( __("Welcome to %s! Here's how to log in:"), get_option('blogname')) . "\r\n\r\n"; $message .= wp_login_url() . "\r\n"; $message .= sprintf( __('Username: %s'), $user_login ) . "\r\n"; $message .= sprintf( __('Password: %s'), $plaintext_pass ) . "\r\n\r\n"; $message .= sprintf( __('If you have any problems, please contact me at %s.'), get_option('admin_email') ) . "\r\n\r\n"; $message .= __('Adios!'); wp_mail( $user_email, sprintf( __('[%s] Your username and password'), get_option('blogname') ), $message ); } } </code></pre> <p>I know it's said that if the password information is not passed the email will not be sent to the user, but I don't seem to be receiving the email to my admin email either.</p> <p>But from my understanding of the code if '' is given that would mean it's empty but the information is passed so the email should be sent.</p> <p>Is it the way I Insert the new user that is not correct? Or is it something else that am missing.</p> <p>The tests were made, normal emails are being sent properly with my WP Mail Bank plugin.</p> <p>Just to make sure I also tried to call the function itself, as per the line above I am passing the user_login and user_pass information: </p> <pre><code>wp_new_user_notification( $user_login, $user_pass); </code></pre> <p><em>EDIT</em> Now that I use the function (which fixed a quarter of the issue), the admin receives the email, but without any details of the user_login or $user_pass (which are variables, as you can see above, I use to send the information WordPress to fill in the information inside the DB. </p> <p>-- Original Message --</p> <p>I was trying my new registration form plugin on a website live (Thanks @Pieter Goosen), but there is no email sent after the user has clicked register.</p> <p>The question is, is it because I use a different form that there is no email sent?</p> <p>I was thinking that the default email would be sent automatically?</p> <p>Do I absolutely have to setup an email inside my Plugin?</p> <p>Or should I expect WordPress to do it?</p> <p><em>-</em>-<em>-</em>-<em>-</em></p> <p>As Pieter mentioned in the comments, yes the emails are going through as I am using a plugin to use the SMTP and not the PHP mailer by default (Plugin named: Wp Mail Bank)</p> <p>The test was made BY the Plugin (to make sure there was not configuration changes on my servers) and I also disabled my plugin and try the original email from the normal Registration form of WordPress and I got both emails without any problems.</p>
[ { "answer_id": 190483, "author": "Django Reinhardt", "author_id": 4109, "author_profile": "https://wordpress.stackexchange.com/users/4109", "pm_score": 2, "selected": false, "text": "<p>The answer to both issues was pretty simple.</p>\n\n<ol>\n<li>Simply add an argument to WP_Query to limit to the current category</li>\n<li>Make sure that WP_Query doesn't run unless there's actually some sticky posts</li>\n</ol>\n\n<p>Like so:</p>\n\n<pre><code>&lt;?php\n// Get sticky posts\n$sticky_ids = get_option( 'sticky_posts' );\n\n// BEGIN Custom \"sticky\" loop\n\n// If sticky posts found...\nif(!empty($sticky_ids)) {\n $args = array(\n 'post_type' =&gt; 'post',\n 'category__in' =&gt; get_query_var('cat'), // Get current category only\n 'post__in' =&gt; get_option('sticky_posts') // Get stickied posts\n );\n\n $sticky_posts = new WP_Query($args);\n\n if ($sticky_posts-&gt;have_posts()) :\n while ($sticky_posts-&gt;have_posts()) : $sticky_posts-&gt;the_post();\n\n get_template_part('post-formats/content', 'sticky');\n\n endwhile; endif;\n// END Custom \"sticky\" loop\n\n // Reset post data ready for next loop\n wp_reset_postdata();\n}\n\nif (have_posts()) :\n\n /* Start the Loop */\n while (have_posts()) : the_post();\n\n $format = get_post_format();\n if (false === $format) {\n $format = 'standard';\n }\n get_template_part('post-formats/content', $format);\n\n endwhile; endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 190485, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>To make this more complete, here is what I have said in comments in reply to the question on hand</p>\n\n<blockquote>\n <p>Just to quickly explain, <code>WP_Query</code> fails catastrophically in some cases where empty arrays are passed to some of its parameters, instead of also returning an empty array as we should expect, <code>WP_Query</code> returns all posts. As for getting the correct stickies, as I said before, you need to get the current category id and use that to filter the sticky posts. Remember, with your approach, you need remove sticky posts from the main query otherwise you will get duplicates</p>\n</blockquote>\n\n<p>As an alternative solution using hooks and filters on the main query, and working from a <a href=\"https://wordpress.stackexchange.com/a/183620/31545\">similar question/answer</a>, this is what I have come up with: (<em>Code is well commented so it can be followed. CAVEAT: This is untested though, and needs at least PHP 5.4+</em>)</p>\n\n<pre><code>function get_term_sticky_posts()\n{\n // First check if we are on a category page, if not, return false\n if ( !is_category() )\n return false;\n\n // Secondly, check if we have stickies, return false on failure\n $stickies = get_option( 'sticky_posts' );\n\n if ( !$stickies )\n return false;\n\n // OK, we have stickies and we are on a category page, continue to execute. Get current object (category) ID\n $current_object = get_queried_object_id();\n\n // Create the query to get category specific stickies, just get post ID's though\n $args = [\n 'nopaging' =&gt; true,\n 'post__in' =&gt; $stickies,\n 'cat' =&gt; $current_object,\n 'ignore_sticky_posts' =&gt; 1,\n 'fields' =&gt; 'ids'\n ];\n $q = get_posts( $args );\n\n return $q;\n}\n\nadd_action( 'pre_get_posts', function ( $q )\n{\n if ( !is_admin() // IMPORTANT, make sure to target front end only\n &amp;&amp; $q-&gt;is_main_query() // IMPORTANT, make sure we only target the main query\n &amp;&amp; $q-&gt;is_category() // Only target category archives\n ) {\n // Check if our function to get term related stickies exists to avoid fatal errors\n if ( function_exists( 'get_term_sticky_posts' ) ) {\n // check if we have stickies\n $stickies = get_term_sticky_posts();\n\n if ( $stickies ) {\n // Remove stickies from the main query to avoid duplicates\n $q-&gt;set( 'post__not_in', $stickies );\n\n // Check that we add stickies on the first page only, remove this check if you need stickies on all paged pages\n if ( !$q-&gt;is_paged() ) {\n\n // Add stickies via the the_posts filter\n add_filter( 'the_posts', function ( $posts ) use ( $stickies )\n { \n $term_stickies = get_posts( ['post__in' =&gt; $stickies, 'nopaging' =&gt; true] );\n\n $posts = array_merge( $term_stickies, $posts );\n\n return $posts;\n }, 10, 1 );\n }\n }\n }\n }\n});\n</code></pre>\n\n<h2>FEW NOTES:</h2>\n\n<ul>\n<li><p>This only works with default <code>category</code> taxonomy. The code can be easily modified (please do that, modify to your needs) to use any taxonomy and its relevant terms</p></li>\n<li><p>You just add this to functions.php. No need to alter your template files or using custom queries. All you need is the main query with default loop</p></li>\n</ul>\n\n<h2>EDIT</h2>\n\n<p>The above code is now tested and working on Wordpress 4.2.1 and PHP 5.4+</p>\n" }, { "answer_id": 299957, "author": "bz-mof", "author_id": 141221, "author_profile": "https://wordpress.stackexchange.com/users/141221", "pm_score": 2, "selected": false, "text": "<p>I cannot comment Pieter Goosen's answer due to reputation rules /-:</p>\n\n<p>The current code has a side-effect on current wordpress 4.8 (March 2018), it shows sticky posts when accessing a non-existing page thta should give a 404 error instead. Like \"www.example.com/asd\" where \"asd\" does not exist. Same problem it \"wp-admin\". This is because in that case \"asd\" or \"wp-admin\" is saved in $q as category name, although that is not an existing category.</p>\n\n<p>Fix: Check if the passed category really exists by adding the last line of this code into the code posted above:</p>\n\n<pre><code>if ( !is_admin() // IMPORTANT, make sure to target front end only\n &amp;&amp; $q-&gt;is_main_query() // IMPORTANT, make sure we only target the main query\n &amp;&amp; $q-&gt;is_category() // Only target category archives \n &amp;&amp; $q-&gt;is_tax(get_query_var ( 'category_name')) // Only target existing category names \n</code></pre>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190478", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66412/" ]
Good Day Everyone, I am trying my New User Registration form Plugin on a live site, but the emails are not being sent. I save the new user using: ``` if (empty($errors)) { $myplugin_newuser = wp_insert_user(array( 'user_login' => $user_login, 'user_email' => $user_email, 'nickname' => $user_nickname, 'user_pass' => $user_pass, 'first_name' => $user_firstname, 'last_name' => $user_lastname, 'description' => $user_bio, 'user_url' => $user_url, 'user_registered' => date('Y-m-d H:i:s'), 'role' => 'subscriber' )); ``` After that I follow the official way of WordPress to change the New User Notification found here: ``` // Redefine user notification function if ( !function_exists('wp_new_user_notification') ) { function wp_new_user_notification( $user_id, $plaintext_pass = '' ) { $user = new WP_User( $user_id ); $user_login = stripslashes( $user->user_login ); $user_email = stripslashes( $user->user_email ); $message = sprintf( __('New user registration on %s:'), get_option('blogname') ) . "\r\n\r\n"; $message .= sprintf( __('Username: %s'), $user_login ) . "\r\n\r\n"; $message .= sprintf( __('E-mail: %s'), $user_email ) . "\r\n"; @wp_mail( get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname') ), $message ); if ( empty( $plaintext_pass ) ) return; $message = __('Hi there,') . "\r\n\r\n"; $message .= sprintf( __("Welcome to %s! Here's how to log in:"), get_option('blogname')) . "\r\n\r\n"; $message .= wp_login_url() . "\r\n"; $message .= sprintf( __('Username: %s'), $user_login ) . "\r\n"; $message .= sprintf( __('Password: %s'), $plaintext_pass ) . "\r\n\r\n"; $message .= sprintf( __('If you have any problems, please contact me at %s.'), get_option('admin_email') ) . "\r\n\r\n"; $message .= __('Adios!'); wp_mail( $user_email, sprintf( __('[%s] Your username and password'), get_option('blogname') ), $message ); } } ``` I know it's said that if the password information is not passed the email will not be sent to the user, but I don't seem to be receiving the email to my admin email either. But from my understanding of the code if '' is given that would mean it's empty but the information is passed so the email should be sent. Is it the way I Insert the new user that is not correct? Or is it something else that am missing. The tests were made, normal emails are being sent properly with my WP Mail Bank plugin. Just to make sure I also tried to call the function itself, as per the line above I am passing the user\_login and user\_pass information: ``` wp_new_user_notification( $user_login, $user_pass); ``` *EDIT* Now that I use the function (which fixed a quarter of the issue), the admin receives the email, but without any details of the user\_login or $user\_pass (which are variables, as you can see above, I use to send the information WordPress to fill in the information inside the DB. -- Original Message -- I was trying my new registration form plugin on a website live (Thanks @Pieter Goosen), but there is no email sent after the user has clicked register. The question is, is it because I use a different form that there is no email sent? I was thinking that the default email would be sent automatically? Do I absolutely have to setup an email inside my Plugin? Or should I expect WordPress to do it? *-*-*-*-*-* As Pieter mentioned in the comments, yes the emails are going through as I am using a plugin to use the SMTP and not the PHP mailer by default (Plugin named: Wp Mail Bank) The test was made BY the Plugin (to make sure there was not configuration changes on my servers) and I also disabled my plugin and try the original email from the normal Registration form of WordPress and I got both emails without any problems.
To make this more complete, here is what I have said in comments in reply to the question on hand > > Just to quickly explain, `WP_Query` fails catastrophically in some cases where empty arrays are passed to some of its parameters, instead of also returning an empty array as we should expect, `WP_Query` returns all posts. As for getting the correct stickies, as I said before, you need to get the current category id and use that to filter the sticky posts. Remember, with your approach, you need remove sticky posts from the main query otherwise you will get duplicates > > > As an alternative solution using hooks and filters on the main query, and working from a [similar question/answer](https://wordpress.stackexchange.com/a/183620/31545), this is what I have come up with: (*Code is well commented so it can be followed. CAVEAT: This is untested though, and needs at least PHP 5.4+*) ``` function get_term_sticky_posts() { // First check if we are on a category page, if not, return false if ( !is_category() ) return false; // Secondly, check if we have stickies, return false on failure $stickies = get_option( 'sticky_posts' ); if ( !$stickies ) return false; // OK, we have stickies and we are on a category page, continue to execute. Get current object (category) ID $current_object = get_queried_object_id(); // Create the query to get category specific stickies, just get post ID's though $args = [ 'nopaging' => true, 'post__in' => $stickies, 'cat' => $current_object, 'ignore_sticky_posts' => 1, 'fields' => 'ids' ]; $q = get_posts( $args ); return $q; } add_action( 'pre_get_posts', function ( $q ) { if ( !is_admin() // IMPORTANT, make sure to target front end only && $q->is_main_query() // IMPORTANT, make sure we only target the main query && $q->is_category() // Only target category archives ) { // Check if our function to get term related stickies exists to avoid fatal errors if ( function_exists( 'get_term_sticky_posts' ) ) { // check if we have stickies $stickies = get_term_sticky_posts(); if ( $stickies ) { // Remove stickies from the main query to avoid duplicates $q->set( 'post__not_in', $stickies ); // Check that we add stickies on the first page only, remove this check if you need stickies on all paged pages if ( !$q->is_paged() ) { // Add stickies via the the_posts filter add_filter( 'the_posts', function ( $posts ) use ( $stickies ) { $term_stickies = get_posts( ['post__in' => $stickies, 'nopaging' => true] ); $posts = array_merge( $term_stickies, $posts ); return $posts; }, 10, 1 ); } } } } }); ``` FEW NOTES: ---------- * This only works with default `category` taxonomy. The code can be easily modified (please do that, modify to your needs) to use any taxonomy and its relevant terms * You just add this to functions.php. No need to alter your template files or using custom queries. All you need is the main query with default loop EDIT ---- The above code is now tested and working on Wordpress 4.2.1 and PHP 5.4+
190,491
<p>dear I unable to understand of simple function call &amp; do_action function call.</p> <pre><code>do_action: </code></pre> <p>I hook function and I place this in my one template file for use in header template.</p> <pre><code>add_action('theme_document', 'run_this') function run_this() { &lt;!DOCTYPE html&gt; &lt;html class="no-js"&gt; &lt;head&gt; } </code></pre> <p>then I call it on my header <code>do_action('theme_document')</code> and it worked. But when it also worked in simple function call, then why need of call action hook?</p> <p>This code also work when I use this by a simple function call like:</p> <pre><code>function run_this() { &lt;!DOCTYPE html&gt; &lt;html class="no-js"&gt; &lt;head&gt; } </code></pre> <p>and I call this function in my header and it also worked</p> <pre><code>run_this(); </code></pre>
[ { "answer_id": 190497, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": false, "text": "<p>The main benefit with hooks ( such as <code>add_action</code> ) is that they allow you to add additional logic very easily based on priority. The only way to achieve the same thing with a standalone function is to edit the function directly. You wouldn't want to do this in premium theme ( or core ) as any time there's an update your function will be overwritten.</p>\n\n<p>Take the following example which outputs a title into the <code>&lt;title&gt;</code> tag. First we register our hook and put the call into the <code>header.php</code> file in it's respective spot.</p>\n\n<pre><code>/**\n * Custom Theme Title\n */\nfunction theme_custom_title() {\n do_action( 'theme_custom_title' );\n}\n</code></pre>\n\n<p><code>header.php</code> HTML</p>\n\n<pre><code>&lt;title&gt;&lt;?php echo theme_custom_title(); ?&gt;&lt;/title&gt;\n</code></pre>\n\n<p>Now that our custom hook is set up let's discuss priorities, the 3rd parameter of <a href=\"https://codex.wordpress.org/Function_Reference/add_action\" rel=\"nofollow\"><code>add_action</code></a>. Priorities allow us to run additional functions in order of priority in Ascending order, let's register 3 hooks to our Custom Hook.</p>\n\n<pre><code>function custom_title_one() {\n echo \"Hook One \";\n}\nadd_action( 'theme_custom_title', 'custom_title_one', 10 );\n\nfunction custom_title_two() {\n echo \"Hook Two \";\n}\nadd_action( 'theme_custom_title', 'custom_title_two', 20 );\n\nfunction custom_title_three() {\n echo \"Hook Three \";\n}\nadd_action( 'theme_custom_title', 'custom_title_three', 1 );\n</code></pre>\n\n<p>If we run the above we'll see the following output in the <code>&lt;title&gt;</code> tag:</p>\n\n<blockquote>\n <p>Hook Three Hook One Hook Two</p>\n</blockquote>\n\n<p>While it may seem trivial, this is fantastic for functions / hooks you <em>do not</em> want to actually overwrite. We could add these three hooks into a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">Child Theme</a> and it will always run these hooks no matter how many times the Parent Theme updates. If the function takes parameters you could conditionally handle and manipulate the parameter and return different output. This is much more difficult to achieve as a stand alone function and the purpose is to allow developers to modify the main function without actually overwriting its core functionality.</p>\n" }, { "answer_id": 190498, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">Actions</a> and <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference\" rel=\"nofollow noreferrer\">filters</a> are intended to allow third part code (though Core uses a lot of actions and filters as well) to modify how WordPress works without hacking the code. That is, <a href=\"http://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow noreferrer\">hooks</a> allow WordPress to be extended and altered without requiring hackers to modify the main body of code, which would be a nightmare when a new release comes out. </p>\n\n<p>Hooks are not meant simply as ways to fire a function. If that is all you are doing, you are using them incorrectly. You should be using hooks and filters to run code that modifies other code. For example, the incredibly useful <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> modifies the way that <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> operates: </p>\n\n<pre><code>function exclude_category( $query ) {\n if ( $query-&gt;is_home() &amp;&amp; $query-&gt;is_main_query() ) {\n $query-&gt;set( 'cat', '-1,-1347' );\n }\n}\nadd_action( 'pre_get_posts', 'exclude_category' );\n</code></pre>\n\n<p>To do that without using the hook would mean rewriting <code>WP_Query</code> or rolling your own SQL. </p>\n\n<p>Reference:\n<a href=\"https://wordpress.stackexchange.com/questions/103641/clarification-on-filters-and-hooks\">Clarification on filters and hooks</a></p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63068/" ]
dear I unable to understand of simple function call & do\_action function call. ``` do_action: ``` I hook function and I place this in my one template file for use in header template. ``` add_action('theme_document', 'run_this') function run_this() { <!DOCTYPE html> <html class="no-js"> <head> } ``` then I call it on my header `do_action('theme_document')` and it worked. But when it also worked in simple function call, then why need of call action hook? This code also work when I use this by a simple function call like: ``` function run_this() { <!DOCTYPE html> <html class="no-js"> <head> } ``` and I call this function in my header and it also worked ``` run_this(); ```
The main benefit with hooks ( such as `add_action` ) is that they allow you to add additional logic very easily based on priority. The only way to achieve the same thing with a standalone function is to edit the function directly. You wouldn't want to do this in premium theme ( or core ) as any time there's an update your function will be overwritten. Take the following example which outputs a title into the `<title>` tag. First we register our hook and put the call into the `header.php` file in it's respective spot. ``` /** * Custom Theme Title */ function theme_custom_title() { do_action( 'theme_custom_title' ); } ``` `header.php` HTML ``` <title><?php echo theme_custom_title(); ?></title> ``` Now that our custom hook is set up let's discuss priorities, the 3rd parameter of [`add_action`](https://codex.wordpress.org/Function_Reference/add_action). Priorities allow us to run additional functions in order of priority in Ascending order, let's register 3 hooks to our Custom Hook. ``` function custom_title_one() { echo "Hook One "; } add_action( 'theme_custom_title', 'custom_title_one', 10 ); function custom_title_two() { echo "Hook Two "; } add_action( 'theme_custom_title', 'custom_title_two', 20 ); function custom_title_three() { echo "Hook Three "; } add_action( 'theme_custom_title', 'custom_title_three', 1 ); ``` If we run the above we'll see the following output in the `<title>` tag: > > Hook Three Hook One Hook Two > > > While it may seem trivial, this is fantastic for functions / hooks you *do not* want to actually overwrite. We could add these three hooks into a [Child Theme](https://codex.wordpress.org/Child_Themes) and it will always run these hooks no matter how many times the Parent Theme updates. If the function takes parameters you could conditionally handle and manipulate the parameter and return different output. This is much more difficult to achieve as a stand alone function and the purpose is to allow developers to modify the main function without actually overwriting its core functionality.
190,509
<p>I can't seem to find where to delete/comment the line that prints:</p> <p><code>&lt;link rel="alternate" type="application/rss+xml" title="[site title] [single title] RSS de los comentarios" href="[site_url]/post/[single title]/feed/" /&gt;</code></p> <p>I've seen that there's a few plugins for this, but I just want not to rint this line...</p> <p>If found this <a href="https://wordpress.org/support/topic/remove-comments-rss-feed-link" rel="nofollow">here</a></p> <p><code>remove_action( 'wp_head', 'feed_links' ); remove_action( 'wp_head', 'rsd_link'); remove_action( 'wp_head', 'wlwmanifest_link'); remove_action( 'wp_head', 'index_rel_link'); remove_action( 'wp_head', 'parent_post_rel_link'); remove_action( 'wp_head', 'start_post_rel_link'); remove_action( 'wp_head', 'adjacent_posts_rel_link'); remove_action( 'wp_head', 'wp_generator');</code></p> <p>Wich looks great, but not working for me..</p> <p>Any thoughts?</p>
[ { "answer_id": 190521, "author": "Jon", "author_id": 14416, "author_profile": "https://wordpress.stackexchange.com/users/14416", "pm_score": -1, "selected": false, "text": "<p>look in header.php</p>\n\n<p>A trial an error way of finding it is to delete the whole php page, load your wordpress page, check your source (usually ctrl+u depending on browser) and see if your code is there. If not then your code is on that page. If you cant find it still - delete half the page and check. Repeat.</p>\n" }, { "answer_id": 190524, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>Things added by WordPress core can not be deleted or removed, or better said, shouldn't be modified directly. Instead, you can use any of the actions and filters.</p>\n<p>Specifically, to disable comments feeds, you can use this (note the priority parameter):</p>\n<pre><code>remove_action( 'wp_head', 'feed_links', 2 );\n</code></pre>\n<p>The above code will remove also other posts feed link, there is no specific action for comments links. So, if you want to add other <a href=\"https://codex.wordpress.org/WordPress_Feeds\" rel=\"noreferrer\">feed links you need to add them manually</a>, for example:</p>\n<pre><code>add_action( 'wp_head', function() {\n\n echo '&lt;link rel=&quot;alternate&quot; type=&quot;application/rss+xml&quot; title=&quot;RSS 2.0 Feed&quot; href=&quot;'.get_bloginfo('rss2_url').'&quot; /&gt;';\n\n} );\n</code></pre>\n<p>Also, you must know that <a href=\"https://codex.wordpress.org/Automatic_Feed_Links\" rel=\"noreferrer\">automatic feed links in <code>&lt;head&gt;</code> is a theme feature</a>, so, if you want to remove them you can also look for and remove this line in your theme functios.php:</p>\n<pre><code>add_theme_support( 'automatic-feed-links');\n</code></pre>\n<p>If none of these code snippets work, look for hard coded feed links in your theme, for example in header.php. If you find that links hardcoded in a template, you can complaint to the theme developer; that links shouldn't be there.</p>\n<h2>UPDATE</h2>\n<p>Since WordPress 4.4.0 you can use <a href=\"https://developer.wordpress.org/reference/hooks/feed_links_show_comments_feed/\" rel=\"noreferrer\"><code>feed_links_show_comments_feed</code> filter</a> to specifically remove comments feed link:</p>\n<pre><code>add_filter( 'feed_links_show_comments_feed', '__return_false' );\n</code></pre>\n" }, { "answer_id": 202521, "author": "glueckpress", "author_id": 23011, "author_profile": "https://wordpress.stackexchange.com/users/23011", "pm_score": 2, "selected": false, "text": "<p>From 4.4 on this seems to get easier with a brand-new filter: <a href=\"https://github.com/WordPress/WordPress/blob/504cd3bf15a754e9888fcba43f9e963c91fce527/wp-includes/general-template.php#L2311-L2320\" rel=\"nofollow\"><code>feed_links_show_posts_feed</code></a>. So <code>add_filter( 'feed_links_show_comments_feed', '__return_false' );</code> will do then.</p>\n" }, { "answer_id": 309509, "author": "Andrew Magill", "author_id": 132392, "author_profile": "https://wordpress.stackexchange.com/users/132392", "pm_score": 2, "selected": false, "text": "<p>The accepted answer did not disable the comment feed for pages and custom post types, just posts. I had to add a new filter to remove it entirely. Here is what I ended up with :</p>\n\n<pre><code>// remove comments feed\nadd_filter( 'feed_links_show_comments_feed', '__return_false' );\nremove_action( 'wp_head', 'feed_links' );\nfunction remove_comments_rss( $for_comments ) {\n return;\n}\nadd_filter('post_comments_feed_link','remove_comments_rss');\n</code></pre>\n\n<p>Sauce : <a href=\"https://wordpress.stackexchange.com/questions/218877/how-to-remove-cpt-comment-feed-from-head\">How to remove CPT comment feed from head?</a></p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190509", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3435/" ]
I can't seem to find where to delete/comment the line that prints: `<link rel="alternate" type="application/rss+xml" title="[site title] [single title] RSS de los comentarios" href="[site_url]/post/[single title]/feed/" />` I've seen that there's a few plugins for this, but I just want not to rint this line... If found this [here](https://wordpress.org/support/topic/remove-comments-rss-feed-link) `remove_action( 'wp_head', 'feed_links' ); remove_action( 'wp_head', 'rsd_link'); remove_action( 'wp_head', 'wlwmanifest_link'); remove_action( 'wp_head', 'index_rel_link'); remove_action( 'wp_head', 'parent_post_rel_link'); remove_action( 'wp_head', 'start_post_rel_link'); remove_action( 'wp_head', 'adjacent_posts_rel_link'); remove_action( 'wp_head', 'wp_generator');` Wich looks great, but not working for me.. Any thoughts?
Things added by WordPress core can not be deleted or removed, or better said, shouldn't be modified directly. Instead, you can use any of the actions and filters. Specifically, to disable comments feeds, you can use this (note the priority parameter): ``` remove_action( 'wp_head', 'feed_links', 2 ); ``` The above code will remove also other posts feed link, there is no specific action for comments links. So, if you want to add other [feed links you need to add them manually](https://codex.wordpress.org/WordPress_Feeds), for example: ``` add_action( 'wp_head', function() { echo '<link rel="alternate" type="application/rss+xml" title="RSS 2.0 Feed" href="'.get_bloginfo('rss2_url').'" />'; } ); ``` Also, you must know that [automatic feed links in `<head>` is a theme feature](https://codex.wordpress.org/Automatic_Feed_Links), so, if you want to remove them you can also look for and remove this line in your theme functios.php: ``` add_theme_support( 'automatic-feed-links'); ``` If none of these code snippets work, look for hard coded feed links in your theme, for example in header.php. If you find that links hardcoded in a template, you can complaint to the theme developer; that links shouldn't be there. UPDATE ------ Since WordPress 4.4.0 you can use [`feed_links_show_comments_feed` filter](https://developer.wordpress.org/reference/hooks/feed_links_show_comments_feed/) to specifically remove comments feed link: ``` add_filter( 'feed_links_show_comments_feed', '__return_false' ); ```
190,510
<p>Is there a way to add a TinyMCE editor to the taxonomy description field on the term editing pages? The solution here (<a href="https://wordpress.stackexchange.com/questions/15758/can-you-add-the-visual-editor-to-the-description-field-for-custom-taxonomies">Can you add the visual editor to the description field for custom taxonomies?</a>) no longer works, I think because the wp_tiny_mce function has been deprecated.</p>
[ { "answer_id": 190854, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 5, "selected": true, "text": "<p>You can use a <strong>{$taxonomy}_edit_form_fields</strong> action hook to add html to the term edit table. In that HTML you can remove description textarea and add tinymce editor</p>\n\n<pre><code>add_action(\"{$taxonomy}_edit_form_fields\", 'add_form_fields_example', 10, 2);\n\nfunction add_form_fields_example($term, $taxonomy){\n ?&gt;\n &lt;tr valign=\"top\"&gt;\n &lt;th scope=\"row\"&gt;Description&lt;/th&gt;\n &lt;td&gt;\n &lt;?php wp_editor(html_entity_decode($term-&gt;description), 'description', array('media_buttons' =&gt; false)); ?&gt;\n &lt;script&gt;\n jQuery(window).ready(function(){\n jQuery('label[for=description]').parent().parent().remove();\n });\n &lt;/script&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php\n} \n</code></pre>\n" }, { "answer_id": 365995, "author": "jg314", "author_id": 26202, "author_profile": "https://wordpress.stackexchange.com/users/26202", "pm_score": 3, "selected": false, "text": "<p>For those still looking for a solution to this problem, it's worth mentioning that the <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"noreferrer\">Yoast SEO plugin</a> adds a WYSIWYG editor for descriptions automatically on the taxonomy term edit screen.</p>\n\n<p>If you're not planning to use that plugin for SEO please don't add it only for this functionality. Given the plugin's popularity, I figured it was worth noting it here since it could save time for someone who already plans to install the plugin.</p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190510", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9764/" ]
Is there a way to add a TinyMCE editor to the taxonomy description field on the term editing pages? The solution here ([Can you add the visual editor to the description field for custom taxonomies?](https://wordpress.stackexchange.com/questions/15758/can-you-add-the-visual-editor-to-the-description-field-for-custom-taxonomies)) no longer works, I think because the wp\_tiny\_mce function has been deprecated.
You can use a **{$taxonomy}\_edit\_form\_fields** action hook to add html to the term edit table. In that HTML you can remove description textarea and add tinymce editor ``` add_action("{$taxonomy}_edit_form_fields", 'add_form_fields_example', 10, 2); function add_form_fields_example($term, $taxonomy){ ?> <tr valign="top"> <th scope="row">Description</th> <td> <?php wp_editor(html_entity_decode($term->description), 'description', array('media_buttons' => false)); ?> <script> jQuery(window).ready(function(){ jQuery('label[for=description]').parent().parent().remove(); }); </script> </td> </tr> <?php } ```
190,511
<p>I want to show only one latest post by each author and found this code that it working. However, it takes too long to load the page since I have over 100K authors and 100K posts in database. How can I optimize this code?</p> <pre><code>&lt;?php //Displaying latest post per author on front page function filter_where($where = '') { global $wpdb; $where .= " AND wp_posts.id = (select id from {$wpdb-&gt;prefix}posts p2 where p2.post_status = 'publish' and p2.post_author = {$wpdb-&gt;prefix}posts.post_author order by p2.post_date desc limit 0,1)"; return $where; } add_filter('posts_where', 'filter_where'); query_posts($query_string); //The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); ... ?&gt; </code></pre> <p>Here is an original article for the code.</p> <p><a href="http://www.dbuggr.com/smallwei/show-latest-post-author-wordpress-front-page/" rel="nofollow">http://www.dbuggr.com/smallwei/show-latest-post-author-wordpress-front-page/</a></p>
[ { "answer_id": 190854, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 5, "selected": true, "text": "<p>You can use a <strong>{$taxonomy}_edit_form_fields</strong> action hook to add html to the term edit table. In that HTML you can remove description textarea and add tinymce editor</p>\n\n<pre><code>add_action(\"{$taxonomy}_edit_form_fields\", 'add_form_fields_example', 10, 2);\n\nfunction add_form_fields_example($term, $taxonomy){\n ?&gt;\n &lt;tr valign=\"top\"&gt;\n &lt;th scope=\"row\"&gt;Description&lt;/th&gt;\n &lt;td&gt;\n &lt;?php wp_editor(html_entity_decode($term-&gt;description), 'description', array('media_buttons' =&gt; false)); ?&gt;\n &lt;script&gt;\n jQuery(window).ready(function(){\n jQuery('label[for=description]').parent().parent().remove();\n });\n &lt;/script&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php\n} \n</code></pre>\n" }, { "answer_id": 365995, "author": "jg314", "author_id": 26202, "author_profile": "https://wordpress.stackexchange.com/users/26202", "pm_score": 3, "selected": false, "text": "<p>For those still looking for a solution to this problem, it's worth mentioning that the <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"noreferrer\">Yoast SEO plugin</a> adds a WYSIWYG editor for descriptions automatically on the taxonomy term edit screen.</p>\n\n<p>If you're not planning to use that plugin for SEO please don't add it only for this functionality. Given the plugin's popularity, I figured it was worth noting it here since it could save time for someone who already plans to install the plugin.</p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74171/" ]
I want to show only one latest post by each author and found this code that it working. However, it takes too long to load the page since I have over 100K authors and 100K posts in database. How can I optimize this code? ``` <?php //Displaying latest post per author on front page function filter_where($where = '') { global $wpdb; $where .= " AND wp_posts.id = (select id from {$wpdb->prefix}posts p2 where p2.post_status = 'publish' and p2.post_author = {$wpdb->prefix}posts.post_author order by p2.post_date desc limit 0,1)"; return $where; } add_filter('posts_where', 'filter_where'); query_posts($query_string); //The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); ... ?> ``` Here is an original article for the code. <http://www.dbuggr.com/smallwei/show-latest-post-author-wordpress-front-page/>
You can use a **{$taxonomy}\_edit\_form\_fields** action hook to add html to the term edit table. In that HTML you can remove description textarea and add tinymce editor ``` add_action("{$taxonomy}_edit_form_fields", 'add_form_fields_example', 10, 2); function add_form_fields_example($term, $taxonomy){ ?> <tr valign="top"> <th scope="row">Description</th> <td> <?php wp_editor(html_entity_decode($term->description), 'description', array('media_buttons' => false)); ?> <script> jQuery(window).ready(function(){ jQuery('label[for=description]').parent().parent().remove(); }); </script> </td> </tr> <?php } ```
190,515
<p>I'm developing a site that involves a lot of long posts I'd like to break up using the nextpage quicktag. On the first page there's a large splash photo in the header that I'd like to disappear on subsequent pages—so I need some way of testing if the user is on the first page. I did find this code:</p> <p><code>if ( isset($wp_query-&gt;query_vars['page'] ) )</code></p> <p>But that seems to only works with default permalink settings. I need something that works with the Postname permalink setting. Any help is greatly appreciated.</p>
[ { "answer_id": 190854, "author": "Oleg Butuzov", "author_id": 14536, "author_profile": "https://wordpress.stackexchange.com/users/14536", "pm_score": 5, "selected": true, "text": "<p>You can use a <strong>{$taxonomy}_edit_form_fields</strong> action hook to add html to the term edit table. In that HTML you can remove description textarea and add tinymce editor</p>\n\n<pre><code>add_action(\"{$taxonomy}_edit_form_fields\", 'add_form_fields_example', 10, 2);\n\nfunction add_form_fields_example($term, $taxonomy){\n ?&gt;\n &lt;tr valign=\"top\"&gt;\n &lt;th scope=\"row\"&gt;Description&lt;/th&gt;\n &lt;td&gt;\n &lt;?php wp_editor(html_entity_decode($term-&gt;description), 'description', array('media_buttons' =&gt; false)); ?&gt;\n &lt;script&gt;\n jQuery(window).ready(function(){\n jQuery('label[for=description]').parent().parent().remove();\n });\n &lt;/script&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php\n} \n</code></pre>\n" }, { "answer_id": 365995, "author": "jg314", "author_id": 26202, "author_profile": "https://wordpress.stackexchange.com/users/26202", "pm_score": 3, "selected": false, "text": "<p>For those still looking for a solution to this problem, it's worth mentioning that the <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"noreferrer\">Yoast SEO plugin</a> adds a WYSIWYG editor for descriptions automatically on the taxonomy term edit screen.</p>\n\n<p>If you're not planning to use that plugin for SEO please don't add it only for this functionality. Given the plugin's popularity, I figured it was worth noting it here since it could save time for someone who already plans to install the plugin.</p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73676/" ]
I'm developing a site that involves a lot of long posts I'd like to break up using the nextpage quicktag. On the first page there's a large splash photo in the header that I'd like to disappear on subsequent pages—so I need some way of testing if the user is on the first page. I did find this code: `if ( isset($wp_query->query_vars['page'] ) )` But that seems to only works with default permalink settings. I need something that works with the Postname permalink setting. Any help is greatly appreciated.
You can use a **{$taxonomy}\_edit\_form\_fields** action hook to add html to the term edit table. In that HTML you can remove description textarea and add tinymce editor ``` add_action("{$taxonomy}_edit_form_fields", 'add_form_fields_example', 10, 2); function add_form_fields_example($term, $taxonomy){ ?> <tr valign="top"> <th scope="row">Description</th> <td> <?php wp_editor(html_entity_decode($term->description), 'description', array('media_buttons' => false)); ?> <script> jQuery(window).ready(function(){ jQuery('label[for=description]').parent().parent().remove(); }); </script> </td> </tr> <?php } ```
190,529
<p>I uploaded a brand-new wp install to my host. I am able to access the admin, and all its settings just fine, but I get a 500 internal error on the front-end.</p> <p><strong>I have tried solving this issue by:</strong></p> <ul> <li>checking .htaccess</li> <li>checking wp-config.php</li> <li>checking for missing core files</li> <li>doing a permalink reset</li> <li>checking file permissions</li> <li>switching themes</li> <li>disabling all plugins</li> <li>using a default theme</li> <li>server config (i have a vps with other sites working just fine under the same config).</li> </ul> <p>What else can I check for? Could setting up wordpress under one php version and then moving it to another server under another php version cause this issue?</p> <p>My .htaccess file has what you would expect.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre>
[ { "answer_id": 190603, "author": "gdaniel", "author_id": 30984, "author_profile": "https://wordpress.stackexchange.com/users/30984", "pm_score": 1, "selected": false, "text": "<p>My problem had to do with file permissions. Even though it looked like the permissions were correct, the index.php in the root had the permission set to 644, instead of 664. Once I changed the permission the front-end loaded. It's a bit odd that of all files in the root, the index is the only one with the wrong permission.</p>\n" }, { "answer_id": 256582, "author": "ritsa", "author_id": 113400, "author_profile": "https://wordpress.stackexchange.com/users/113400", "pm_score": 1, "selected": false, "text": "<p>It can be simple mistakes in your code too.In my case I had forgotten the php closing tag and started another opening tag in the header file</p>\n" }, { "answer_id": 387032, "author": "Shane McCurdy", "author_id": 172334, "author_profile": "https://wordpress.stackexchange.com/users/172334", "pm_score": 0, "selected": false, "text": "<p>I have been chasing my tail for hours trying to find this problem, and it wound up being that the theme codebase from my project was developed on a PHP 5.* environment and I had it setup on PHP 7.2... and the code had the old <code>&lt;?</code> opening tag (now deprecated, with no <code>php</code> after the question mark in the opening tags) all over the place. I had to hunt them all down and add the <code>php</code> so they looked like this <code>&lt;?php</code>.</p>\n<p>Try doing a search for <code>&lt;? </code> with the white space after the question mark, then switch the search mode to REGEX and use <code>&lt;\\?\\n</code> as the string to look for line returns after the question mark.</p>\n<p>I made a YouTube about finding these little <code>&lt;?</code> buggers awhile back, if it helps anyone:</p>\n<p><strong>PHP HOW TO FIND: &quot;Parse error: syntax error, unexpected end of file in...&quot;</strong>\n<a href=\"https://www.youtube.com/watch?v=dzXaQ3cttRU\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=dzXaQ3cttRU</a></p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190529", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/30984/" ]
I uploaded a brand-new wp install to my host. I am able to access the admin, and all its settings just fine, but I get a 500 internal error on the front-end. **I have tried solving this issue by:** * checking .htaccess * checking wp-config.php * checking for missing core files * doing a permalink reset * checking file permissions * switching themes * disabling all plugins * using a default theme * server config (i have a vps with other sites working just fine under the same config). What else can I check for? Could setting up wordpress under one php version and then moving it to another server under another php version cause this issue? My .htaccess file has what you would expect. ``` # 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 ```
My problem had to do with file permissions. Even though it looked like the permissions were correct, the index.php in the root had the permission set to 644, instead of 664. Once I changed the permission the front-end loaded. It's a bit odd that of all files in the root, the index is the only one with the wrong permission.
190,532
<p>I'm trying to use the plugin PrivateContent to limit access to certain pages/categories. I have a function (getAllowedCategories()) which reads PrivateContent access levels for the current user and outputs a list of category IDs which the user has access to. I'm trying to use this to build a foreach() loop that passes each ID to a WP_QUERY and generates the latest two posts in that category. But when I try to use a variable as WP_QUERY's parameter, it does no filtering at all. Here is my code: </p> <pre><code>&lt;?php $currentCats = getAllowedCategories($user_data); foreach ($currentCats as $currentCat) { echo $currentCat . "&lt;br/&gt;"; $parameters = "'category__in=" . $currentCat . "'"; $aj_query = new WP_Query( $parameters ); if ( $aj_query-&gt;have_posts() ) { echo '&lt;ul&gt;'; while ( $aj_query-&gt;have_posts() ) { $aj_query-&gt;the_post(); echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } wp_reset_postdata(); } ?&gt; </code></pre>
[ { "answer_id": 190549, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>You are wrapping your parameters string in unnecessary layer of quotes:</p>\n\n<ul>\n<li><code>$parameters = \"'category__in=1'\";</code> — wrong</li>\n<li><code>$parameters = 'category__in=1';</code> — right</li>\n</ul>\n\n<p>It is usually preferable to use arrays for query arguments:</p>\n\n<ul>\n<li><code>$parameters = [ 'category__in' =&gt; 1 ];</code></li>\n</ul>\n" }, { "answer_id": 190553, "author": "authorandrew", "author_id": 52164, "author_profile": "https://wordpress.stackexchange.com/users/52164", "pm_score": 0, "selected": false, "text": "<p>The WordPress code guide tripped me up on this one. It was wrapping query parameters in single quotes -- which works, when everything is plain text (e.g. <code>$aj_query = new WP_Query( 'category__in=4');</code>)</p>\n\n<p>There's no need for a $parameters variable to pass into <code>WP_QUERY</code> (though I assume this method might work as well) By ditching the single quotes and just passing <code>$currentCat</code> directly into <code>WP_QUERY</code>, everything filters exactly right. The final code for the query is as follows:</p>\n\n<p><code>$aj_query = new WP_Query( \"category__in=\" . $currentCat);</code></p>\n\n<p>This will read the variable correctly and return all posts directly in that category (not children posts -- if you want to include child categories, use <code>\"cat\"</code> instead of <code>\"category__in\"</code>.</p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190532", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52164/" ]
I'm trying to use the plugin PrivateContent to limit access to certain pages/categories. I have a function (getAllowedCategories()) which reads PrivateContent access levels for the current user and outputs a list of category IDs which the user has access to. I'm trying to use this to build a foreach() loop that passes each ID to a WP\_QUERY and generates the latest two posts in that category. But when I try to use a variable as WP\_QUERY's parameter, it does no filtering at all. Here is my code: ``` <?php $currentCats = getAllowedCategories($user_data); foreach ($currentCats as $currentCat) { echo $currentCat . "<br/>"; $parameters = "'category__in=" . $currentCat . "'"; $aj_query = new WP_Query( $parameters ); if ( $aj_query->have_posts() ) { echo '<ul>'; while ( $aj_query->have_posts() ) { $aj_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; } wp_reset_postdata(); } ?> ```
You are wrapping your parameters string in unnecessary layer of quotes: * `$parameters = "'category__in=1'";` — wrong * `$parameters = 'category__in=1';` — right It is usually preferable to use arrays for query arguments: * `$parameters = [ 'category__in' => 1 ];`
190,540
<p>I have a page that has a new template, and I want to set that new template with wp-cli.</p> <p>When I <code>wp post get &lt;id&gt;</code> I get an output like the following:</p> <pre><code>+-----------------------+---------------------+ | Field | Value | +-----------------------+---------------------+ | ID | 4 | | post_author | 5 | | post_date | 2012-03-09 13:11:38 | | post_date_gmt | 0000-00-00 00:00:00 | | post_content | | | post_title | Home Page | | post_excerpt | | | post_status | publish | | comment_status | closed | | ping_status | open | | post_password | | | post_name | home | | to_ping | | | pinged | | | post_modified | 2015-06-04 12:23:41 | | post_modified_gmt | 2015-06-04 19:23:41 | | post_content_filtered | | | post_parent | 0 | | guid | /?page_id=4 | | menu_order | 0 | | post_type | page | | post_mime_type | | | comment_count | 0 | +-----------------------+---------------------+ </code></pre> <p>This doesn't have the attribute I am looking for <code>page_template</code></p> <p>When I try what seems to be the correct attribute key:<br> <code>wp post update 4 --page_template='New Home Page'</code> </p> <p>I get <code>Warning: The page template is invalid.</code></p>
[ { "answer_id": 190542, "author": "Mike Lyons", "author_id": 20884, "author_profile": "https://wordpress.stackexchange.com/users/20884", "pm_score": 3, "selected": true, "text": "<p>I found that in the <a href=\"http://wp-cli.org/commands/post/create/\" rel=\"nofollow\">documentation</a> for wp-cli it says</p>\n\n<blockquote>\n <p><code>[--&lt;field&gt;=&lt;value&gt;]</code> Associative args for the new post. See\n <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_post\" rel=\"nofollow\">wp_insert_post().</a></p>\n</blockquote>\n\n<p>Which then subsequently shows:</p>\n\n<blockquote>\n<pre><code>'page_template' =&gt; [ &lt;string&gt; ] // Requires name of template file, eg. template.php.\n</code></pre>\n</blockquote>\n\n<p>The command is <code>wp post update 4 --page_template='new-home.php'</code></p>\n" }, { "answer_id": 298643, "author": "Prisoner 13", "author_id": 122236, "author_profile": "https://wordpress.stackexchange.com/users/122236", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>This doesn't have the attribute I am looking for <code>page_template</code></p>\n</blockquote>\n\n<p>Try using <code>page_template</code> in <code>fields</code>:</p>\n\n<pre><code>wp post list --post_type=page,post --fields=ID,post_title,post_name,post_type,page_template\n</code></pre>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20884/" ]
I have a page that has a new template, and I want to set that new template with wp-cli. When I `wp post get <id>` I get an output like the following: ``` +-----------------------+---------------------+ | Field | Value | +-----------------------+---------------------+ | ID | 4 | | post_author | 5 | | post_date | 2012-03-09 13:11:38 | | post_date_gmt | 0000-00-00 00:00:00 | | post_content | | | post_title | Home Page | | post_excerpt | | | post_status | publish | | comment_status | closed | | ping_status | open | | post_password | | | post_name | home | | to_ping | | | pinged | | | post_modified | 2015-06-04 12:23:41 | | post_modified_gmt | 2015-06-04 19:23:41 | | post_content_filtered | | | post_parent | 0 | | guid | /?page_id=4 | | menu_order | 0 | | post_type | page | | post_mime_type | | | comment_count | 0 | +-----------------------+---------------------+ ``` This doesn't have the attribute I am looking for `page_template` When I try what seems to be the correct attribute key: `wp post update 4 --page_template='New Home Page'` I get `Warning: The page template is invalid.`
I found that in the [documentation](http://wp-cli.org/commands/post/create/) for wp-cli it says > > `[--<field>=<value>]` Associative args for the new post. See > [wp\_insert\_post().](https://codex.wordpress.org/Function_Reference/wp_insert_post) > > > Which then subsequently shows: > > > ``` > 'page_template' => [ <string> ] // Requires name of template file, eg. template.php. > > ``` > > The command is `wp post update 4 --page_template='new-home.php'`
190,554
<p>I'm stuck in an awful situation and I think it's because I've registered 5 post types but calling flash_rewrite_rules() function just once, so I have this question:</p> <p>Should I call flash_rewrite_rules() function after each registration of custom post type or just one call?</p> <p>And by the way, is it OK to have 10 custom post type for a theme (or as many as we want)? any effect on performance?</p> <p>Thank you.</p> <pre><code> &lt;?php /*** Registering book post type ***/ function px_book() { $labels = array( 'name' =&gt; 'books', 'singular_name' =&gt; 'book', 'menu_name' =&gt; 'books', ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'book' ), 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'book', $args ); } add_action( 'init', 'px_book' ); /*** Registering book post type ***/ function px_movie() { $labels = array( 'name' =&gt; 'movies', 'singular_name' =&gt; 'movie', 'menu_name' =&gt; 'movies', ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'movie' ), 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'movie', $args ); } add_action( 'init', 'px_movie' ); add_action( 'after_switch_theme', 'flush_rewrite_rules' ); ?&gt; </code></pre> <p>or like this: </p> <pre><code> &lt;?php /*** Registering book post type ***/ function px_book() { $labels = array( 'name' =&gt; 'books', 'singular_name' =&gt; 'book', 'menu_name' =&gt; 'books', ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'book' ), 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'book', $args ); } add_action( 'init', 'px_book' ); add_action( 'after_switch_theme', 'flush_rewrite_rules' ); /*** Registering book post type ***/ function px_movie() { $labels = array( 'name' =&gt; 'movies', 'singular_name' =&gt; 'movie', 'menu_name' =&gt; 'movies', ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'movie' ), 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'movie', $args ); } add_action( 'init', 'px_movie' ); add_action( 'after_switch_theme', 'flush_rewrite_rules' ); ?&gt; </code></pre>
[ { "answer_id": 190657, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>Your problem is that you are flushing the rewrite rules before the post types are registered. Your <code>after_switch_theme</code> should look something like this:</p>\n\n<pre><code>function px_book() {\n $labels = array(\n 'name' =&gt; 'books',\n 'singular_name' =&gt; 'book',\n 'menu_name' =&gt; 'books',\n );\n\n $args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'book' ),\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; 5,\n 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' )\n );\n\n register_post_type( 'book', $args );\n}\nadd_action( 'init', 'px_book' );\n\nfunction px_movie() {\n $labels = array(\n 'name' =&gt; 'movies',\n 'singular_name' =&gt; 'movie',\n 'menu_name' =&gt; 'movies',\n );\n\n $args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'movie' ),\n 'capability_type' =&gt; 'post',\n 'has_archive' =&gt; true,\n 'hierarchical' =&gt; false,\n 'menu_position' =&gt; 5,\n 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' )\n );\n\n register_post_type( 'movie', $args );\n}\nadd_action( 'init', 'px_movie' );\n\nadd_action( 'after_switch_theme', function() {\n\n // At this point, post types are not registered\n\n // register post types\n px_movie();\n px_book();\n\n // flush rewrite rules\n flush_rewrite_rules();\n\n} );\n</code></pre>\n\n<p>Why? When you click on \"Activate\" a theme, the <code>init</code> event in the next page load is triggered before your theme is activated, so on <code>after_switch_theme</code> the functions you hook on <code>init</code> are not triggered. It is similar what is described in <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#Flushing_Rewrite_on_Activation\" rel=\"nofollow\">register_post_type on Codex</a> when registering post types in plugins (by the way, I think registering post types should be done in plugins, not in themes. Themes are for look and feel, post types are content structure, not look and feel. If you switch to another theme you lose the content, <strong>that is very bad</strong>).</p>\n" }, { "answer_id": 265186, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Don't call <code>flush_rewrite_rules</code>. It's a super expensive call to make and slows everything down.</p>\n<p>Also the order matters, but the correct thing to do is register all your content types, then re-save permalinks in WP Admin, and then... nothing, you've done everything. Only flush permalinks when things have changed, not on every page load. Visiting the permalinks page should be enough to flush them.</p>\n<p>Also, don't register post types and taxonomies inside themes, you'll loose access to the data when the user switches to another theme. Themes are for looks, plugins are for functionality</p>\n" } ]
2015/06/04
[ "https://wordpress.stackexchange.com/questions/190554", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74115/" ]
I'm stuck in an awful situation and I think it's because I've registered 5 post types but calling flash\_rewrite\_rules() function just once, so I have this question: Should I call flash\_rewrite\_rules() function after each registration of custom post type or just one call? And by the way, is it OK to have 10 custom post type for a theme (or as many as we want)? any effect on performance? Thank you. ``` <?php /*** Registering book post type ***/ function px_book() { $labels = array( 'name' => 'books', 'singular_name' => 'book', 'menu_name' => 'books', ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'book' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'book', $args ); } add_action( 'init', 'px_book' ); /*** Registering book post type ***/ function px_movie() { $labels = array( 'name' => 'movies', 'singular_name' => 'movie', 'menu_name' => 'movies', ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'movie' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'movie', $args ); } add_action( 'init', 'px_movie' ); add_action( 'after_switch_theme', 'flush_rewrite_rules' ); ?> ``` or like this: ``` <?php /*** Registering book post type ***/ function px_book() { $labels = array( 'name' => 'books', 'singular_name' => 'book', 'menu_name' => 'books', ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'book' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'book', $args ); } add_action( 'init', 'px_book' ); add_action( 'after_switch_theme', 'flush_rewrite_rules' ); /*** Registering book post type ***/ function px_movie() { $labels = array( 'name' => 'movies', 'singular_name' => 'movie', 'menu_name' => 'movies', ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'movie' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' ) ); register_post_type( 'movie', $args ); } add_action( 'init', 'px_movie' ); add_action( 'after_switch_theme', 'flush_rewrite_rules' ); ?> ```
Don't call `flush_rewrite_rules`. It's a super expensive call to make and slows everything down. Also the order matters, but the correct thing to do is register all your content types, then re-save permalinks in WP Admin, and then... nothing, you've done everything. Only flush permalinks when things have changed, not on every page load. Visiting the permalinks page should be enough to flush them. Also, don't register post types and taxonomies inside themes, you'll loose access to the data when the user switches to another theme. Themes are for looks, plugins are for functionality
190,559
<p>I am following this DIY code by GravityWiz but the author doesn't mention how to make the code work with 30 minutes, 1 hour, 2 hours, etc...? He only explains how to make it work with 24 hours - <a href="http://gravitywiz.com/better-limit-submission-per-time-period-by-user-or-ip/" rel="nofollow">http://gravitywiz.com/better-limit-submission-per-time-period-by-user-or-ip/</a></p> <p>When looking at the code here - <a href="https://gist.githubusercontent.com/spivurno/4024361/raw/gw-gravity-forms-submission-limit.php" rel="nofollow">https://gist.githubusercontent.com/spivurno/4024361/raw/gw-gravity-forms-submission-limit.php</a></p> <p>Does this mean I make the functions:</p> <pre><code># Basic Usage new GW_Submission_Limit( array( 'form_id' =&gt; 86, 'limit' =&gt; 1, 'time_period' =&gt; '60', 'limit_message' =&gt; 'Aha! You have been limited for 60 minutes!.' ) ); </code></pre> <p>Would this be the right way to do it? I posted a comment on their site but never got an answer, which was a few days ago :(</p>
[ { "answer_id": 190565, "author": "Dave from Gravity Wiz", "author_id": 50224, "author_profile": "https://wordpress.stackexchange.com/users/50224", "pm_score": 1, "selected": false, "text": "<p>I've updated the article with more detailed instructions on the time_period usage. For others having the same question here:</p>\n\n<blockquote><p>The period of time to which the limit applies. The default time period is one day. In any 24 hour period, if the user reaches the limit they will no longer be able to make new submissions.</p>\n\n<p>If you want to limit by less than a day, you can provide the time period in seconds. A time period of 60 would be one minute (60 seconds). A time period of 60 * 60 (or 3600) would be one hour.</p>\n\n<p>Also supported are three different calendar periods: per_day, per_month, per_year. Calendar time periods are more rigid time periods that “reset” when the calendar time period expires (i.e. one month ends and another begins).</p>\n\n<p>If you do not want to limit by a time period at all, set the time period to false.</p></blockquote>\n" }, { "answer_id": 346500, "author": "swapnil SHIVAJI jadhav", "author_id": 174558, "author_profile": "https://wordpress.stackexchange.com/users/174558", "pm_score": 0, "selected": false, "text": "<p>The period of time to which the limit applies. The default time period is one day. In any 24 hour period, if the user reaches the limit they will no longer be able to make new submissions.</p>\n\n<p>If you want to limit by less than a day, you can provide the time period in seconds. A time period of 60 would be one minute (60 seconds). A time period of 60 * 60 (or 3600) would be one hour.</p>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29189/" ]
I am following this DIY code by GravityWiz but the author doesn't mention how to make the code work with 30 minutes, 1 hour, 2 hours, etc...? He only explains how to make it work with 24 hours - <http://gravitywiz.com/better-limit-submission-per-time-period-by-user-or-ip/> When looking at the code here - <https://gist.githubusercontent.com/spivurno/4024361/raw/gw-gravity-forms-submission-limit.php> Does this mean I make the functions: ``` # Basic Usage new GW_Submission_Limit( array( 'form_id' => 86, 'limit' => 1, 'time_period' => '60', 'limit_message' => 'Aha! You have been limited for 60 minutes!.' ) ); ``` Would this be the right way to do it? I posted a comment on their site but never got an answer, which was a few days ago :(
I've updated the article with more detailed instructions on the time\_period usage. For others having the same question here: > The period of time to which the limit applies. The default time period is one day. In any 24 hour period, if the user reaches the limit they will no longer be able to make new submissions. > > > If you want to limit by less than a day, you can provide the time period in seconds. A time period of 60 would be one minute (60 seconds). A time period of 60 \* 60 (or 3600) would be one hour. > > > Also supported are three different calendar periods: per\_day, per\_month, per\_year. Calendar time periods are more rigid time periods that “reset” when the calendar time period expires (i.e. one month ends and another begins). > > > If you do not want to limit by a time period at all, set the time period to false. > >
190,568
<p>I get this type of data using <code>print_r()</code></p> <pre><code> Array ( [0] =&gt; test [1] =&gt; [email protected] [2] =&gt; 1.00 [3] =&gt; 21:16:36 Jun 04, 2015 PDT [4] =&gt; 9DS7592P74GMN ) </code></pre> <p>Now I want to add this data in my custom table but I cant.</p> <p>Here is my code</p> <pre><code> if(!empty($_POST)) { $player_name = $_POST['first_name']; $payer_email = $_POST['payer_email']; $payment_gross = $_POST['payment_gross']; $payment_date = $_POST['payment_date']; $payer_id = $_POST['payer_id']; $paypal_str = array($player_name, $payer_email, $payment_gross, $payment_date, $payer_id); print_r($paypal_str); global $wpdb; $wpdb-&gt;insert( 'paypal', array( 'name' =&gt; $paypal_str[0], 'email' =&gt; $paypal_str[1], 'amount' =&gt; $paypal_str[2], 'player_id' =&gt; $paypal_str[3], 'date' =&gt; $paypal_str[4], ) ); } </code></pre>
[ { "answer_id": 190565, "author": "Dave from Gravity Wiz", "author_id": 50224, "author_profile": "https://wordpress.stackexchange.com/users/50224", "pm_score": 1, "selected": false, "text": "<p>I've updated the article with more detailed instructions on the time_period usage. For others having the same question here:</p>\n\n<blockquote><p>The period of time to which the limit applies. The default time period is one day. In any 24 hour period, if the user reaches the limit they will no longer be able to make new submissions.</p>\n\n<p>If you want to limit by less than a day, you can provide the time period in seconds. A time period of 60 would be one minute (60 seconds). A time period of 60 * 60 (or 3600) would be one hour.</p>\n\n<p>Also supported are three different calendar periods: per_day, per_month, per_year. Calendar time periods are more rigid time periods that “reset” when the calendar time period expires (i.e. one month ends and another begins).</p>\n\n<p>If you do not want to limit by a time period at all, set the time period to false.</p></blockquote>\n" }, { "answer_id": 346500, "author": "swapnil SHIVAJI jadhav", "author_id": 174558, "author_profile": "https://wordpress.stackexchange.com/users/174558", "pm_score": 0, "selected": false, "text": "<p>The period of time to which the limit applies. The default time period is one day. In any 24 hour period, if the user reaches the limit they will no longer be able to make new submissions.</p>\n\n<p>If you want to limit by less than a day, you can provide the time period in seconds. A time period of 60 would be one minute (60 seconds). A time period of 60 * 60 (or 3600) would be one hour.</p>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190568", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74198/" ]
I get this type of data using `print_r()` ``` Array ( [0] => test [1] => [email protected] [2] => 1.00 [3] => 21:16:36 Jun 04, 2015 PDT [4] => 9DS7592P74GMN ) ``` Now I want to add this data in my custom table but I cant. Here is my code ``` if(!empty($_POST)) { $player_name = $_POST['first_name']; $payer_email = $_POST['payer_email']; $payment_gross = $_POST['payment_gross']; $payment_date = $_POST['payment_date']; $payer_id = $_POST['payer_id']; $paypal_str = array($player_name, $payer_email, $payment_gross, $payment_date, $payer_id); print_r($paypal_str); global $wpdb; $wpdb->insert( 'paypal', array( 'name' => $paypal_str[0], 'email' => $paypal_str[1], 'amount' => $paypal_str[2], 'player_id' => $paypal_str[3], 'date' => $paypal_str[4], ) ); } ```
I've updated the article with more detailed instructions on the time\_period usage. For others having the same question here: > The period of time to which the limit applies. The default time period is one day. In any 24 hour period, if the user reaches the limit they will no longer be able to make new submissions. > > > If you want to limit by less than a day, you can provide the time period in seconds. A time period of 60 would be one minute (60 seconds). A time period of 60 \* 60 (or 3600) would be one hour. > > > Also supported are three different calendar periods: per\_day, per\_month, per\_year. Calendar time periods are more rigid time periods that “reset” when the calendar time period expires (i.e. one month ends and another begins). > > > If you do not want to limit by a time period at all, set the time period to false. > >
190,588
<p>I see that upon upgrades the .maintenance file is deleted, if present. Is it still a viable/correct way to put WP in maintenance mode? </p>
[ { "answer_id": 190590, "author": "gmazzap", "author_id": 35541, "author_profile": "https://wordpress.stackexchange.com/users/35541", "pm_score": 6, "selected": true, "text": "<p>Not really.</p>\n\n<p><code>.maintenance</code> is a temporary file, not viable if you want to put your site in maintenance mode for a long time.</p>\n\n<p>If you look at <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/load.php#L162-L165\" rel=\"noreferrer\">source</a> the maintenance mode is maintained only if <code>$upgrading</code> variable defined in the file is no older than 10 minutes.</p>\n\n<p>It means <code>.maintenance</code> is a sort of <em>lock file</em> when WordPress is upgrading plugins, themes or itself, something that should not last more than 10 minutes.</p>\n\n<p>Surely is possible to insert into that file something like:</p>\n\n<pre><code>$upgrading = time();\n</code></pre>\n\n<p>And in theory hold WordPress in maintenance mode, but once it is intended to be a temporary file, WordPress feels free to delete the file after a successfull update.</p>\n\n<p>For a long-duration maintenance mode you need to use a different solution.</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/169610/35541\">Here</a> you'll find one. </p>\n" }, { "answer_id": 254771, "author": "li bing zhao", "author_id": 108466, "author_profile": "https://wordpress.stackexchange.com/users/108466", "pm_score": 5, "selected": false, "text": "<p>Step 1: Create a file <code>.maintenance</code> in the WP root directory like <code>.htaccess</code> </p>\n\n<p>Step 2: Put this code in the file </p>\n\n<pre><code>&lt;?php $upgrading = time(); ?&gt;\n</code></pre>\n\n<p>Step 3: Save the file. Then you can see the default maintenance message 'Briefly unavailable for scheduled maintenance. Check back in a minute.'. </p>\n\n<p>Step 4: Once you have finished the repair or upgrade, then delete the code or the file <code>.maintenance</code>.</p>\n\n<p>In case you want to have your own custom warning message, create a <code>maintenance.php</code> file and placing it in your <code>/wp-content/</code> directory. WordPress uses this file to display during any forced maintenance period that you might have.</p>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190588", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10381/" ]
I see that upon upgrades the .maintenance file is deleted, if present. Is it still a viable/correct way to put WP in maintenance mode?
Not really. `.maintenance` is a temporary file, not viable if you want to put your site in maintenance mode for a long time. If you look at [source](https://github.com/WordPress/WordPress/blob/master/wp-includes/load.php#L162-L165) the maintenance mode is maintained only if `$upgrading` variable defined in the file is no older than 10 minutes. It means `.maintenance` is a sort of *lock file* when WordPress is upgrading plugins, themes or itself, something that should not last more than 10 minutes. Surely is possible to insert into that file something like: ``` $upgrading = time(); ``` And in theory hold WordPress in maintenance mode, but once it is intended to be a temporary file, WordPress feels free to delete the file after a successfull update. For a long-duration maintenance mode you need to use a different solution. [Here](https://wordpress.stackexchange.com/a/169610/35541) you'll find one.
190,594
<p>I'm using this plugin (<a href="https://github.com/parisholley/wordpress-fantastic-elasticsearch" rel="nofollow">FantasticElasticSearch</a>) to index content when it's published. So far it was strightforward and an easy task but, now that I tried to index a flag saying if a post is sticky, I'm having trouble and it's being impossible.</p> <p>I'm changing the addOrUpdate function of the plugin to my profit, I'm adding some data (featured image, featured video...) and as I said I want to index if a post is sticky. The problem is that the database is not updated in the index moment, and I don't know how to hook to that event.</p> <p>This is what's happening now:</p> <ol> <li>I publish a post, non-sticky.</li> <li>I check if the post is sticky to add that information to the index, so far all is good and it's indexed well (as a non-sticky post is_sticky returns false).</li> <li>I edit the post and turn it to an Sticky post. When I check if the post is sticky it returns false again, as if it wasnt updated in the database yet.</li> </ol> <p>So, where do I have to hook? Can I force the update of the database with the sticky/nonsticky information with some function?</p> <p>The function (addOrUpdate) that I'm rewritting is the one that's in <a href="http://I&#39;m%20rewritting%20the%20addOrUpdate%20function%20that%20there&#39;s%20in%20this%20file:%20[https://github.com/parisholley/wordpress-fantastic-elasticsearch/blob/master/src/elasticsearch/Indexer.php].">this file</a>.</p> <p>I turned it into something like this:</p> <pre><code>static function addOrUpdate($post){ $type = self::_index(true)-&gt;getType($post-&gt;post_type); $data = self::_build_document($post); //filling $data with extra fields I'd like to index $data['is_sticky'] = is_sticky(); //now the document is added to elastic. $type-&gt;addDocument(new \Elastica\Document($post-&gt;ID, $data)); } </code></pre> <p>The addOrUpdate function hooks into the save_post event as you can see <a href="https://github.com/parisholley/wordpress-fantastic-elasticsearch/blob/master/wp/admin/hooks.php" rel="nofollow">in the hooks.php</a> file.</p> <p>I'm still unable to get this working, I'd aprecciate any help you could give me on this matter. By the way, I already tried Pat J's method (is_sticky with Id post as a parameter, but I'm in the loop as I'm in the save_post action).</p> <p>Finally solved it by looking in the $_POST array. $_POST['sticky'] is only informed when a POST is (<strong>or is being made</strong>) sticky.</p>
[ { "answer_id": 190609, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>If you're not in The Loop, you should pass an ID to <code>is_sticky()</code>:</p>\n\n<pre><code>static function addOrUpdate($post){\n $type = self::_index(true)-&gt;getType($post-&gt;post_type);\n $data = self::_build_document($post);\n\n //filling $data with extra fields I'd like to index\n $data['is_sticky'] = is_sticky( $post-&gt;ID );\n\n //now the document is added to elastic.\n $type-&gt;addDocument(new \\Elastica\\Document($post-&gt;ID, $data)); \n}\n</code></pre>\n\n<p>This assumes that the <code>$post</code> parameter you pass in is a <a href=\"https://developer.wordpress.org/reference/classes/wp_post/\" rel=\"nofollow\"><code>WP_Post</code></a> object.</p>\n\n<h3>Reference</h3>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/is_sticky/\" rel=\"nofollow\"><code>is_sticky()</code></a></li>\n</ul>\n" }, { "answer_id": 192961, "author": "Astaroth", "author_id": 74215, "author_profile": "https://wordpress.stackexchange.com/users/74215", "pm_score": 2, "selected": true, "text": "<p>As I said in the question post, I finally solved it by looking into the $_POST global. There's a <code>$_POST['sticky']</code> field (valued as <em>'sticky'</em>) that is there just when a Post is <em>sticky</em> or is being made <em>sticky</em>, and it's not when a post is not <em>sticky</em> or is being <em>unsticked</em>.</p>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190594", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74215/" ]
I'm using this plugin ([FantasticElasticSearch](https://github.com/parisholley/wordpress-fantastic-elasticsearch)) to index content when it's published. So far it was strightforward and an easy task but, now that I tried to index a flag saying if a post is sticky, I'm having trouble and it's being impossible. I'm changing the addOrUpdate function of the plugin to my profit, I'm adding some data (featured image, featured video...) and as I said I want to index if a post is sticky. The problem is that the database is not updated in the index moment, and I don't know how to hook to that event. This is what's happening now: 1. I publish a post, non-sticky. 2. I check if the post is sticky to add that information to the index, so far all is good and it's indexed well (as a non-sticky post is\_sticky returns false). 3. I edit the post and turn it to an Sticky post. When I check if the post is sticky it returns false again, as if it wasnt updated in the database yet. So, where do I have to hook? Can I force the update of the database with the sticky/nonsticky information with some function? The function (addOrUpdate) that I'm rewritting is the one that's in [this file](http://I'm%20rewritting%20the%20addOrUpdate%20function%20that%20there's%20in%20this%20file:%20[https://github.com/parisholley/wordpress-fantastic-elasticsearch/blob/master/src/elasticsearch/Indexer.php].). I turned it into something like this: ``` static function addOrUpdate($post){ $type = self::_index(true)->getType($post->post_type); $data = self::_build_document($post); //filling $data with extra fields I'd like to index $data['is_sticky'] = is_sticky(); //now the document is added to elastic. $type->addDocument(new \Elastica\Document($post->ID, $data)); } ``` The addOrUpdate function hooks into the save\_post event as you can see [in the hooks.php](https://github.com/parisholley/wordpress-fantastic-elasticsearch/blob/master/wp/admin/hooks.php) file. I'm still unable to get this working, I'd aprecciate any help you could give me on this matter. By the way, I already tried Pat J's method (is\_sticky with Id post as a parameter, but I'm in the loop as I'm in the save\_post action). Finally solved it by looking in the $\_POST array. $\_POST['sticky'] is only informed when a POST is (**or is being made**) sticky.
As I said in the question post, I finally solved it by looking into the $\_POST global. There's a `$_POST['sticky']` field (valued as *'sticky'*) that is there just when a Post is *sticky* or is being made *sticky*, and it's not when a post is not *sticky* or is being *unsticked*.
190,616
<p>We've turned on WordPress Auto-Updates (yey!), but, just in case this does break anything, we'd like to only run Auto-Updates during daylight hours (e.g. 09:00 - 17:30).</p> <p>We have the "on init" WP-Cron disabled, and are calling it from the servers crontab every 10 minutes.</p> <p>How can adapt the AutoUpdate, so all updates are run during these times? I've looked at hooks for WP-Cron, but got a little lost.</p> <p>Additionally - is there a hook that fires once an auto-updated is complete? Our code is in source control, and I'm looking at ways to 'auto-commit' a new branch into our code after an update (rather than having to do it manually).</p> <p><em>(The duplicate question doesn't provide any guidance into the hooks to check - simply suggesting to edit the Database - it also talks about WP Cron being fired 'on load' - rather than running on a dedicated cron).</em></p> <p>Cheers, Darren</p>
[ { "answer_id": 191018, "author": "Ben Cole", "author_id": 32532, "author_profile": "https://wordpress.stackexchange.com/users/32532", "pm_score": 3, "selected": false, "text": "<p>This one is actually surprisingly simple; add this to your wp-config.php file and all automatic updates will be blocked when outside of the specified hours:</p>\n\n<pre><code>// Suspend updates when outside of business hours, 9:00 AM to 5:30 PM\n$updates_suspended = (date('Hi') &lt; 0900 || date('Hi') &gt; 1730);\n\ndefine( 'AUTOMATIC_UPDATER_DISABLED', $updates_suspended );\n</code></pre>\n\n<p>You can also use <a href=\"https://codex.wordpress.org/Configuring_Automatic_Background_Updates\" rel=\"noreferrer\">these other constants and filters</a> to control which automatic updates are allowed to run if you need to make this more specific. </p>\n\n<blockquote>\n <p>Make sure you use the <strong>server timezone</strong> when you set this. The function <code>date()</code> might be configured to use a timezone that is different from your local timezone. </p>\n</blockquote>\n" }, { "answer_id": 372252, "author": "iohnatan", "author_id": 192590, "author_profile": "https://wordpress.stackexchange.com/users/192590", "pm_score": 2, "selected": false, "text": "<p>Based on &quot;BenCole&quot; answer:</p>\n<p>date() is affected by runtime timezone changes which can cause date/time to be incorrectly displayed. better to use WordPress native current_datetime() that &quot;retrieves the current time as an object with the timezone from settings&quot;.</p>\n<pre><code> $current_time = current_datetime()-&gt;format( 'Hi' );\n\n $disable_updater = ( $current_time &gt; 900 || $current_time &lt; 1730 );\n\n define( 'AUTOMATIC_UPDATER_DISABLED', $disable_updater );\n</code></pre>\n" }, { "answer_id": 400386, "author": "laurent avril", "author_id": 197591, "author_profile": "https://wordpress.stackexchange.com/users/197591", "pm_score": 0, "selected": false, "text": "<pre><code>// An example to allow plugin auto update between &quot;friday 6pm et monday 12am&quot; :\n$updates_suspended = !((date('N') == 5 &amp;&amp; date('G') &gt; 17) || in_array(date('N'), array(6,7)) || (date('N') == 1 &amp;&amp; date('G') &lt; 12)(;\ndefine( 'AUTOMATIC_UPDATER_DISABLED', $updates_suspended );\n</code></pre>\n<p>the value of date('N') is an integer who is the day of the week (1 to monday and 5 to friday)\nthe value of date('G') is an integer who is the hour of day\nIf you just want handle with hour of day, use only date('G')\nExample : to allow update plugin auto every day only after 11pm and before 6am :</p>\n<pre><code>$updates_suspended = !((date('G') &lt; 6 || date('G') &gt; 22));\ndefine( 'AUTOMATIC_UPDATER_DISABLED', $updates_suspended );\n</code></pre>\n<p>This code goes in wp-config.php, it have been tested and it works.</p>\n<p>More details on dates here : <a href=\"https://www.php.net/manual/fr/function.date.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/fr/function.date.php</a></p>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190616", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74235/" ]
We've turned on WordPress Auto-Updates (yey!), but, just in case this does break anything, we'd like to only run Auto-Updates during daylight hours (e.g. 09:00 - 17:30). We have the "on init" WP-Cron disabled, and are calling it from the servers crontab every 10 minutes. How can adapt the AutoUpdate, so all updates are run during these times? I've looked at hooks for WP-Cron, but got a little lost. Additionally - is there a hook that fires once an auto-updated is complete? Our code is in source control, and I'm looking at ways to 'auto-commit' a new branch into our code after an update (rather than having to do it manually). *(The duplicate question doesn't provide any guidance into the hooks to check - simply suggesting to edit the Database - it also talks about WP Cron being fired 'on load' - rather than running on a dedicated cron).* Cheers, Darren
This one is actually surprisingly simple; add this to your wp-config.php file and all automatic updates will be blocked when outside of the specified hours: ``` // Suspend updates when outside of business hours, 9:00 AM to 5:30 PM $updates_suspended = (date('Hi') < 0900 || date('Hi') > 1730); define( 'AUTOMATIC_UPDATER_DISABLED', $updates_suspended ); ``` You can also use [these other constants and filters](https://codex.wordpress.org/Configuring_Automatic_Background_Updates) to control which automatic updates are allowed to run if you need to make this more specific. > > Make sure you use the **server timezone** when you set this. The function `date()` might be configured to use a timezone that is different from your local timezone. > > >
190,618
<p>I am trying to get rid of the following error in debug:</p> <pre><code>Notice: register_sidebar was called &lt;strong&gt;incorrectly&lt;/strong&gt;. No &lt;code&gt;id&lt;/code&gt; was set in the arguments array for the "Header" sidebar. </code></pre> <p>So when I register that sidebar I added the id parameter like so:</p> <pre><code>register_sidebar(array( 'id' =&gt; 'header-sidebar', 'name' =&gt; 'Header', 'before_widget' =&gt; '&lt;div class="widget"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h3 class="widget-title"&gt;', 'after_title' =&gt; '&lt;/h3&gt;', )); </code></pre> <p>Now no matter if I use the name field or the id field <code>dynamic_sidebar</code> always returns false.</p> <p>I've tried:</p> <pre><code>dynamic_sidebar( 'Header' ); </code></pre> <p>and</p> <pre><code>dynamic_sidebar( 'header-sidebar' ); </code></pre> <p>My understand is both of the above should work. Note if I comment out the id parameter in the register_sidebar call and use <code>dynamic_sidebar( 'Header' );</code> everything works fine. What am I missing?</p> <p>This is WP 4.2.2.</p> <p>So per these directions: <a href="https://wordpress.stackexchange.com/questions/13450/list-all-sidebar-names">List all sidebar names?</a> I was able to list all the sidebar names and when I set the id parameter with <code>register_sidebar</code> the id in the list of names changes. The specific sidebar I'm playing with now is 'sidebar-5' before setting an id and 'sidebar-jsp' after. Once the id field is set I can not use <code>dynamic_sidebar</code> with the name 'Sidebar', the original id 'sidebar-5' or the new id 'sidebar-jsp'.</p> <p>Per s_ha_dum's suggestion I wrapped a single sidebar inside a function so that I could make it happen after 'widgets_init'. This did not work. </p> <pre><code>function register_header_sidebar_jsp() { register_sidebar(array( 'name' =&gt; 'Sidebar', 'id' =&gt; 'sidebar-jsp', 'before_widget' =&gt; '&lt;div class="widget"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;h3 class="widget-title"&gt;', 'after_title' =&gt; '&lt;/h3&gt;', )); } add_action( 'widgets_init', 'register_header_sidebar_jsp' ); </code></pre> <p>I'm calling it right now with:</p> <pre><code>&lt;?php var_dump(dynamic_sidebar('sidebar-jsp')); ?&gt; </code></pre> <p>I'm not sure what's going on but I don't have all day to mess with this. Thanks for your suggestions everyone.</p>
[ { "answer_id": 190622, "author": "shanebp", "author_id": 16575, "author_profile": "https://wordpress.stackexchange.com/users/16575", "pm_score": -1, "selected": false, "text": "<p>Try starting the <code>id</code> field value with 'sidebar'.</p>\n\n<p>If that doesn't work, the order shouldn't matter, but try following the codex example:</p>\n\n<pre><code>register_sidebar( array(\n 'name' =&gt; __( 'Main Sidebar', 'theme-slug' ),\n 'id' =&gt; 'sidebar-1',\n 'description' =&gt; __( 'show on all posts and pages', 'theme-slug' ),\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) );\n</code></pre>\n\n<p>Also try not using the word 'header' in the <code>id</code> field. </p>\n" }, { "answer_id": 190623, "author": "Brad Dalton", "author_id": 9884, "author_profile": "https://wordpress.stackexchange.com/users/9884", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php dynamic_sidebar( 'new-header-sidebar' ); ?&gt;\n\nregister_sidebar( array(\n 'name' =&gt; __( 'Header', 'theme-slug' ),\n 'id' =&gt; 'new-header-sidebar',\n) );\n</code></pre>\n\n<p>You may have a I.D conflict so try changing the I.D</p>\n" }, { "answer_id": 190630, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 1, "selected": false, "text": "<p>Your code works when I test it. I can only assume that the registration code is being hooked into the system too early or too late. <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow\"><code>register_sidebar()</code> should be hooked on <code>widgets_init</code> per the Codex</a>. Therefore:</p>\n\n<pre><code>function register_header_sidebar_wpse_190618() {\n register_sidebar(\n array(\n 'id' =&gt; 'header-sidebar',\n 'name' =&gt; 'Header',\n 'before_widget' =&gt; '&lt;div class=\"widget\"&gt;',\n 'after_widget' =&gt; '&lt;/div&gt;',\n 'before_title' =&gt; '&lt;h3 class=\"widget-title\"&gt;',\n 'after_title' =&gt; '&lt;/h3&gt;',\n )\n );\n}\nadd_action( 'widgets_init', 'register_header_sidebar_wpse_190618' );\n</code></pre>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190618", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23259/" ]
I am trying to get rid of the following error in debug: ``` Notice: register_sidebar was called <strong>incorrectly</strong>. No <code>id</code> was set in the arguments array for the "Header" sidebar. ``` So when I register that sidebar I added the id parameter like so: ``` register_sidebar(array( 'id' => 'header-sidebar', 'name' => 'Header', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', )); ``` Now no matter if I use the name field or the id field `dynamic_sidebar` always returns false. I've tried: ``` dynamic_sidebar( 'Header' ); ``` and ``` dynamic_sidebar( 'header-sidebar' ); ``` My understand is both of the above should work. Note if I comment out the id parameter in the register\_sidebar call and use `dynamic_sidebar( 'Header' );` everything works fine. What am I missing? This is WP 4.2.2. So per these directions: [List all sidebar names?](https://wordpress.stackexchange.com/questions/13450/list-all-sidebar-names) I was able to list all the sidebar names and when I set the id parameter with `register_sidebar` the id in the list of names changes. The specific sidebar I'm playing with now is 'sidebar-5' before setting an id and 'sidebar-jsp' after. Once the id field is set I can not use `dynamic_sidebar` with the name 'Sidebar', the original id 'sidebar-5' or the new id 'sidebar-jsp'. Per s\_ha\_dum's suggestion I wrapped a single sidebar inside a function so that I could make it happen after 'widgets\_init'. This did not work. ``` function register_header_sidebar_jsp() { register_sidebar(array( 'name' => 'Sidebar', 'id' => 'sidebar-jsp', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', )); } add_action( 'widgets_init', 'register_header_sidebar_jsp' ); ``` I'm calling it right now with: ``` <?php var_dump(dynamic_sidebar('sidebar-jsp')); ?> ``` I'm not sure what's going on but I don't have all day to mess with this. Thanks for your suggestions everyone.
Your code works when I test it. I can only assume that the registration code is being hooked into the system too early or too late. [`register_sidebar()` should be hooked on `widgets_init` per the Codex](https://codex.wordpress.org/Function_Reference/register_sidebar). Therefore: ``` function register_header_sidebar_wpse_190618() { register_sidebar( array( 'id' => 'header-sidebar', 'name' => 'Header', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'register_header_sidebar_wpse_190618' ); ```
190,625
<p>How do I gee the numbered pagination of custom wpdb result? </p> <p>below code will show one latest post from each authors in the site. I want to show 20 posts per page with a numbered pagination.</p> <pre><code>$postids = $wpdb-&gt;get_results( " SELECT a.ID, a.post_title, a.post_author, a.post_date FROM $wpdb-&gt;posts a JOIN ( SELECT max(post_date) post_date, post_author FROM $wpdb-&gt;posts WHERE post_status = 'publish' AND post_type = 'post' GROUP BY post_author ) b ON a.post_author = b.post_author AND a.post_date = b.post_date WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC " ); foreach ( $postids as $postid ) { //setup_postdata( $postid ); echo $postid-&gt;ID." :: ".$postid-&gt;post_title." :: ".$postid-&gt;post_author . "&lt;br /&gt;" ; //get_template_part( 'content', 'category' ); } </code></pre>
[ { "answer_id": 190632, "author": "Ohsik", "author_id": 74171, "author_profile": "https://wordpress.stackexchange.com/users/74171", "pm_score": 2, "selected": false, "text": "<p>So I ended getting what I wanted to do with below code. However, I know this is not a good way to do this. Please feel free to share your advice on this code.</p>\n\n<pre><code>global $wpdb;\nglobal $post;\n\n// Pagination Setup\n$posts_per_page = 20;\n$start = 0;\n$paged = get_query_var( 'paged') ? get_query_var( 'paged', 1 ) : 1; // Current page number\n$start = ($paged-1)*$posts_per_page;\n\n$num_of_total_posts = $wpdb-&gt;get_results( \n \"\n SELECT a.ID, a.post_title, a.post_author, a.post_date\n FROM $wpdb-&gt;posts a\n JOIN (\n SELECT max(post_date) post_date, post_author\n FROM $wpdb-&gt;posts\n WHERE post_status = 'publish' \n AND post_type = 'post'\n GROUP BY post_author\n ) b ON a.post_author = b.post_author AND a.post_date = b.post_date\n WHERE post_status = 'publish' \n AND post_type = 'post'\n ORDER BY post_date DESC\n \"\n);\n$total_posts = $wpdb-&gt;num_rows; // Get Total number of posts\n\n\n$postids = $wpdb-&gt;get_results( \n \"\n SELECT a.ID, a.post_title, a.post_author, a.post_date, a.post_name\n FROM $wpdb-&gt;posts a\n JOIN (\n SELECT max(post_date) post_date, post_author\n FROM $wpdb-&gt;posts\n WHERE post_status = 'publish' \n AND post_type = 'post'\n GROUP BY post_author\n ) b ON a.post_author = b.post_author AND a.post_date = b.post_date\n WHERE post_status = 'publish' \n AND post_type = 'post'\n ORDER BY post_date DESC\n LIMIT $start, $posts_per_page\n \"\n);\n\n// Loop content\nforeach ( $postids as $post ):\n setup_postdata($post);\n get_template_part( 'content', 'category' );\nendforeach;\n\n\n// Display Pagination\n$total_page = ceil( $total_posts / $posts_per_page); // Calculate Total pages\n\n$prev_arrow = is_rtl() ? '&amp;rarr;' : '&amp;larr;';\n$next_arrow = is_rtl() ? '&amp;larr;' : '&amp;rarr;';\n\nglobal $wp_query;\n$big = 999999999; // need an unlikely integer\nif( $total &gt; 1 ) {\n if( !$current_page = get_query_var('paged') )\n $current_page = 1;\n if( get_option('permalink_structure') ) {\n $format = 'page/%#%/';\n } else {\n $format = '&amp;paged=%#%';\n }\n echo paginate_links(array(\n 'base' =&gt; str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' =&gt; $format,\n 'current' =&gt; max( 1, get_query_var('paged') ),\n 'total' =&gt; $total_page,\n 'mid_size' =&gt; 3,\n 'type' =&gt; 'list',\n 'prev_text' =&gt; $prev_arrow,\n 'next_text' =&gt; $next_arrow,\n ) );\n}\n</code></pre>\n" }, { "answer_id": 232025, "author": "willrich33", "author_id": 90020, "author_profile": "https://wordpress.stackexchange.com/users/90020", "pm_score": 3, "selected": false, "text": "<p>You say \"However, I know this is not a good way to do this\" in your self answer. One thing I could add answering your question and using your answer is, you can use SQL_CALC_FOUND_ROWS with $wpdb</p>\n\n<pre><code>$result = $wpdb-&gt;get_results( \n \"SELECT SQL_CALC_FOUND_ROWS * FROM `wp_table` WHERE 1 LIMIT 10;\"\n);\n$total_count = $wpdb-&gt;get_var(\n \"SELECT FOUND_ROWS();\"\n);\n</code></pre>\n\n<p>This way you don't have to run the query twice.</p>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190625", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74171/" ]
How do I gee the numbered pagination of custom wpdb result? below code will show one latest post from each authors in the site. I want to show 20 posts per page with a numbered pagination. ``` $postids = $wpdb->get_results( " SELECT a.ID, a.post_title, a.post_author, a.post_date FROM $wpdb->posts a JOIN ( SELECT max(post_date) post_date, post_author FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' GROUP BY post_author ) b ON a.post_author = b.post_author AND a.post_date = b.post_date WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC " ); foreach ( $postids as $postid ) { //setup_postdata( $postid ); echo $postid->ID." :: ".$postid->post_title." :: ".$postid->post_author . "<br />" ; //get_template_part( 'content', 'category' ); } ```
You say "However, I know this is not a good way to do this" in your self answer. One thing I could add answering your question and using your answer is, you can use SQL\_CALC\_FOUND\_ROWS with $wpdb ``` $result = $wpdb->get_results( "SELECT SQL_CALC_FOUND_ROWS * FROM `wp_table` WHERE 1 LIMIT 10;" ); $total_count = $wpdb->get_var( "SELECT FOUND_ROWS();" ); ``` This way you don't have to run the query twice.
190,629
<p>get_page_by_title works fine on plain text title. but when it comes to smart quotes and symbols like <code>#</code> it doesn't work. It fails to find post with the given title.</p> <p>For Example:-</p> <pre><code>get_page_by_title('The #1 Reason to Buy Right Now – THE MONEY!!', OBJECT, 'post'); </code></pre> <p>returns <code>NULL</code>.</p> <p>But there exists a post with this title. If there is a better way to do so, then that would be great.</p>
[ { "answer_id": 190633, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>The '#' character in title is not a problem. Second parameter of the function is a string. Change <code>OBJECT</code> to <code>'OBJECT'</code>. That's all.</p>\n" }, { "answer_id": 325167, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 1, "selected": false, "text": "<p>You may need to html entity decode that title. Similar to the issue found <a href=\"https://wordpress.stackexchange.com/questions/100445/get-page-by-title-not-working-when-used-with-a-variable/116541\">here</a>. Try this:</p>\n\n<pre><code>get_page_by_title(\n html_entity_decode('The #1 Reason to Buy Right Now – THE MONEY!!'), \n OBJECT, \n 'post',\n));\n</code></pre>\n" }, { "answer_id": 352889, "author": "kripto", "author_id": 178597, "author_profile": "https://wordpress.stackexchange.com/users/178597", "pm_score": -1, "selected": false, "text": "<p>In case someone needs it.</p>\n\n<pre><code>$post = get_page_by_title(wp_unslash(sanitize_post_field( 'post_title', 'This is my Title', 0, 'db' ) ), OBJECT, 'post')\n</code></pre>\n" }, { "answer_id": 375396, "author": "Andre de Almeida", "author_id": 180789, "author_profile": "https://wordpress.stackexchange.com/users/180789", "pm_score": 0, "selected": false, "text": "<p>Anyone stumbling on this here is the solution:</p>\n<pre><code>get_page_by_title(esc_html('The #1 Reason to Buy Right Now – THE MONEY!!'), OBJECT, 'post');\n</code></pre>\n<p>Escaping the value encodes the special characters to match the title.</p>\n" } ]
2015/06/05
[ "https://wordpress.stackexchange.com/questions/190629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/36718/" ]
get\_page\_by\_title works fine on plain text title. but when it comes to smart quotes and symbols like `#` it doesn't work. It fails to find post with the given title. For Example:- ``` get_page_by_title('The #1 Reason to Buy Right Now – THE MONEY!!', OBJECT, 'post'); ``` returns `NULL`. But there exists a post with this title. If there is a better way to do so, then that would be great.
You may need to html entity decode that title. Similar to the issue found [here](https://wordpress.stackexchange.com/questions/100445/get-page-by-title-not-working-when-used-with-a-variable/116541). Try this: ``` get_page_by_title( html_entity_decode('The #1 Reason to Buy Right Now – THE MONEY!!'), OBJECT, 'post', )); ```
190,646
<p>I have hierarchy like this: Category1 -Subcategory1 -Subcategory2 --Post1 Category2 -Subcategory1</p> <p>I need to show subcategories name and description when i go to category//// Now i use this code:</p> <pre><code> &lt;?php if (is_category()) { $this_category = get_category($cat); if (get_category_children($this_category-&gt;cat_ID) != "") { echo '&lt;div id="catlist"&gt;&lt;ul&gt;'; $childcategories = get_categories(array( 'orderyby' =&gt; 'name', 'hide_empty' =&gt; false, 'child_of' =&gt; $this_category-&gt;cat_ID )); foreach($childcategories as $category) { echo '&lt;a href="' . get_category_link( $category-&gt;term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category-&gt;name ) . '" ' . '&gt;' . $category-&gt;name.'&lt;/a&gt;'; echo '&lt;p&gt;'.$category-&gt;description.'&lt;/p&gt;'; } echo '&lt;/ul&gt;&lt;/div&gt;'; } } ?&gt; </code></pre> <p>Now i have subcategories list when click on category and blank page if i click on subcategory link but i need to show posts when i click on subcategory list.</p>
[ { "answer_id": 232819, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 1, "selected": false, "text": "<p>Your code checks for child categories and shows them if they exist, but you aren't then going on to process the loop that would ordinarily display the posts in the current category.</p>\n\n<p>You want to extend your code to be of the form:</p>\n\n<pre><code>if ( is_category() ) {\n\n $this_category = get_category($cat);\n\n if ( get_category_children( $this_category-&gt;cat_ID ) != \"\" ) {\n\n // display the list of child categories as you currently do\n\n } else {\n\n /* run the standard loop to show the posts using\n whatever loop code your other templates use\n */\n\n }\n}\n</code></pre>\n" }, { "answer_id": 232822, "author": "Praveen", "author_id": 97802, "author_profile": "https://wordpress.stackexchange.com/users/97802", "pm_score": -1, "selected": false, "text": "<pre><code> &lt;?php if ( have_posts() ) : ?&gt;&lt;!-- .page-header --&gt;\n &lt;div class=\"clearfix enclose\"&gt;\n &lt;?php\n // Start the Loop.\n while ( have_posts() ) : the_post(); ?&gt;\n &lt;div class=\"sub-category-block\"&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title_attribute(); ?&gt;\"&gt;&lt;?php the_post_thumbnail('medium_thumbnail'); ?&gt;\n &lt;p class=\"title\"&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt;\n &lt;/a&gt;\n &lt;/div&gt;\n &lt;?php endwhile; ?&gt; \n &lt;/div&gt;\n &lt;?php else : ?&gt;\n &lt;div class=\"page-header\"&gt;\n &lt;?php $args = array(\n 'posts_per_page' =&gt; 5,\n 'offset' =&gt; 0,\n 'category' =&gt; '',\n 'category_name' =&gt; '',\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC',\n 'include' =&gt; '',\n 'exclude' =&gt; '',\n 'meta_key' =&gt; '',\n 'meta_value' =&gt; '',\n 'post_type' =&gt; 'post',\n 'post_mime_type' =&gt; '',\n 'post_parent' =&gt; '',\n 'author' =&gt; '',\n 'post_status' =&gt; 'publish',\n 'suppress_filters' =&gt; true \n );?&gt;\n &lt;?php query_posts( $args ); ?&gt;\n &lt;?php while ( have_posts() ) : the_post(); ?&gt;\n &lt;?php endwhile; wp_reset_query(); ?&gt;\n &lt;/div&gt;&lt;!-- .page-header --&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n\n<p>create category template file for e.g category-abc.php and insert the above code where you will get all subcategory of the repesctive parent category and when you click the sub-category the post of the sub category will be displayed</p>\n" }, { "answer_id": 279164, "author": "tayyab islam", "author_id": 127291, "author_profile": "https://wordpress.stackexchange.com/users/127291", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;div id=\"content\" role=\"main\"&gt;\n &lt;?php if (is_category()) {\n $this_category = get_category($cat);\n if (get_category_children($this_category-&gt;cat_ID) != \"\") {\n echo '&lt;div id=\"catlist\"&gt;&lt;ul&gt;';\n $childcategories = get_categories(array(\n 'orderyby' =&gt; 'name',\n 'hide_empty' =&gt; false,\n 'child_of' =&gt; $this_category-&gt;cat_ID\n ));\n foreach($childcategories as $category) {\n echo '&lt;a href=\"' . get_category_link( $category-&gt;term_id ) . '\" title=\"' . sprintf( __( \"View all posts in %s\" ), $category-&gt;name ) . '\" ' . '&gt;' . $category-&gt;name.'&lt;/a&gt;';\n echo '&lt;p&gt;'.$category-&gt;description.'&lt;/p&gt;';\n } echo '&lt;/ul&gt;&lt;/div&gt;';\n }\n else{ \n get_template_part('loop-header'); \n if (have_posts()) :\n get_template_part('loop-actions');\n get_template_part('loop-content');\n get_template_part('loop-nav');\n else :\n get_template_part('loop-error');\n endif; }}?&gt;\n&lt;?php \n ?&gt;\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 292368, "author": "Tanvir Ahmed Shaon", "author_id": 104650, "author_profile": "https://wordpress.stackexchange.com/users/104650", "pm_score": 0, "selected": false, "text": "<pre><code>if (is_category()){\n$category = get_queried_object();\n$subcategories = get_category_children( $category-&gt;term_id );\n// var_dump($subcategories);\nif ( $subcategories != \"\" ) {\n echo '&lt;div id=\"catlist\"&gt;&lt;ul&gt;';\n $childcategories = get_categories(array(\n 'orderyby' =&gt; 'name',\n 'hide_empty' =&gt; false,\n 'child_of' =&gt; $category-&gt;term_id,\n ));\n foreach( $childcategories as $single ) {\n echo '&lt;a href=\"' . get_category_link( $single-&gt;term_id ) . '\" title=\"' . sprintf( __( \"View all posts in %s\" ), $single-&gt;name ) . '\" ' . '&gt;' . $single-&gt;name.'&lt;/a&gt;';\n echo '&lt;p&gt;'.$single-&gt;description.'&lt;/p&gt;';\n }\n echo '&lt;/ul&gt;&lt;/div&gt;';\n} else {\n// your loop.\n}\n</code></pre>\n" } ]
2015/06/06
[ "https://wordpress.stackexchange.com/questions/190646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74254/" ]
I have hierarchy like this: Category1 -Subcategory1 -Subcategory2 --Post1 Category2 -Subcategory1 I need to show subcategories name and description when i go to category//// Now i use this code: ``` <?php if (is_category()) { $this_category = get_category($cat); if (get_category_children($this_category->cat_ID) != "") { echo '<div id="catlist"><ul>'; $childcategories = get_categories(array( 'orderyby' => 'name', 'hide_empty' => false, 'child_of' => $this_category->cat_ID )); foreach($childcategories as $category) { echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; echo '<p>'.$category->description.'</p>'; } echo '</ul></div>'; } } ?> ``` Now i have subcategories list when click on category and blank page if i click on subcategory link but i need to show posts when i click on subcategory list.
Your code checks for child categories and shows them if they exist, but you aren't then going on to process the loop that would ordinarily display the posts in the current category. You want to extend your code to be of the form: ``` if ( is_category() ) { $this_category = get_category($cat); if ( get_category_children( $this_category->cat_ID ) != "" ) { // display the list of child categories as you currently do } else { /* run the standard loop to show the posts using whatever loop code your other templates use */ } } ```
190,670
<p>I am new to wordpress and this is the first html website I converted. After I converted my page to a wordpress theme, I notice that there is a white space on all sides of my page. This only happened after converting because my original html page doesn't have white spaces. I have *{padding:0; margin:0;} on my css but it doesn't seem to work on wordpress. </p> <p>header.php</p> <pre><code> &lt;?php /** * The template for displaying the header * * * @package WordPress * @subpackage Twenty_Fifteen * @since Twenty Fifteen 1.0 */ ?&gt;&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;My Theme&lt;/title&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;link rel="profile" href="http://gmpg.org/xfn/11"&gt; &lt;link rel="pingback" href="&lt;?php bloginfo( 'pingback_url' ); ?&gt;"&gt; &lt;link rel="stylesheet" href="&lt;?php bloginfo('stylesheet_url'); ?&gt;" type="text/css" media="screen" /&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;?php if(is_home()): $awesome_classes = array('awesome-class', 'my-class'); else: $awesome_classes = array('no-awesome-class'); endif; ?&gt; &lt;body &lt;?php body_class($awesome_classes); ?&gt;&gt; &lt;div class="container"&gt; &lt;h2 class="logo"&gt;MY WEBSITE&lt;/h2&gt; &lt;?php wp_nav_menu(array('theme_location'=&gt;'primary')); ?&gt; </code></pre> <p>footer.php</p> <pre><code>&lt;/div&gt; &lt;footer class="thefooter"&gt; &lt;p&gt;Copyright 2015 My Website - All Rights Reserved&lt;/p&gt; &lt;?php //wp_nav_menu(array('theme_location'=&gt;'secondary')); ?&gt; &lt;/footer&gt; &lt;?php wp_footer(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>style.css</p> <pre><code>/* Theme Name: My Theme Theme URL: wordpress.com/index.php Author: Rendell Lasola Description: This is an awesome theme License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: black, white, responsive, one-column, two-columns, featured-images, custom-menu, custom-header, post-formats */ *{ padding: 0; margin: 0; font-family: Arial; list-style-type: none; } .container{ width: 100%; max-width: 1020px; margin: auto; } h1,.widget-title{ display: none; } h2.logo{ float: left; font-family: Azedo; font-size: 2em; padding: 10px; } #menu-navigation{ float: right; padding: 10px; } #menu-navigation li{ display: inline-block; font-weight: bold; padding: 15px; } #menu-navigation li a{ text-decoration: none; font-family: Arial; font-weight: bold; color: #2C3E50; -webkit-transition: 0.4s all; -moz-transition: 0.4s all; -ms-transition: 0.4s all; -o-transition: 0.4s all; transition: 0.3s all; } #menu-navigation li a:hover{ color: #1E8BC3; } .container .jumbotron{ background: url('images/Jumbotron-wallpaper.png'); width: 1020px; max-width: 100%; height: 431px; clear: both; } .container .content{ text-align: center; font-family: Arial; color: #22313f; } .container .content h2{ padding: 20px; } .container .content article{ width: 284px; margin: 0 auto; display: inline-block; vertical-align: top; padding: 10px } .container .content article aside h4{ padding: 10px; font-size: 1.5em; } .container .content article aside p{ width: 100%; text-align: justify; padding-top: 10px; font-weight: bold; } .thefooter{ background: #22313f; min-height: 75px; margin-top: 75px; text-align: center; } .thefooter p{ padding: 28px; font-family: Arial; font-weight: bold; color: #FFF; } @media(min-width: 240px) and (max-width: 768px){ h2.logo{ float: none; text-align: center; } #menu-navigation{ float: none; text-align: center; } #menu-navigation li{ display: block; } .container .jumbotron{ background-position: 50%; } } </code></pre> <p><img src="https://i.stack.imgur.com/Y2J0Y.jpg" alt="enter image description here"></p>
[ { "answer_id": 190682, "author": "Rahul S", "author_id": 74210, "author_profile": "https://wordpress.stackexchange.com/users/74210", "pm_score": -1, "selected": false, "text": "<p>Can you please give this in css file to avoid spaces</p>\n\n<p>html, body {\n margin: 0;\n padding: 0;\n }</p>\n\n<p>Also yes the container is given max-width of 1020px.</p>\n" }, { "answer_id": 190683, "author": "Ace", "author_id": 51592, "author_profile": "https://wordpress.stackexchange.com/users/51592", "pm_score": 0, "selected": false, "text": "<p>Your css file clearly shows a max-width of 1020px it appears as if your zoomed out or just on a large screen from your screenshot. If your window is bigger then 1020px then obviously there would be white space on either side.</p>\n\n<pre><code>.container{\n width: 100%;\n max-width: 1020px;\n margin: auto;\n}\n</code></pre>\n\n<p>Also important to note this is not a wordpress issue</p>\n" }, { "answer_id": 190736, "author": "rendell", "author_id": 74265, "author_profile": "https://wordpress.stackexchange.com/users/74265", "pm_score": 1, "selected": true, "text": "<p>So I resolved it by adding body{padding: 0!important; margin: 0!important}. Didn't know that something was overriding my *{padding: 0; margin: 0;}. Also, forgot to mention that the footer does not belong inside the wrapper which has a max-width of 1020px; because my psd file had the same width.</p>\n" } ]
2015/06/06
[ "https://wordpress.stackexchange.com/questions/190670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74265/" ]
I am new to wordpress and this is the first html website I converted. After I converted my page to a wordpress theme, I notice that there is a white space on all sides of my page. This only happened after converting because my original html page doesn't have white spaces. I have \*{padding:0; margin:0;} on my css but it doesn't seem to work on wordpress. header.php ``` <?php /** * The template for displaying the header * * * @package WordPress * @subpackage Twenty_Fifteen * @since Twenty Fifteen 1.0 */ ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Theme</title> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width"> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> <?php wp_head(); ?> </head> <?php if(is_home()): $awesome_classes = array('awesome-class', 'my-class'); else: $awesome_classes = array('no-awesome-class'); endif; ?> <body <?php body_class($awesome_classes); ?>> <div class="container"> <h2 class="logo">MY WEBSITE</h2> <?php wp_nav_menu(array('theme_location'=>'primary')); ?> ``` footer.php ``` </div> <footer class="thefooter"> <p>Copyright 2015 My Website - All Rights Reserved</p> <?php //wp_nav_menu(array('theme_location'=>'secondary')); ?> </footer> <?php wp_footer(); ?> </body> </html> ``` style.css ``` /* Theme Name: My Theme Theme URL: wordpress.com/index.php Author: Rendell Lasola Description: This is an awesome theme License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: black, white, responsive, one-column, two-columns, featured-images, custom-menu, custom-header, post-formats */ *{ padding: 0; margin: 0; font-family: Arial; list-style-type: none; } .container{ width: 100%; max-width: 1020px; margin: auto; } h1,.widget-title{ display: none; } h2.logo{ float: left; font-family: Azedo; font-size: 2em; padding: 10px; } #menu-navigation{ float: right; padding: 10px; } #menu-navigation li{ display: inline-block; font-weight: bold; padding: 15px; } #menu-navigation li a{ text-decoration: none; font-family: Arial; font-weight: bold; color: #2C3E50; -webkit-transition: 0.4s all; -moz-transition: 0.4s all; -ms-transition: 0.4s all; -o-transition: 0.4s all; transition: 0.3s all; } #menu-navigation li a:hover{ color: #1E8BC3; } .container .jumbotron{ background: url('images/Jumbotron-wallpaper.png'); width: 1020px; max-width: 100%; height: 431px; clear: both; } .container .content{ text-align: center; font-family: Arial; color: #22313f; } .container .content h2{ padding: 20px; } .container .content article{ width: 284px; margin: 0 auto; display: inline-block; vertical-align: top; padding: 10px } .container .content article aside h4{ padding: 10px; font-size: 1.5em; } .container .content article aside p{ width: 100%; text-align: justify; padding-top: 10px; font-weight: bold; } .thefooter{ background: #22313f; min-height: 75px; margin-top: 75px; text-align: center; } .thefooter p{ padding: 28px; font-family: Arial; font-weight: bold; color: #FFF; } @media(min-width: 240px) and (max-width: 768px){ h2.logo{ float: none; text-align: center; } #menu-navigation{ float: none; text-align: center; } #menu-navigation li{ display: block; } .container .jumbotron{ background-position: 50%; } } ``` ![enter image description here](https://i.stack.imgur.com/Y2J0Y.jpg)
So I resolved it by adding body{padding: 0!important; margin: 0!important}. Didn't know that something was overriding my \*{padding: 0; margin: 0;}. Also, forgot to mention that the footer does not belong inside the wrapper which has a max-width of 1020px; because my psd file had the same width.
190,678
<p>I'm trying to change the look of my website but while doing that, facing some problems.</p> <p>Now, different classes and id's in style.css apply to all pages on my theme.</p> <p>I want to overwrite those styles elements (only 2 or 3) on my homepage.</p> <p>Now when I'm adding style in my index.php file, they are not being applied.</p> <p>I've already tried marking them <code>!important</code></p> <p>Code snippets: I've added this code in my index.php file before the <code>&lt;?php</code> code starts</p> <pre><code>&lt;style type="text/css"&gt; #main { margin-left: 0 !important; } .container { width: 95% !important; } &lt;/style&gt; </code></pre> <p>But they are still not affecting the look of my homepage.</p> <p>I've confirmed that the class and ids I'm using are perfect and are present in style.css file?</p> <p>So, can you please guide me how to overwrite these element stylings only on my homepage?</p> <p>OR</p> <p>If I'm doing something wrong in the above process?</p>
[ { "answer_id": 190682, "author": "Rahul S", "author_id": 74210, "author_profile": "https://wordpress.stackexchange.com/users/74210", "pm_score": -1, "selected": false, "text": "<p>Can you please give this in css file to avoid spaces</p>\n\n<p>html, body {\n margin: 0;\n padding: 0;\n }</p>\n\n<p>Also yes the container is given max-width of 1020px.</p>\n" }, { "answer_id": 190683, "author": "Ace", "author_id": 51592, "author_profile": "https://wordpress.stackexchange.com/users/51592", "pm_score": 0, "selected": false, "text": "<p>Your css file clearly shows a max-width of 1020px it appears as if your zoomed out or just on a large screen from your screenshot. If your window is bigger then 1020px then obviously there would be white space on either side.</p>\n\n<pre><code>.container{\n width: 100%;\n max-width: 1020px;\n margin: auto;\n}\n</code></pre>\n\n<p>Also important to note this is not a wordpress issue</p>\n" }, { "answer_id": 190736, "author": "rendell", "author_id": 74265, "author_profile": "https://wordpress.stackexchange.com/users/74265", "pm_score": 1, "selected": true, "text": "<p>So I resolved it by adding body{padding: 0!important; margin: 0!important}. Didn't know that something was overriding my *{padding: 0; margin: 0;}. Also, forgot to mention that the footer does not belong inside the wrapper which has a max-width of 1020px; because my psd file had the same width.</p>\n" } ]
2015/06/06
[ "https://wordpress.stackexchange.com/questions/190678", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71530/" ]
I'm trying to change the look of my website but while doing that, facing some problems. Now, different classes and id's in style.css apply to all pages on my theme. I want to overwrite those styles elements (only 2 or 3) on my homepage. Now when I'm adding style in my index.php file, they are not being applied. I've already tried marking them `!important` Code snippets: I've added this code in my index.php file before the `<?php` code starts ``` <style type="text/css"> #main { margin-left: 0 !important; } .container { width: 95% !important; } </style> ``` But they are still not affecting the look of my homepage. I've confirmed that the class and ids I'm using are perfect and are present in style.css file? So, can you please guide me how to overwrite these element stylings only on my homepage? OR If I'm doing something wrong in the above process?
So I resolved it by adding body{padding: 0!important; margin: 0!important}. Didn't know that something was overriding my \*{padding: 0; margin: 0;}. Also, forgot to mention that the footer does not belong inside the wrapper which has a max-width of 1020px; because my psd file had the same width.
190,691
<p>i have this html mark-up to sort some data</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-xs-2"&gt; &lt;img src="images/member-schools/ms1.jpg" class="img-responsive"&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;h4&gt;American International School - East&lt;/h4&gt; &lt;/div&gt; &lt;div class="col-xs-2"&gt; &lt;img src="images/member-schools/ms2.jpg" class="img-responsive"&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;h4&gt;Dover American International School&lt;/h4&gt; &lt;/div&gt; </code></pre> <p></p> <p>and i am pulling out the data from repeatable group metabox i use from <a href="https://github.com/WebDevStudios/CMB2/wiki/Field-Types#group" rel="nofollow">CMB2</a></p> <p>this is the code for the registered metabox</p> <pre><code>function schools() { // Start with an underscore to hide fields from custom fields list $prefix = 'schools_'; /** * Repeatable Field Groups */ $schools= new_cmb2_box( array( 'id' =&gt; $prefix . 'metabox', 'title' =&gt; __( 'schools', 'cmb2' ), 'object_types' =&gt; array( 'page', ), 'show_on' =&gt; array( 'key' =&gt; 'id', 'value' =&gt; 6 ), 'closed' =&gt; true, ) ); $group_field_id = $schools-&gt;add_field( array( 'id' =&gt; $prefix . 'field', 'type' =&gt; 'group', 'options' =&gt; array( 'group_title' =&gt; __( 'Slide {#}', 'cmb2' ), // {#} gets replaced by row number 'add_button' =&gt; __( 'Add Another Slide', 'cmb2' ), 'remove_button' =&gt; __( 'Remove Slide', 'cmb2' ), 'sortable' =&gt; true, // beta ), ) ); $schools-&gt;add_group_field( $group_field_id, array( 'name' =&gt; __( 'Photo', 'cmb2' ), 'id' =&gt; 'photo', 'type' =&gt; 'file', ) ); $schools-&gt;add_group_field( $group_field_id, array( 'name' =&gt; __( 'Name', 'cmb2' ), 'id' =&gt; 'name', 'type' =&gt; 'text', ) );} </code></pre> <p>i pull the data out through this code </p> <pre><code>$schools = get_post_meta( get_the_ID(), 'schools_field', true ); </code></pre> <p>where $schools is an array that contain an image and title for each entry which i can loop through to pull out the values. my question is how i can add <code>&lt;div class="row"&gt;</code> every two items from that array , because i need a row for each two entries</p> <p>EDIT: var_dump result </p> <pre><code>array(3) { [0] =&gt; array(3) { ["photo_id"] =&gt; string(2) "89" ["photo"] =&gt; string(56) "http://localhost/NCSR/wp-content/uploads/2015/06/ms3.jpg" ["name"] =&gt; string(8) "School 1" } [1] =&gt; array(3) { ["photo_id"] =&gt; string(2) "88" ["photo"] =&gt; string(56) "http://localhost/NCSR/wp-content/uploads/2015/06/ms2.jpg" ["name"] =&gt; string(8) "school 2" } [2] =&gt; array(3) { ["photo_id"] =&gt; string(2) "87" ["photo"] =&gt; string(56) "http://localhost/NCSR/wp-content/uploads/2015/06/ms1.jpg" ["name"] =&gt; string(8) "school 3" } } </code></pre>
[ { "answer_id": 190686, "author": "Yadi", "author_id": 74279, "author_profile": "https://wordpress.stackexchange.com/users/74279", "pm_score": 1, "selected": false, "text": "<p>try \"update URL Plugin\" It updates all urls and content links in your website;\n<a href=\"http://www.velvetblues.com/web-development-blog/wordpress-plugin-update-urls/\" rel=\"nofollow\">http://www.velvetblues.com/web-development-blog/wordpress-plugin-update-urls/</a></p>\n" }, { "answer_id": 190688, "author": "Parsa", "author_id": 74284, "author_profile": "https://wordpress.stackexchange.com/users/74284", "pm_score": 2, "selected": false, "text": "<p><strong>Method 1:</strong>\nYou can export your data from \"Tools > Export\" and for ensure export from database and rename old blog folder, then install WordPress in root &amp; active WordPress Network. set url structure for new blog to sub-folder. now create new blog with \"blog\" name, login to blog &amp; import old blog data.\nYour old post in blog and new post in main WordPress. copy old upload folder to new blog upload folder. this method is slightly involved but site run with one WordPress installation. </p>\n\n<p><strong>Method 2:</strong>\nMove old blog to root (<em>for this method first set blog and WordPress address to new address in settings > general</em>) and create new <strong><em>post type</em></strong> with \"blog\" name or slug, now install <a href=\"https://wordpress.org/plugins/post-type-switcher/\" rel=\"nofollow\">Post Type Switcher</a> plugin and switch old post to new post type. set post type permalink structure to old structure.</p>\n\n<p><strong>Method 3:</strong>\nsimple method you can install new WordPress in root and linked to old page for <em>/contact</em>, <em>/about</em> , etc.</p>\n" }, { "answer_id": 190718, "author": "nbjahan", "author_id": 74299, "author_profile": "https://wordpress.stackexchange.com/users/74299", "pm_score": 1, "selected": false, "text": "<p>You need to redirect those urls with htaccess rules. Check here for example: <a href=\"https://stackoverflow.com/questions/3292506/help-with-htaccess-and-two-wordpress-instances\">https://stackoverflow.com/questions/3292506/help-with-htaccess-and-two-wordpress-instances</a></p>\n" } ]
2015/06/06
[ "https://wordpress.stackexchange.com/questions/190691", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62794/" ]
i have this html mark-up to sort some data ``` <div class="row"> <div class="col-xs-2"> <img src="images/member-schools/ms1.jpg" class="img-responsive"> </div> <div class="col-xs-4"> <h4>American International School - East</h4> </div> <div class="col-xs-2"> <img src="images/member-schools/ms2.jpg" class="img-responsive"> </div> <div class="col-xs-4"> <h4>Dover American International School</h4> </div> ``` and i am pulling out the data from repeatable group metabox i use from [CMB2](https://github.com/WebDevStudios/CMB2/wiki/Field-Types#group) this is the code for the registered metabox ``` function schools() { // Start with an underscore to hide fields from custom fields list $prefix = 'schools_'; /** * Repeatable Field Groups */ $schools= new_cmb2_box( array( 'id' => $prefix . 'metabox', 'title' => __( 'schools', 'cmb2' ), 'object_types' => array( 'page', ), 'show_on' => array( 'key' => 'id', 'value' => 6 ), 'closed' => true, ) ); $group_field_id = $schools->add_field( array( 'id' => $prefix . 'field', 'type' => 'group', 'options' => array( 'group_title' => __( 'Slide {#}', 'cmb2' ), // {#} gets replaced by row number 'add_button' => __( 'Add Another Slide', 'cmb2' ), 'remove_button' => __( 'Remove Slide', 'cmb2' ), 'sortable' => true, // beta ), ) ); $schools->add_group_field( $group_field_id, array( 'name' => __( 'Photo', 'cmb2' ), 'id' => 'photo', 'type' => 'file', ) ); $schools->add_group_field( $group_field_id, array( 'name' => __( 'Name', 'cmb2' ), 'id' => 'name', 'type' => 'text', ) );} ``` i pull the data out through this code ``` $schools = get_post_meta( get_the_ID(), 'schools_field', true ); ``` where $schools is an array that contain an image and title for each entry which i can loop through to pull out the values. my question is how i can add `<div class="row">` every two items from that array , because i need a row for each two entries EDIT: var\_dump result ``` array(3) { [0] => array(3) { ["photo_id"] => string(2) "89" ["photo"] => string(56) "http://localhost/NCSR/wp-content/uploads/2015/06/ms3.jpg" ["name"] => string(8) "School 1" } [1] => array(3) { ["photo_id"] => string(2) "88" ["photo"] => string(56) "http://localhost/NCSR/wp-content/uploads/2015/06/ms2.jpg" ["name"] => string(8) "school 2" } [2] => array(3) { ["photo_id"] => string(2) "87" ["photo"] => string(56) "http://localhost/NCSR/wp-content/uploads/2015/06/ms1.jpg" ["name"] => string(8) "school 3" } } ```
**Method 1:** You can export your data from "Tools > Export" and for ensure export from database and rename old blog folder, then install WordPress in root & active WordPress Network. set url structure for new blog to sub-folder. now create new blog with "blog" name, login to blog & import old blog data. Your old post in blog and new post in main WordPress. copy old upload folder to new blog upload folder. this method is slightly involved but site run with one WordPress installation. **Method 2:** Move old blog to root (*for this method first set blog and WordPress address to new address in settings > general*) and create new ***post type*** with "blog" name or slug, now install [Post Type Switcher](https://wordpress.org/plugins/post-type-switcher/) plugin and switch old post to new post type. set post type permalink structure to old structure. **Method 3:** simple method you can install new WordPress in root and linked to old page for */contact*, */about* , etc.
190,701
<p>I have created a custom true/false field with the default value of true. I've set different posts to different values. However, get_field() always returns false:</p> <pre><code>&lt;?php if( have_posts() ): while( have_posts() ): the_post(); ?&gt; &lt;?php global var_dump(get_field('display_featured_image'));?&gt; &lt;?php endwhile; endif ?&gt; </code></pre> <p>The displayed output is: (bool)false</p> <p>I've checked and double checked the field name. Why would it return false if the value is set to true? </p>
[ { "answer_id": 190702, "author": "Hybrid Web Dev", "author_id": 36506, "author_profile": "https://wordpress.stackexchange.com/users/36506", "pm_score": 3, "selected": false, "text": "<p>You need to pass in the ID of the post you're trying to get the field from: Eg </p>\n\n<pre><code>get_field('display_featured_image', $post_id). \n</code></pre>\n\n<p>In a loop you could do </p>\n\n<pre><code>get_field('display_featured_image', get_the_id());\n</code></pre>\n\n<p>ACF Stores field data in wp's meta_fields, so you could even use WP's built in meta handler to pull the data yourself Eg: </p>\n\n<pre><code>get_post_meta( $post_id, 'acf_field_name', true); // Use true for almost every case, as WP will return an array otherwise. \n</code></pre>\n" }, { "answer_id": 207859, "author": "doublesharp", "author_id": 20880, "author_profile": "https://wordpress.stackexchange.com/users/20880", "pm_score": -1, "selected": false, "text": "<p>You have a few options. The easiest would be to use <code>get_field( $field_key )</code> (use the ACF field ID rather than the meta_key). This will choose the correct field regardless of location rules which will let it access the default value.</p>\n\n<p>If you must use the meta key, you can mostly do so with filters. Not sure how efficient it is (could be mitigated by using acf-json caching). This also assumes that your fields keys are unique (otherwise you have to filter based on the location rules, which may or may not be available).</p>\n\n<pre><code>add_filter( 'acf/load_value', function( $value, $post_id, $field ){\n // get your field groups\n $groups = acf_get_field_groups();\n if ( !empty( $groups ) ){\n // loop over each group\n foreach ($groups as $group) {\n // load the fields for this group key\n $fields = acf_get_fields( $group['key'] );\n if ( !empty( $fields ) ){\n // loop over the returned fields\n foreach ( $fields as $this_field ){\n // if the name is a match, set the default value\n if ( $this_field['name'] == $field['name'] ){\n return $this_field['default_value'];\n }\n }\n }\n }\n }\n return $value;\n}\n</code></pre>\n" } ]
2015/06/06
[ "https://wordpress.stackexchange.com/questions/190701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74293/" ]
I have created a custom true/false field with the default value of true. I've set different posts to different values. However, get\_field() always returns false: ``` <?php if( have_posts() ): while( have_posts() ): the_post(); ?> <?php global var_dump(get_field('display_featured_image'));?> <?php endwhile; endif ?> ``` The displayed output is: (bool)false I've checked and double checked the field name. Why would it return false if the value is set to true?
You need to pass in the ID of the post you're trying to get the field from: Eg ``` get_field('display_featured_image', $post_id). ``` In a loop you could do ``` get_field('display_featured_image', get_the_id()); ``` ACF Stores field data in wp's meta\_fields, so you could even use WP's built in meta handler to pull the data yourself Eg: ``` get_post_meta( $post_id, 'acf_field_name', true); // Use true for almost every case, as WP will return an array otherwise. ```
190,757
<p>I'm moving a site from an Apache server to a nginx server. A lot of the pages have a .php extension at the end of the permalink. Trying to view those pages results in a nginx 404 Not Found. However those pages worked fine on Apache. Here is the server block config for the site:</p> <pre><code># Vhost Config: example.com server { root /var/www/vhosts/sites/www.example.com/web; index index.php index.html index.htm; server_name example.com www.example.com; port_in_redirect off; location /Denied { return 403; } location / { try_files $uri $uri/ /index.php?$args; } location ~* ^(/sitemap).*(\.xml)$ { rewrite ^ /index.php; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location = /404.html { root /usr/share/nginx/html; } location ~ ^/.*\.php$ { try_files $uri = 404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } location ~* \.(js|css|png|jpg|jpeg|gif|ico|xml)(\?ver=[0-9.]+)?$ { expires 1w; log_not_found off; } location ~ /\. { deny all; } location = /ping.html { access_log off; } } </code></pre> <p>I commented out "#try_files $uri = 404;" to see if that would work however that resulted in a "File not found." message.</p> <p>So the main problem is trying to get WordPress and nginx to see the permalink with a .php extension before it tries to run a .php file which it sees is not a real file.</p> <p>Is this possible?</p>
[ { "answer_id": 190769, "author": "Dave Lozier", "author_id": 74314, "author_profile": "https://wordpress.stackexchange.com/users/74314", "pm_score": 0, "selected": false, "text": "<p>This sounds like a path info issue.</p>\n\n<p><a href=\"http://wiki.nginx.org/PHPFcgiExample\" rel=\"nofollow\">http://wiki.nginx.org/PHPFcgiExample</a></p>\n\n<pre><code> location ~ [^/]\\.php(/|$) {\n fastcgi_split_path_info ^(.+?\\.php)(/.*)$;\n if (!-f $document_root$fastcgi_script_name) {\n return 404;\n }\n\n fastcgi_pass 127.0.0.1:9000;\n fastcgi_index index.php;\n include fastcgi_params;\n }\n</code></pre>\n\n<p>This may get you going in the right direction, I hope.</p>\n" }, { "answer_id": 190891, "author": "jpcadillac", "author_id": 74308, "author_profile": "https://wordpress.stackexchange.com/users/74308", "pm_score": 1, "selected": false, "text": "<p>I ended up changing</p>\n\n<pre><code>location ~ ^/.*\\.php$ {\n try_files $uri = 404;\n fastcgi_pass unix:/var/run/php5-fpm.sock;\n fastcgi_index index.php;\n include fastcgi_params;\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>location ~ ^/.*\\.php$ {\n try_files $uri $uri/ /index.php?$args;\n fastcgi_pass unix:/var/run/php5-fpm.sock;\n fastcgi_index index.php;\n include fastcgi_params;\n}\n</code></pre>\n\n<p>It now works, but I feel that is a security issue now.</p>\n" } ]
2015/06/07
[ "https://wordpress.stackexchange.com/questions/190757", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74308/" ]
I'm moving a site from an Apache server to a nginx server. A lot of the pages have a .php extension at the end of the permalink. Trying to view those pages results in a nginx 404 Not Found. However those pages worked fine on Apache. Here is the server block config for the site: ``` # Vhost Config: example.com server { root /var/www/vhosts/sites/www.example.com/web; index index.php index.html index.htm; server_name example.com www.example.com; port_in_redirect off; location /Denied { return 403; } location / { try_files $uri $uri/ /index.php?$args; } location ~* ^(/sitemap).*(\.xml)$ { rewrite ^ /index.php; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location = /404.html { root /usr/share/nginx/html; } location ~ ^/.*\.php$ { try_files $uri = 404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } location ~* \.(js|css|png|jpg|jpeg|gif|ico|xml)(\?ver=[0-9.]+)?$ { expires 1w; log_not_found off; } location ~ /\. { deny all; } location = /ping.html { access_log off; } } ``` I commented out "#try\_files $uri = 404;" to see if that would work however that resulted in a "File not found." message. So the main problem is trying to get WordPress and nginx to see the permalink with a .php extension before it tries to run a .php file which it sees is not a real file. Is this possible?
I ended up changing ``` location ~ ^/.*\.php$ { try_files $uri = 404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } ``` to ``` location ~ ^/.*\.php$ { try_files $uri $uri/ /index.php?$args; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } ``` It now works, but I feel that is a security issue now.
190,774
<p>I wanted to ask if ths is the best practice for calling an image into a parent theme file by using bloginfo('template_directory')?</p> <pre><code>&lt;img src="&lt;?php bloginfo('template_directory'); ?&gt;/img/logo.jpg" /&gt; </code></pre> <p>or should one use:</p> <pre><code>&lt;img src="&lt;?php echo get_template_directory(); ?&gt;/img/logo.jpg" /&gt; </code></pre>
[ { "answer_id": 190769, "author": "Dave Lozier", "author_id": 74314, "author_profile": "https://wordpress.stackexchange.com/users/74314", "pm_score": 0, "selected": false, "text": "<p>This sounds like a path info issue.</p>\n\n<p><a href=\"http://wiki.nginx.org/PHPFcgiExample\" rel=\"nofollow\">http://wiki.nginx.org/PHPFcgiExample</a></p>\n\n<pre><code> location ~ [^/]\\.php(/|$) {\n fastcgi_split_path_info ^(.+?\\.php)(/.*)$;\n if (!-f $document_root$fastcgi_script_name) {\n return 404;\n }\n\n fastcgi_pass 127.0.0.1:9000;\n fastcgi_index index.php;\n include fastcgi_params;\n }\n</code></pre>\n\n<p>This may get you going in the right direction, I hope.</p>\n" }, { "answer_id": 190891, "author": "jpcadillac", "author_id": 74308, "author_profile": "https://wordpress.stackexchange.com/users/74308", "pm_score": 1, "selected": false, "text": "<p>I ended up changing</p>\n\n<pre><code>location ~ ^/.*\\.php$ {\n try_files $uri = 404;\n fastcgi_pass unix:/var/run/php5-fpm.sock;\n fastcgi_index index.php;\n include fastcgi_params;\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>location ~ ^/.*\\.php$ {\n try_files $uri $uri/ /index.php?$args;\n fastcgi_pass unix:/var/run/php5-fpm.sock;\n fastcgi_index index.php;\n include fastcgi_params;\n}\n</code></pre>\n\n<p>It now works, but I feel that is a security issue now.</p>\n" } ]
2015/06/07
[ "https://wordpress.stackexchange.com/questions/190774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68130/" ]
I wanted to ask if ths is the best practice for calling an image into a parent theme file by using bloginfo('template\_directory')? ``` <img src="<?php bloginfo('template_directory'); ?>/img/logo.jpg" /> ``` or should one use: ``` <img src="<?php echo get_template_directory(); ?>/img/logo.jpg" /> ```
I ended up changing ``` location ~ ^/.*\.php$ { try_files $uri = 404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } ``` to ``` location ~ ^/.*\.php$ { try_files $uri $uri/ /index.php?$args; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } ``` It now works, but I feel that is a security issue now.
190,809
<p>I've looked at previous examples of this problem but I can't find a solution for what is causing this notice based on what I've seen from other people. This appears at the top of the screen when I am adding a new post.</p> <p>1145 is:</p> <pre><code>$post = get_post( $args[0] ); </code></pre> <p>I'm not getting any other kind of error so I'm not sure where in my code this is causing the problem.</p> <p><strong>Any help on this?</strong></p> <p>This is the code:</p> <pre><code>//show metabox in post editing page add_action('add_meta_boxes', 'kk_add_metabox' ); //save metabox data add_action('save_post', 'kk_save_metabox' ); //register widgets add_action('widgets_init', 'kk_widget_init'); function kk_add_metabox() { add_meta_box('kk_youtube', 'YouTube Video Link','kk_youtube_handler', 'post'); } /** * metabox handler */ function kk_youtube_handler($post) { $youtube_link = esc_attr( get_post_meta( $post-&gt;ID, 'kk_youtube', true ) ); echo '&lt;label for="kk_youtube"&gt;YouTube Video Link&lt;/label&gt;&lt;input type="text" id="kk_youtube" name="kk_youtube" value="' . $youtube_link . '" /&gt;'; } /** * save metadata */ function kk_save_metabox($post_id) { if( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return; } //check if user can edit post if( !current_user_can( 'edit_post' ) ) { return; } if( isset($_POST['kk_youtube'] )) { update_post_meta($post_id, 'kk_youtube', esc_url($_POST['kk_youtube'])); } } /** * register widget */ function kk_widget_init() { register_widget('KK_Widget'); } /** * Class KK_Widget widget class */ class KK_Widget extends WP_Widget { function __construct() { $widget_options = array( 'classname' =&gt; 'kk_class', // For CSS class name 'description' =&gt; 'Show a YouTube video from post metadata' ); $this-&gt;WP_Widget('kk_id', 'YouTube Video', $widget_options); } /** * Show widget form in Appearance/Widgets */ function form($instance) { $defaults = array( 'title' =&gt; 'YouTube Video' ); $instance = wp_parse_args((array)$instance, $defaults); var_dump($instance); $title = esc_attr($instance['title']); echo '&lt;p&gt;Title &lt;input type="text" class="widefat" name="' . $this-&gt;get_field_name('title') . '" value="' . $title . '" /&gt;&lt;/p&gt;'; } function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); return $instance; } /** * Show widget in post/page */ function widget($args, $instance) { global $before_widget; global $after_widget; global $before_title; global $after_title; extract( $args ); $title = apply_filters('widget_title', $instance['title']); //show only if single post if(is_single()) { echo $before_widget; echo $before_title.$title.$after_title; //get post metadata $kk_youtube = esc_url(get_post_meta(get_the_ID(), 'kk_youtube', true)); //print widget content echo '&lt;iframe width="200" height="200" frameborder="0" allowfullscreen src="http://www.youtube.com/embed/' . $this-&gt;get_yt_videoid($kk_youtube) . '"&gt;&lt;/iframe&gt;'; echo $after_widget; } } function get_yt_videoid($url) { parse_str(parse_url($url, PHP_URL_QUERY), $my_array_of_vars); return $my_array_of_vars['v']; } } </code></pre>
[ { "answer_id": 190812, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 4, "selected": true, "text": "<p>That error is because you are not providing the post ID to check capabilities:</p>\n\n<p>This line:</p>\n\n<pre><code>if( !current_user_can( 'edit_post' ) ) {\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>if( !current_user_can( 'edit_post', $post_id ) ) {\n</code></pre>\n" }, { "answer_id": 357806, "author": "jave.web", "author_id": 45050, "author_profile": "https://wordpress.stackexchange.com/users/45050", "pm_score": 1, "selected": false, "text": "<p>If @cybmeta 's answer does not work for you (you don't have any particular post ID and check if user can edit posts in general) => you probably just forgot \"<strong><code>s</code></strong>\" \nat the end :) </p>\n\n<p>Code quote from docs + some comments of mine:</p>\n\n<pre><code>current_user_can( 'edit_posts' ); // SEE THE EXTRA \"s\" HERE ? :)\ncurrent_user_can( 'edit_post', $post-&gt;ID ); // check for specific post (NO \"s\"!)\ncurrent_user_can( 'edit_post_meta', $post-&gt;ID, $meta_key );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/current_user_can/\" rel=\"nofollow noreferrer\">DOCS: current_user_can( string $capability, mixed ...$args )</a></p>\n\n<ul>\n<li>also there is a DOC-typo in the whole docs with <code>...$args</code> being documented as just <code>$args</code> and their are practicaly not documented besides the code quote above</li>\n</ul>\n" } ]
2015/06/08
[ "https://wordpress.stackexchange.com/questions/190809", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73681/" ]
I've looked at previous examples of this problem but I can't find a solution for what is causing this notice based on what I've seen from other people. This appears at the top of the screen when I am adding a new post. 1145 is: ``` $post = get_post( $args[0] ); ``` I'm not getting any other kind of error so I'm not sure where in my code this is causing the problem. **Any help on this?** This is the code: ``` //show metabox in post editing page add_action('add_meta_boxes', 'kk_add_metabox' ); //save metabox data add_action('save_post', 'kk_save_metabox' ); //register widgets add_action('widgets_init', 'kk_widget_init'); function kk_add_metabox() { add_meta_box('kk_youtube', 'YouTube Video Link','kk_youtube_handler', 'post'); } /** * metabox handler */ function kk_youtube_handler($post) { $youtube_link = esc_attr( get_post_meta( $post->ID, 'kk_youtube', true ) ); echo '<label for="kk_youtube">YouTube Video Link</label><input type="text" id="kk_youtube" name="kk_youtube" value="' . $youtube_link . '" />'; } /** * save metadata */ function kk_save_metabox($post_id) { if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } //check if user can edit post if( !current_user_can( 'edit_post' ) ) { return; } if( isset($_POST['kk_youtube'] )) { update_post_meta($post_id, 'kk_youtube', esc_url($_POST['kk_youtube'])); } } /** * register widget */ function kk_widget_init() { register_widget('KK_Widget'); } /** * Class KK_Widget widget class */ class KK_Widget extends WP_Widget { function __construct() { $widget_options = array( 'classname' => 'kk_class', // For CSS class name 'description' => 'Show a YouTube video from post metadata' ); $this->WP_Widget('kk_id', 'YouTube Video', $widget_options); } /** * Show widget form in Appearance/Widgets */ function form($instance) { $defaults = array( 'title' => 'YouTube Video' ); $instance = wp_parse_args((array)$instance, $defaults); var_dump($instance); $title = esc_attr($instance['title']); echo '<p>Title <input type="text" class="widefat" name="' . $this->get_field_name('title') . '" value="' . $title . '" /></p>'; } function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); return $instance; } /** * Show widget in post/page */ function widget($args, $instance) { global $before_widget; global $after_widget; global $before_title; global $after_title; extract( $args ); $title = apply_filters('widget_title', $instance['title']); //show only if single post if(is_single()) { echo $before_widget; echo $before_title.$title.$after_title; //get post metadata $kk_youtube = esc_url(get_post_meta(get_the_ID(), 'kk_youtube', true)); //print widget content echo '<iframe width="200" height="200" frameborder="0" allowfullscreen src="http://www.youtube.com/embed/' . $this->get_yt_videoid($kk_youtube) . '"></iframe>'; echo $after_widget; } } function get_yt_videoid($url) { parse_str(parse_url($url, PHP_URL_QUERY), $my_array_of_vars); return $my_array_of_vars['v']; } } ```
That error is because you are not providing the post ID to check capabilities: This line: ``` if( !current_user_can( 'edit_post' ) ) { ``` Should be: ``` if( !current_user_can( 'edit_post', $post_id ) ) { ```
190,817
<p>I've been having trouble Automatically Compiling my .scss files into my main WordPress style.css file.</p> <p>I'm using Leafo's SCSSPHP script and trying to achieve a few things.</p> <ol> <li><p>i'm using Kirki (<a href="http://kirki.org/" rel="nofollow">http://kirki.org/</a>) to override the WordPress Theme Customizer and this is what i'm trying to do. Create my Panels/ Sections/ Settings in the theme customizer like Font Size/ Google Font Changer/ Background Colour etc... and when the value is changed in the theme customizer its updates the .scss file which will automatically compile to display the user what they have changed. Im trying to avoid inlining my CSS, please don't flame as themes like the X-theme do this and so does the Redux Framework.</p></li> <li><p>How would i go about including the variables from the Theme customizer into the .scss files, if it help im using _S theme with sass included. I'm not sure if i need to create a style.php file at theme root level or make my .scss files into mixins.scss.php?, also where will i have to place it so that it will be enqueued.</p></li> </ol> <p>In style.php located at the root of the theme:</p> <pre><code>&lt;?php header( 'Content-type: text/css' ); require dirname( __FILE__ ) . "/framework/scss/wp-scss/scssphp/scss.inc.php"; $scss = new scssc(); $scss-&gt;setImportPaths( "framework/scss/" ); $scss-&gt;setFormatter( "scss_formatter_compressed" ); echo $scss-&gt;compile( '@import "style.scss"' ); </code></pre> <p>and this is in my style.css file:</p> <pre><code>@import url("/framework/scss/style.scss"); </code></pre> <p>then i include the style.php/style.scss like this:</p> <pre><code>wp_enqueue_style( 'theme-style', get_stylesheet_directory_uri() . '/style.php/style.scss' ); </code></pre> <p>Which will compile my style.scss and adjust what i need to do using static values, which i'm trying to avoid and update the file using the variables from the theme customizer.</p> <p>Please let me know if you need more information,</p> <p>any help is much appreciated</p> <p>Thanks</p>
[ { "answer_id": 190924, "author": "Aristeides", "author_id": 17078, "author_profile": "https://wordpress.stackexchange.com/users/17078", "pm_score": 0, "selected": false, "text": "<p>I'm currently experimenting with adding support for pre-processors in Kirki.\nYou can find instructions on how to use that here: <a href=\"https://github.com/reduxframework/kirki/wiki/variables\" rel=\"nofollow\">https://github.com/reduxframework/kirki/wiki/variables</a>\nPlease note that the above only works with the github version of the plugin as it's not stable and still under development.</p>\n\n<p>If all you want to do is avoid inline CSS in the <code>&lt;head&gt;</code> then there are other ways to do it... Check out <a href=\"http://aristeides.com/blog/avoid-dynamic-css-in-head/\" rel=\"nofollow\">http://aristeides.com/blog/avoid-dynamic-css-in-head/</a></p>\n" }, { "answer_id": 199852, "author": "adambock", "author_id": 73732, "author_profile": "https://wordpress.stackexchange.com/users/73732", "pm_score": 1, "selected": false, "text": "<p>I wanted to achieve the same thing.. What I ended up doing was creating a function that collects the Kirki variables (see <a href=\"https://github.com/aristath/kirki/wiki/variables\" rel=\"nofollow\">here</a> about the use of variables in Kirki) and writes them to a scss..</p>\n\n<pre><code>$file = get_template_directory() . '/sass/custom/_custom_vars_mixins_options.scss';\n\nif(file_exists($file)){\n\n $output = \"\";\n\n $variables = Kirki::get_variables();\n foreach ( $variables as $variable =&gt; $vvalue ) {\n $output .= '$' . $variable . ': ' . $vvalue . ';' . PHP_EOL;\n //echo '@' . $variable . ':' . $value . ';';\n }\n\n file_put_contents($file, $output, FILE_TEXT )or die('&lt;br /&gt;Error writing to custom options CSS file');\n</code></pre>\n\n<p>This function is called each time the user saves their settings in WP Customizer through the sanitization callback, hence writing all the custom user settings to the .scss file.</p>\n" } ]
2015/06/08
[ "https://wordpress.stackexchange.com/questions/190817", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54516/" ]
I've been having trouble Automatically Compiling my .scss files into my main WordPress style.css file. I'm using Leafo's SCSSPHP script and trying to achieve a few things. 1. i'm using Kirki (<http://kirki.org/>) to override the WordPress Theme Customizer and this is what i'm trying to do. Create my Panels/ Sections/ Settings in the theme customizer like Font Size/ Google Font Changer/ Background Colour etc... and when the value is changed in the theme customizer its updates the .scss file which will automatically compile to display the user what they have changed. Im trying to avoid inlining my CSS, please don't flame as themes like the X-theme do this and so does the Redux Framework. 2. How would i go about including the variables from the Theme customizer into the .scss files, if it help im using \_S theme with sass included. I'm not sure if i need to create a style.php file at theme root level or make my .scss files into mixins.scss.php?, also where will i have to place it so that it will be enqueued. In style.php located at the root of the theme: ``` <?php header( 'Content-type: text/css' ); require dirname( __FILE__ ) . "/framework/scss/wp-scss/scssphp/scss.inc.php"; $scss = new scssc(); $scss->setImportPaths( "framework/scss/" ); $scss->setFormatter( "scss_formatter_compressed" ); echo $scss->compile( '@import "style.scss"' ); ``` and this is in my style.css file: ``` @import url("/framework/scss/style.scss"); ``` then i include the style.php/style.scss like this: ``` wp_enqueue_style( 'theme-style', get_stylesheet_directory_uri() . '/style.php/style.scss' ); ``` Which will compile my style.scss and adjust what i need to do using static values, which i'm trying to avoid and update the file using the variables from the theme customizer. Please let me know if you need more information, any help is much appreciated Thanks
I wanted to achieve the same thing.. What I ended up doing was creating a function that collects the Kirki variables (see [here](https://github.com/aristath/kirki/wiki/variables) about the use of variables in Kirki) and writes them to a scss.. ``` $file = get_template_directory() . '/sass/custom/_custom_vars_mixins_options.scss'; if(file_exists($file)){ $output = ""; $variables = Kirki::get_variables(); foreach ( $variables as $variable => $vvalue ) { $output .= '$' . $variable . ': ' . $vvalue . ';' . PHP_EOL; //echo '@' . $variable . ':' . $value . ';'; } file_put_contents($file, $output, FILE_TEXT )or die('<br />Error writing to custom options CSS file'); ``` This function is called each time the user saves their settings in WP Customizer through the sanitization callback, hence writing all the custom user settings to the .scss file.
190,823
<p>I want to display only a given level of menu items in my main nav menu when on that page. Currently sub menus of my main menu are part of the main menu HTML being an unordered list within the nav link list.</p> <pre><code>&lt;ul id="menu-main-top-navigation"&gt; &lt;li class="menu nav-1"&gt; ... &lt;ul&gt; &lt;li class="menu sub-nav-1"&gt;&lt;/li&gt; &lt;li class="menu sub-nav-2"&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="menu nav-2"&gt;...&lt;/li&gt; &lt;li class="menu nav-3"&gt;...&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>When on the page of menu nav-1, I want something like</p> <pre><code>&lt;ul id="menu-main-sub-navigation"&gt; &lt;li class="menu sub-nav-1"&gt;...&lt;/li&gt; &lt;li class="menu sub-nav-2"&gt;...&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Currently I have written a hacky piece of code which displays only the second level navigation for a given menu item when that page is open. However it doesn't work for any given level.</p> <p>I think a custom walker is the way to go but I cannot seem to get it to work...</p> <p><strong>EDIT:</strong></p> <p>Here is my hacky code which currently only works to display the second level sub navigation when on that page;</p> <pre><code>function submenu_display( $items, $args ) { $current_page_id = (string)get_the_ID(); $top_level = array(); $second_level = array(); foreach ( $items as $item ) { // The parent menu ID is different to the object (post) ID if ( $item-&gt;object_id === $current_page_id ) { $current_parent_id = $item-&gt;ID; } if ( $item-&gt;menu_item_parent === '0' ) { $top_level[ $item-&gt;ID ] = $item-&gt;object_id; } if ( array_key_exists( $item-&gt;menu_item_parent, $top_level ) ) { $second_level[ $item-&gt;ID ] = $item-&gt;object_id; } } if ( isset( $current_parent_id ) ) { if ( array_key_exists( $current_parent_id, $second_level ) ) { foreach ( $items as $item =&gt; $details ) { if ( $current_parent_id === $details-&gt;ID ) { $current_parent_id = $details-&gt;menu_item_parent; } } } if ( array_key_exists( $current_parent_id, $top_level ) ) { foreach ( $items as $item =&gt; $details ) { if ( $details-&gt;menu_item_parent != $current_parent_id ) { unset( $items[ $item ] ); } } } } else { $items = array(); } return $items; } </code></pre> <p>And used via </p> <pre><code>add_filter( 'wp_nav_menu_objects', 'submenu_display', 10, 2 ); wp_nav_menu( array( 'theme_location' =&gt; 'primary_navigation', 'menu_class' =&gt; 'nav nav-sub', 'menu_id' =&gt; 'menu-main-sub-navigation' ) ); remove_filter( 'wp_nav_menu_objects', 'submenu_display', 10 ); </code></pre>
[ { "answer_id": 190875, "author": "Robbert", "author_id": 25834, "author_profile": "https://wordpress.stackexchange.com/users/25834", "pm_score": 0, "selected": false, "text": "<p>Maybe you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items\" rel=\"nofollow\">wp_get_nav_menu_items()</a> to get the items and then check if an item has a parent.</p>\n\n<pre><code>&lt;?php\n$items = wp_get_nav_menu_items( 'header' );\nif( $items ) {\n echo '&lt;ul id=\"menu-main-top-navigation\"&gt;';\n foreach( $items as $index =&gt; $item ) {\n if( $item-&gt;menu_item_parent != 0 ) \n echo '&lt;li class=\"menu\"&gt;&lt;a href=\"' . get_permalink( $item-&gt;ID ) . '\"&gt;' . $item-&gt;post_title . '&lt;/a&gt;&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 190953, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": true, "text": "<p>You need to extend <code>Walker_Nav_Menu</code> in such a way that it only outputs, if I understand you, items that are not \"zero\" depth-- top level.</p>\n\n<pre><code>class my_extended_walker extends Walker_Nav_Menu {\n function start_lvl(&amp;$output, $depth, $args ) {\n if (0 !== $depth) {\n parent::start_lvl($output, $depth, $args);\n }\n }\n\n function end_lvl(&amp;$output, $depth, $args) {\n if (0 !== $depth) {\n parent::end_lvl($output, $depth, $args);\n }\n }\n\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if (0 !== $depth) {\n parent::start_el($output, $item, $depth, $args, $id);\n }\n }\n\n function end_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if (0 !== $depth) {\n parent::end_el($output, $item, $depth, $args, $id);\n }\n }\n}\n// testing\nwp_nav_menu( \n array( \n 'walker'=&gt;new my_extended_walker(),\n 'menu' =&gt; 'mymenu'\n ) \n);\n</code></pre>\n" } ]
2015/06/08
[ "https://wordpress.stackexchange.com/questions/190823", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51823/" ]
I want to display only a given level of menu items in my main nav menu when on that page. Currently sub menus of my main menu are part of the main menu HTML being an unordered list within the nav link list. ``` <ul id="menu-main-top-navigation"> <li class="menu nav-1"> ... <ul> <li class="menu sub-nav-1"></li> <li class="menu sub-nav-2"></li> </ul> </li> <li class="menu nav-2">...</li> <li class="menu nav-3">...</li> </ul> ``` When on the page of menu nav-1, I want something like ``` <ul id="menu-main-sub-navigation"> <li class="menu sub-nav-1">...</li> <li class="menu sub-nav-2">...</li> </ul> ``` Currently I have written a hacky piece of code which displays only the second level navigation for a given menu item when that page is open. However it doesn't work for any given level. I think a custom walker is the way to go but I cannot seem to get it to work... **EDIT:** Here is my hacky code which currently only works to display the second level sub navigation when on that page; ``` function submenu_display( $items, $args ) { $current_page_id = (string)get_the_ID(); $top_level = array(); $second_level = array(); foreach ( $items as $item ) { // The parent menu ID is different to the object (post) ID if ( $item->object_id === $current_page_id ) { $current_parent_id = $item->ID; } if ( $item->menu_item_parent === '0' ) { $top_level[ $item->ID ] = $item->object_id; } if ( array_key_exists( $item->menu_item_parent, $top_level ) ) { $second_level[ $item->ID ] = $item->object_id; } } if ( isset( $current_parent_id ) ) { if ( array_key_exists( $current_parent_id, $second_level ) ) { foreach ( $items as $item => $details ) { if ( $current_parent_id === $details->ID ) { $current_parent_id = $details->menu_item_parent; } } } if ( array_key_exists( $current_parent_id, $top_level ) ) { foreach ( $items as $item => $details ) { if ( $details->menu_item_parent != $current_parent_id ) { unset( $items[ $item ] ); } } } } else { $items = array(); } return $items; } ``` And used via ``` add_filter( 'wp_nav_menu_objects', 'submenu_display', 10, 2 ); wp_nav_menu( array( 'theme_location' => 'primary_navigation', 'menu_class' => 'nav nav-sub', 'menu_id' => 'menu-main-sub-navigation' ) ); remove_filter( 'wp_nav_menu_objects', 'submenu_display', 10 ); ```
You need to extend `Walker_Nav_Menu` in such a way that it only outputs, if I understand you, items that are not "zero" depth-- top level. ``` class my_extended_walker extends Walker_Nav_Menu { function start_lvl(&$output, $depth, $args ) { if (0 !== $depth) { parent::start_lvl($output, $depth, $args); } } function end_lvl(&$output, $depth, $args) { if (0 !== $depth) { parent::end_lvl($output, $depth, $args); } } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if (0 !== $depth) { parent::start_el($output, $item, $depth, $args, $id); } } function end_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if (0 !== $depth) { parent::end_el($output, $item, $depth, $args, $id); } } } // testing wp_nav_menu( array( 'walker'=>new my_extended_walker(), 'menu' => 'mymenu' ) ); ```
190,831
<p>How can I know what filter I can use to change anything and what my function have to return ?</p> <p>For exemple, sometimes I have to add a or a to a post title. It works (WP doesn't sanitize html tag here) but it's not readable when list the posts in admin because titles are always displayed as is, not HTML sanitize.</p> <p>So, I want to filter html tag on title but only when I list them in admin (not in front and not when I edit a post).</p> <p>Thanks.</p>
[ { "answer_id": 190875, "author": "Robbert", "author_id": 25834, "author_profile": "https://wordpress.stackexchange.com/users/25834", "pm_score": 0, "selected": false, "text": "<p>Maybe you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items\" rel=\"nofollow\">wp_get_nav_menu_items()</a> to get the items and then check if an item has a parent.</p>\n\n<pre><code>&lt;?php\n$items = wp_get_nav_menu_items( 'header' );\nif( $items ) {\n echo '&lt;ul id=\"menu-main-top-navigation\"&gt;';\n foreach( $items as $index =&gt; $item ) {\n if( $item-&gt;menu_item_parent != 0 ) \n echo '&lt;li class=\"menu\"&gt;&lt;a href=\"' . get_permalink( $item-&gt;ID ) . '\"&gt;' . $item-&gt;post_title . '&lt;/a&gt;&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 190953, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": true, "text": "<p>You need to extend <code>Walker_Nav_Menu</code> in such a way that it only outputs, if I understand you, items that are not \"zero\" depth-- top level.</p>\n\n<pre><code>class my_extended_walker extends Walker_Nav_Menu {\n function start_lvl(&amp;$output, $depth, $args ) {\n if (0 !== $depth) {\n parent::start_lvl($output, $depth, $args);\n }\n }\n\n function end_lvl(&amp;$output, $depth, $args) {\n if (0 !== $depth) {\n parent::end_lvl($output, $depth, $args);\n }\n }\n\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if (0 !== $depth) {\n parent::start_el($output, $item, $depth, $args, $id);\n }\n }\n\n function end_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if (0 !== $depth) {\n parent::end_el($output, $item, $depth, $args, $id);\n }\n }\n}\n// testing\nwp_nav_menu( \n array( \n 'walker'=&gt;new my_extended_walker(),\n 'menu' =&gt; 'mymenu'\n ) \n);\n</code></pre>\n" } ]
2015/06/08
[ "https://wordpress.stackexchange.com/questions/190831", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70080/" ]
How can I know what filter I can use to change anything and what my function have to return ? For exemple, sometimes I have to add a or a to a post title. It works (WP doesn't sanitize html tag here) but it's not readable when list the posts in admin because titles are always displayed as is, not HTML sanitize. So, I want to filter html tag on title but only when I list them in admin (not in front and not when I edit a post). Thanks.
You need to extend `Walker_Nav_Menu` in such a way that it only outputs, if I understand you, items that are not "zero" depth-- top level. ``` class my_extended_walker extends Walker_Nav_Menu { function start_lvl(&$output, $depth, $args ) { if (0 !== $depth) { parent::start_lvl($output, $depth, $args); } } function end_lvl(&$output, $depth, $args) { if (0 !== $depth) { parent::end_lvl($output, $depth, $args); } } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if (0 !== $depth) { parent::start_el($output, $item, $depth, $args, $id); } } function end_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if (0 !== $depth) { parent::end_el($output, $item, $depth, $args, $id); } } } // testing wp_nav_menu( array( 'walker'=>new my_extended_walker(), 'menu' => 'mymenu' ) ); ```
190,836
<p>I have array in post_meta like this:</p> <pre><code>array( 'option1' =&gt; 'true', 'option2' =&gt; 'true', 'option3' =&gt; 'false', option4' =&gt; 'true', 'option5' =&gt; 'false' ) </code></pre> <p>and I would like to filter <code>option1</code> with value true. Can someone help me?</p>
[ { "answer_id": 190875, "author": "Robbert", "author_id": 25834, "author_profile": "https://wordpress.stackexchange.com/users/25834", "pm_score": 0, "selected": false, "text": "<p>Maybe you can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items\" rel=\"nofollow\">wp_get_nav_menu_items()</a> to get the items and then check if an item has a parent.</p>\n\n<pre><code>&lt;?php\n$items = wp_get_nav_menu_items( 'header' );\nif( $items ) {\n echo '&lt;ul id=\"menu-main-top-navigation\"&gt;';\n foreach( $items as $index =&gt; $item ) {\n if( $item-&gt;menu_item_parent != 0 ) \n echo '&lt;li class=\"menu\"&gt;&lt;a href=\"' . get_permalink( $item-&gt;ID ) . '\"&gt;' . $item-&gt;post_title . '&lt;/a&gt;&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 190953, "author": "s_ha_dum", "author_id": 21376, "author_profile": "https://wordpress.stackexchange.com/users/21376", "pm_score": 3, "selected": true, "text": "<p>You need to extend <code>Walker_Nav_Menu</code> in such a way that it only outputs, if I understand you, items that are not \"zero\" depth-- top level.</p>\n\n<pre><code>class my_extended_walker extends Walker_Nav_Menu {\n function start_lvl(&amp;$output, $depth, $args ) {\n if (0 !== $depth) {\n parent::start_lvl($output, $depth, $args);\n }\n }\n\n function end_lvl(&amp;$output, $depth, $args) {\n if (0 !== $depth) {\n parent::end_lvl($output, $depth, $args);\n }\n }\n\n function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if (0 !== $depth) {\n parent::start_el($output, $item, $depth, $args, $id);\n }\n }\n\n function end_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n if (0 !== $depth) {\n parent::end_el($output, $item, $depth, $args, $id);\n }\n }\n}\n// testing\nwp_nav_menu( \n array( \n 'walker'=&gt;new my_extended_walker(),\n 'menu' =&gt; 'mymenu'\n ) \n);\n</code></pre>\n" } ]
2015/06/08
[ "https://wordpress.stackexchange.com/questions/190836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74347/" ]
I have array in post\_meta like this: ``` array( 'option1' => 'true', 'option2' => 'true', 'option3' => 'false', option4' => 'true', 'option5' => 'false' ) ``` and I would like to filter `option1` with value true. Can someone help me?
You need to extend `Walker_Nav_Menu` in such a way that it only outputs, if I understand you, items that are not "zero" depth-- top level. ``` class my_extended_walker extends Walker_Nav_Menu { function start_lvl(&$output, $depth, $args ) { if (0 !== $depth) { parent::start_lvl($output, $depth, $args); } } function end_lvl(&$output, $depth, $args) { if (0 !== $depth) { parent::end_lvl($output, $depth, $args); } } function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if (0 !== $depth) { parent::start_el($output, $item, $depth, $args, $id); } } function end_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { if (0 !== $depth) { parent::end_el($output, $item, $depth, $args, $id); } } } // testing wp_nav_menu( array( 'walker'=>new my_extended_walker(), 'menu' => 'mymenu' ) ); ```
190,839
<p>When we add a class to a menu item through dashboard, the css class is added to "li" tag of that item. Is there a way to add these css classes to "a" tag of that item, instead of "li" tag?</p> <p><img src="https://i.stack.imgur.com/KNgtf.png" alt="enter image description here"></p> <p>As you can see in the picture, I want to have this effect :</p> <pre><code>&lt;li id="menu-item-290"&gt; &lt;a class="my-class" href="http://localhost/en-wptuts/"&gt;home&lt;/a&gt; &lt;/li&gt; </code></pre> <p>instead of this one: </p> <pre><code>&lt;li id="menu-item-290" class="my-class"&gt; &lt;a href="http://localhost/en-wptuts/"&gt;home&lt;/a&gt; &lt;/li&gt; </code></pre> <p>So is it possible? Thank you in advance.</p>
[ { "answer_id": 190844, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Here are three approaches:</p>\n\n<h2>I - Plugin for the <code>a-class-</code> prefix:</h2>\n\n<p>We can target the <code>&lt;a&gt;</code> tags with the <code>a-class-...</code> class prefix.</p>\n\n<p>So in your case the way to get:</p>\n\n<pre><code>&lt;li id=\"menu-item-290\" class=\"blue yellow ...\"&gt;\n &lt;a class=\"red pink\" href=\"http://localhost/en-wptuts/\"&gt;home&lt;/a&gt;\n&lt;/li&gt; \n</code></pre>\n\n<p>is to use the following menu classes:</p>\n\n<pre><code>blue yellow a-class-red a-class-pink\n</code></pre>\n\n<p>We support this with the following plugin:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Menu Link Classes (I)\n * Description: Target menu link classes with the \"a-class-\" class prefix.\n * Author: Birgir Erlendsson (birgire)\n * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350\n * Version: 0.0.1\n */\n\n/**\n * Remove menu classes with the \"a-class-\" prefix\n */\nadd_filter( 'nav_menu_css_class', function( $classes )\n{\n return array_filter( \n $classes, \n function( $val )\n {\n return 'a-class-' !== substr( $val, 0, strlen( 'a-class-' ) );\n } \n );\n} );\n\n/**\n * Add only \"a-class-\" prefixed classes to the menu link attribute\n */\nadd_filter( 'nav_menu_link_attributes', function( $atts, $item )\n{\n if( isset( $item-&gt;classes ) )\n {\n $atts['class'] = str_replace( \n 'a-class-',\n '',\n join( \n ' ', \n array_filter(\n $item-&gt;classes, \n function( $val )\n {\n return 'a-class-' === substr( $val, 0, strlen( 'a-class-' ) );\n } \n ) \n )\n );\n }\n return $atts;\n}, 10, 2 );\n</code></pre>\n\n<h2>II - Plugin for the <code>li-class-</code> prefix:</h2>\n\n<p>We can also use the <code>li-class-...</code> class prefix to target the <code>&lt;li&gt;</code> tags instead.</p>\n\n<p>So in your case the way to get:</p>\n\n<pre><code>&lt;li id=\"menu-item-290\" class=\"blue yellow\"&gt;\n &lt;a class=\"red pink\" href=\"http://localhost/en-wptuts/\"&gt;home&lt;/a&gt;\n&lt;/li&gt; \n</code></pre>\n\n<p>is to use the following menu classes:</p>\n\n<pre><code>li-class-blue li-class-yellow red pink\n</code></pre>\n\n<p>Note that this will move <code>&lt;li&gt;</code> classes to <code>&lt;a&gt;</code> that do not have this prefix.</p>\n\n<p>Here's the plugin to support this:</p>\n\n<pre><code>&lt;?php \n/**\n * Plugin Name: Menu Link Classes (II) \n * Description: Add classes prefixed with \"li-class-\" to the li tag, else add it to the a tag.\n * Author: Birgir Erlendsson (birgire)\n * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350\n * Version: 0.0.1\n */\n\n/**\n * Only allow li classess that are prefixed with \"li-class-\"\n */\nadd_filter( 'nav_menu_css_class', function( $classes )\n{\n $newclasses = [];\n foreach( (array) $classes as $class )\n {\n if( 'li-class-' === substr( $class, 0, strlen( 'li-class-' ) ) )\n $newclasses[] = str_replace( 'li-class-', '', $class );\n }\n return $newclasses;\n\n} );\n\n/**\n * Add all classess that aren't prefixed with \"a-class-\" to the &lt;a&gt; tag\n */\nadd_filter( 'nav_menu_link_attributes', function( $atts, $item )\n{\n if( isset( $item-&gt;classes ) )\n {\n $atts['class'] = join( \n ' ', \n array_filter(\n $item-&gt;classes, \n function( $val )\n {\n return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) );\n } \n ) \n );\n }\n return $atts;\n}, 10, 2 );\n</code></pre>\n\n<h2>III - Plugin that moves all optional classes to the <code>&lt;a&gt;</code> tag:</h2>\n\n<p>If we use the following optional CSS classes:</p>\n\n<pre><code>blue yellow red pink\n</code></pre>\n\n<p>then all will be moved to the <code>&lt;a&gt;</code> tag:</p>\n\n<pre><code>&lt;li id=\"menu-item-290\" class=\"...\"&gt;\n &lt;a class=\"blue yellow red pink\" href=\"http://localhost/en-wptuts/\"&gt;home&lt;/a&gt;\n&lt;/li&gt; \n</code></pre>\n\n<p>Note that non-optional classes in <code>&lt;li&gt;</code> are not moved to <code>&lt;a&gt;</code>, so that's why we keep the <code>...</code> notation in the HTML example above.</p>\n\n<p>Support by the following plugin:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Menu Link Classes (III)\n * Description: Move all optional classes from the li tag to the a tag.\n * Author: Birgir Erlendsson (birgire)\n * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350\n * Version: 0.0.1\n */\n\n/**\n * Only allow li classess that are prefixed with \"li-class-\"\n */\nadd_filter( 'nav_menu_css_class', function( $classes, $item )\n{\n return array_filter( $classes, function( $val ) use ( $item )\n {\n return ! in_array( $val, (array) $item-&gt;wpse_classes ) ;\n } );\n}, 10, 2 );\n\nadd_filter( 'wp_get_nav_menu_items', function( $items, $menu, $args )\n{\n foreach( $items as $item )\n $item-&gt;wpse_classes = $item-&gt;classes;\n\n return $items;\n}, 10, 3 );\n\n/**\n * Add all classess that aren't prefixed with \"a-class-\" to the &lt;a&gt; tag\n */\nadd_filter( 'nav_menu_link_attributes', function( $atts, $item )\n{\n if( isset( $item-&gt;wpse_classes ) )\n {\n $atts['class'] = join( \n ' ', \n array_filter(\n $item-&gt;wpse_classes, \n function( $val )\n {\n return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) );\n } \n ) \n );\n }\n return $atts;\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 296888, "author": "jawad", "author_id": 137562, "author_profile": "https://wordpress.stackexchange.com/users/137562", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter ( 'nav_menu_css_class', 'so_37823371_menu_item_class', 10, 4 );\n\nfunction so_37823371_menu_item_class ( $classes, $item, $args, $depth ){\n $classes[] = 'nav-item';\n\n return $classes;\n}\nfunction add_link_atts($atts) {\n $atts['class'] = \"nav-link\";\n return $atts;\n}\nadd_filter( 'nav_menu_link_attributes', 'add_link_atts');\n</code></pre>\n" } ]
2015/06/08
[ "https://wordpress.stackexchange.com/questions/190839", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74115/" ]
When we add a class to a menu item through dashboard, the css class is added to "li" tag of that item. Is there a way to add these css classes to "a" tag of that item, instead of "li" tag? ![enter image description here](https://i.stack.imgur.com/KNgtf.png) As you can see in the picture, I want to have this effect : ``` <li id="menu-item-290"> <a class="my-class" href="http://localhost/en-wptuts/">home</a> </li> ``` instead of this one: ``` <li id="menu-item-290" class="my-class"> <a href="http://localhost/en-wptuts/">home</a> </li> ``` So is it possible? Thank you in advance.
Here are three approaches: I - Plugin for the `a-class-` prefix: ------------------------------------- We can target the `<a>` tags with the `a-class-...` class prefix. So in your case the way to get: ``` <li id="menu-item-290" class="blue yellow ..."> <a class="red pink" href="http://localhost/en-wptuts/">home</a> </li> ``` is to use the following menu classes: ``` blue yellow a-class-red a-class-pink ``` We support this with the following plugin: ``` <?php /** * Plugin Name: Menu Link Classes (I) * Description: Target menu link classes with the "a-class-" class prefix. * Author: Birgir Erlendsson (birgire) * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350 * Version: 0.0.1 */ /** * Remove menu classes with the "a-class-" prefix */ add_filter( 'nav_menu_css_class', function( $classes ) { return array_filter( $classes, function( $val ) { return 'a-class-' !== substr( $val, 0, strlen( 'a-class-' ) ); } ); } ); /** * Add only "a-class-" prefixed classes to the menu link attribute */ add_filter( 'nav_menu_link_attributes', function( $atts, $item ) { if( isset( $item->classes ) ) { $atts['class'] = str_replace( 'a-class-', '', join( ' ', array_filter( $item->classes, function( $val ) { return 'a-class-' === substr( $val, 0, strlen( 'a-class-' ) ); } ) ) ); } return $atts; }, 10, 2 ); ``` II - Plugin for the `li-class-` prefix: --------------------------------------- We can also use the `li-class-...` class prefix to target the `<li>` tags instead. So in your case the way to get: ``` <li id="menu-item-290" class="blue yellow"> <a class="red pink" href="http://localhost/en-wptuts/">home</a> </li> ``` is to use the following menu classes: ``` li-class-blue li-class-yellow red pink ``` Note that this will move `<li>` classes to `<a>` that do not have this prefix. Here's the plugin to support this: ``` <?php /** * Plugin Name: Menu Link Classes (II) * Description: Add classes prefixed with "li-class-" to the li tag, else add it to the a tag. * Author: Birgir Erlendsson (birgire) * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350 * Version: 0.0.1 */ /** * Only allow li classess that are prefixed with "li-class-" */ add_filter( 'nav_menu_css_class', function( $classes ) { $newclasses = []; foreach( (array) $classes as $class ) { if( 'li-class-' === substr( $class, 0, strlen( 'li-class-' ) ) ) $newclasses[] = str_replace( 'li-class-', '', $class ); } return $newclasses; } ); /** * Add all classess that aren't prefixed with "a-class-" to the <a> tag */ add_filter( 'nav_menu_link_attributes', function( $atts, $item ) { if( isset( $item->classes ) ) { $atts['class'] = join( ' ', array_filter( $item->classes, function( $val ) { return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) ); } ) ); } return $atts; }, 10, 2 ); ``` III - Plugin that moves all optional classes to the `<a>` tag: -------------------------------------------------------------- If we use the following optional CSS classes: ``` blue yellow red pink ``` then all will be moved to the `<a>` tag: ``` <li id="menu-item-290" class="..."> <a class="blue yellow red pink" href="http://localhost/en-wptuts/">home</a> </li> ``` Note that non-optional classes in `<li>` are not moved to `<a>`, so that's why we keep the `...` notation in the HTML example above. Support by the following plugin: ``` <?php /** * Plugin Name: Menu Link Classes (III) * Description: Move all optional classes from the li tag to the a tag. * Author: Birgir Erlendsson (birgire) * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350 * Version: 0.0.1 */ /** * Only allow li classess that are prefixed with "li-class-" */ add_filter( 'nav_menu_css_class', function( $classes, $item ) { return array_filter( $classes, function( $val ) use ( $item ) { return ! in_array( $val, (array) $item->wpse_classes ) ; } ); }, 10, 2 ); add_filter( 'wp_get_nav_menu_items', function( $items, $menu, $args ) { foreach( $items as $item ) $item->wpse_classes = $item->classes; return $items; }, 10, 3 ); /** * Add all classess that aren't prefixed with "a-class-" to the <a> tag */ add_filter( 'nav_menu_link_attributes', function( $atts, $item ) { if( isset( $item->wpse_classes ) ) { $atts['class'] = join( ' ', array_filter( $item->wpse_classes, function( $val ) { return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) ); } ) ); } return $atts; }, 10, 2 ); ```
190,865
<p>I have following problem.</p> <p>When I try to search by tag or by category, I have 404 error. It means that when URL is like "domain.com/category/smt/" or "domain.com/tag/smt/", I have the error.</p> <p>I tried to edit category's link, but it didn't solve my problem. Changing template also doesn't solve this.</p>
[ { "answer_id": 190844, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>Here are three approaches:</p>\n\n<h2>I - Plugin for the <code>a-class-</code> prefix:</h2>\n\n<p>We can target the <code>&lt;a&gt;</code> tags with the <code>a-class-...</code> class prefix.</p>\n\n<p>So in your case the way to get:</p>\n\n<pre><code>&lt;li id=\"menu-item-290\" class=\"blue yellow ...\"&gt;\n &lt;a class=\"red pink\" href=\"http://localhost/en-wptuts/\"&gt;home&lt;/a&gt;\n&lt;/li&gt; \n</code></pre>\n\n<p>is to use the following menu classes:</p>\n\n<pre><code>blue yellow a-class-red a-class-pink\n</code></pre>\n\n<p>We support this with the following plugin:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Menu Link Classes (I)\n * Description: Target menu link classes with the \"a-class-\" class prefix.\n * Author: Birgir Erlendsson (birgire)\n * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350\n * Version: 0.0.1\n */\n\n/**\n * Remove menu classes with the \"a-class-\" prefix\n */\nadd_filter( 'nav_menu_css_class', function( $classes )\n{\n return array_filter( \n $classes, \n function( $val )\n {\n return 'a-class-' !== substr( $val, 0, strlen( 'a-class-' ) );\n } \n );\n} );\n\n/**\n * Add only \"a-class-\" prefixed classes to the menu link attribute\n */\nadd_filter( 'nav_menu_link_attributes', function( $atts, $item )\n{\n if( isset( $item-&gt;classes ) )\n {\n $atts['class'] = str_replace( \n 'a-class-',\n '',\n join( \n ' ', \n array_filter(\n $item-&gt;classes, \n function( $val )\n {\n return 'a-class-' === substr( $val, 0, strlen( 'a-class-' ) );\n } \n ) \n )\n );\n }\n return $atts;\n}, 10, 2 );\n</code></pre>\n\n<h2>II - Plugin for the <code>li-class-</code> prefix:</h2>\n\n<p>We can also use the <code>li-class-...</code> class prefix to target the <code>&lt;li&gt;</code> tags instead.</p>\n\n<p>So in your case the way to get:</p>\n\n<pre><code>&lt;li id=\"menu-item-290\" class=\"blue yellow\"&gt;\n &lt;a class=\"red pink\" href=\"http://localhost/en-wptuts/\"&gt;home&lt;/a&gt;\n&lt;/li&gt; \n</code></pre>\n\n<p>is to use the following menu classes:</p>\n\n<pre><code>li-class-blue li-class-yellow red pink\n</code></pre>\n\n<p>Note that this will move <code>&lt;li&gt;</code> classes to <code>&lt;a&gt;</code> that do not have this prefix.</p>\n\n<p>Here's the plugin to support this:</p>\n\n<pre><code>&lt;?php \n/**\n * Plugin Name: Menu Link Classes (II) \n * Description: Add classes prefixed with \"li-class-\" to the li tag, else add it to the a tag.\n * Author: Birgir Erlendsson (birgire)\n * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350\n * Version: 0.0.1\n */\n\n/**\n * Only allow li classess that are prefixed with \"li-class-\"\n */\nadd_filter( 'nav_menu_css_class', function( $classes )\n{\n $newclasses = [];\n foreach( (array) $classes as $class )\n {\n if( 'li-class-' === substr( $class, 0, strlen( 'li-class-' ) ) )\n $newclasses[] = str_replace( 'li-class-', '', $class );\n }\n return $newclasses;\n\n} );\n\n/**\n * Add all classess that aren't prefixed with \"a-class-\" to the &lt;a&gt; tag\n */\nadd_filter( 'nav_menu_link_attributes', function( $atts, $item )\n{\n if( isset( $item-&gt;classes ) )\n {\n $atts['class'] = join( \n ' ', \n array_filter(\n $item-&gt;classes, \n function( $val )\n {\n return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) );\n } \n ) \n );\n }\n return $atts;\n}, 10, 2 );\n</code></pre>\n\n<h2>III - Plugin that moves all optional classes to the <code>&lt;a&gt;</code> tag:</h2>\n\n<p>If we use the following optional CSS classes:</p>\n\n<pre><code>blue yellow red pink\n</code></pre>\n\n<p>then all will be moved to the <code>&lt;a&gt;</code> tag:</p>\n\n<pre><code>&lt;li id=\"menu-item-290\" class=\"...\"&gt;\n &lt;a class=\"blue yellow red pink\" href=\"http://localhost/en-wptuts/\"&gt;home&lt;/a&gt;\n&lt;/li&gt; \n</code></pre>\n\n<p>Note that non-optional classes in <code>&lt;li&gt;</code> are not moved to <code>&lt;a&gt;</code>, so that's why we keep the <code>...</code> notation in the HTML example above.</p>\n\n<p>Support by the following plugin:</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: Menu Link Classes (III)\n * Description: Move all optional classes from the li tag to the a tag.\n * Author: Birgir Erlendsson (birgire)\n * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350\n * Version: 0.0.1\n */\n\n/**\n * Only allow li classess that are prefixed with \"li-class-\"\n */\nadd_filter( 'nav_menu_css_class', function( $classes, $item )\n{\n return array_filter( $classes, function( $val ) use ( $item )\n {\n return ! in_array( $val, (array) $item-&gt;wpse_classes ) ;\n } );\n}, 10, 2 );\n\nadd_filter( 'wp_get_nav_menu_items', function( $items, $menu, $args )\n{\n foreach( $items as $item )\n $item-&gt;wpse_classes = $item-&gt;classes;\n\n return $items;\n}, 10, 3 );\n\n/**\n * Add all classess that aren't prefixed with \"a-class-\" to the &lt;a&gt; tag\n */\nadd_filter( 'nav_menu_link_attributes', function( $atts, $item )\n{\n if( isset( $item-&gt;wpse_classes ) )\n {\n $atts['class'] = join( \n ' ', \n array_filter(\n $item-&gt;wpse_classes, \n function( $val )\n {\n return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) );\n } \n ) \n );\n }\n return $atts;\n}, 10, 2 );\n</code></pre>\n" }, { "answer_id": 296888, "author": "jawad", "author_id": 137562, "author_profile": "https://wordpress.stackexchange.com/users/137562", "pm_score": 0, "selected": false, "text": "<pre><code>add_filter ( 'nav_menu_css_class', 'so_37823371_menu_item_class', 10, 4 );\n\nfunction so_37823371_menu_item_class ( $classes, $item, $args, $depth ){\n $classes[] = 'nav-item';\n\n return $classes;\n}\nfunction add_link_atts($atts) {\n $atts['class'] = \"nav-link\";\n return $atts;\n}\nadd_filter( 'nav_menu_link_attributes', 'add_link_atts');\n</code></pre>\n" } ]
2015/06/08
[ "https://wordpress.stackexchange.com/questions/190865", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74367/" ]
I have following problem. When I try to search by tag or by category, I have 404 error. It means that when URL is like "domain.com/category/smt/" or "domain.com/tag/smt/", I have the error. I tried to edit category's link, but it didn't solve my problem. Changing template also doesn't solve this.
Here are three approaches: I - Plugin for the `a-class-` prefix: ------------------------------------- We can target the `<a>` tags with the `a-class-...` class prefix. So in your case the way to get: ``` <li id="menu-item-290" class="blue yellow ..."> <a class="red pink" href="http://localhost/en-wptuts/">home</a> </li> ``` is to use the following menu classes: ``` blue yellow a-class-red a-class-pink ``` We support this with the following plugin: ``` <?php /** * Plugin Name: Menu Link Classes (I) * Description: Target menu link classes with the "a-class-" class prefix. * Author: Birgir Erlendsson (birgire) * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350 * Version: 0.0.1 */ /** * Remove menu classes with the "a-class-" prefix */ add_filter( 'nav_menu_css_class', function( $classes ) { return array_filter( $classes, function( $val ) { return 'a-class-' !== substr( $val, 0, strlen( 'a-class-' ) ); } ); } ); /** * Add only "a-class-" prefixed classes to the menu link attribute */ add_filter( 'nav_menu_link_attributes', function( $atts, $item ) { if( isset( $item->classes ) ) { $atts['class'] = str_replace( 'a-class-', '', join( ' ', array_filter( $item->classes, function( $val ) { return 'a-class-' === substr( $val, 0, strlen( 'a-class-' ) ); } ) ) ); } return $atts; }, 10, 2 ); ``` II - Plugin for the `li-class-` prefix: --------------------------------------- We can also use the `li-class-...` class prefix to target the `<li>` tags instead. So in your case the way to get: ``` <li id="menu-item-290" class="blue yellow"> <a class="red pink" href="http://localhost/en-wptuts/">home</a> </li> ``` is to use the following menu classes: ``` li-class-blue li-class-yellow red pink ``` Note that this will move `<li>` classes to `<a>` that do not have this prefix. Here's the plugin to support this: ``` <?php /** * Plugin Name: Menu Link Classes (II) * Description: Add classes prefixed with "li-class-" to the li tag, else add it to the a tag. * Author: Birgir Erlendsson (birgire) * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350 * Version: 0.0.1 */ /** * Only allow li classess that are prefixed with "li-class-" */ add_filter( 'nav_menu_css_class', function( $classes ) { $newclasses = []; foreach( (array) $classes as $class ) { if( 'li-class-' === substr( $class, 0, strlen( 'li-class-' ) ) ) $newclasses[] = str_replace( 'li-class-', '', $class ); } return $newclasses; } ); /** * Add all classess that aren't prefixed with "a-class-" to the <a> tag */ add_filter( 'nav_menu_link_attributes', function( $atts, $item ) { if( isset( $item->classes ) ) { $atts['class'] = join( ' ', array_filter( $item->classes, function( $val ) { return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) ); } ) ); } return $atts; }, 10, 2 ); ``` III - Plugin that moves all optional classes to the `<a>` tag: -------------------------------------------------------------- If we use the following optional CSS classes: ``` blue yellow red pink ``` then all will be moved to the `<a>` tag: ``` <li id="menu-item-290" class="..."> <a class="blue yellow red pink" href="http://localhost/en-wptuts/">home</a> </li> ``` Note that non-optional classes in `<li>` are not moved to `<a>`, so that's why we keep the `...` notation in the HTML example above. Support by the following plugin: ``` <?php /** * Plugin Name: Menu Link Classes (III) * Description: Move all optional classes from the li tag to the a tag. * Author: Birgir Erlendsson (birgire) * Plugin URI: http://wordpress.stackexchange.com/a/190844/26350 * Version: 0.0.1 */ /** * Only allow li classess that are prefixed with "li-class-" */ add_filter( 'nav_menu_css_class', function( $classes, $item ) { return array_filter( $classes, function( $val ) use ( $item ) { return ! in_array( $val, (array) $item->wpse_classes ) ; } ); }, 10, 2 ); add_filter( 'wp_get_nav_menu_items', function( $items, $menu, $args ) { foreach( $items as $item ) $item->wpse_classes = $item->classes; return $items; }, 10, 3 ); /** * Add all classess that aren't prefixed with "a-class-" to the <a> tag */ add_filter( 'nav_menu_link_attributes', function( $atts, $item ) { if( isset( $item->wpse_classes ) ) { $atts['class'] = join( ' ', array_filter( $item->wpse_classes, function( $val ) { return 'li-class-' !== substr( $val, 0, strlen( 'li-class-' ) ); } ) ); } return $atts; }, 10, 2 ); ```
190,906
<p>How can i create unique slug while inserting a new post..</p> <p>I know i can query posts and compare the records to create unique slug but</p> <p>I want to insert a post with unique slug at the same time.</p> <p>Lets say i have post title and needed data for the post and want to insert it with wpquery Does wordpress have a function to handle all by itself..</p> <p>When i insert a post with st. like</p> <pre><code>$my_post = array( 'post_title' =&gt; 'My post', 'post_content' =&gt; 'This is my post.', 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_category' =&gt; array(8,39) ); // Insert the post into the database wp_insert_post( $my_post ); </code></pre> <p>Doest it handle the slug automatically..</p> <p>I want to insert this post and open it with php redirect after insert.. </p>
[ { "answer_id": 190908, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": false, "text": "<p>You don't have to think about it - WordPress will take care of this.</p>\n\n<p>Let's take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3094\" rel=\"nofollow\"><code>wp_insert_post</code> source code</a>...</p>\n\n<p>On line <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3203\" rel=\"nofollow\">3203</a> you'll find:</p>\n\n<pre><code>if ( empty($post_name) ) {\n if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {\n $post_name = sanitize_title($post_title);\n } else {\n $post_name = '';\n }\n} else {\n // On updates, we need to check to see if it's using the old, fixed sanitization context.\n $check_name = sanitize_title( $post_name, '', 'old-save' );\n if ( $update &amp;&amp; strtolower( urlencode( $post_name ) ) == $check_name &amp;&amp; get_post_field( 'post_name', $post_ID ) == $check_name ) {\n $post_name = $check_name;\n } else { // new post, or slug has changed.\n $post_name = sanitize_title($post_name);\n }\n}\n</code></pre>\n\n<p>So if no <code>post_name</code> is set, WP will generate it from <code>post_title</code>.</p>\n\n<p>And then on line <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3325\" rel=\"nofollow\">3325</a>:</p>\n\n<pre><code> $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );\n</code></pre>\n\n<p>So WP will take care of uniqueness of <code>post_name</code>.</p>\n" }, { "answer_id": 190909, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>WordPress will take care about unique slug. If you want to redirect to the post after it has been created, you can get the permalink using the post ID which is returned by <code>wp_insert_poost()</code> if it was successfull:</p>\n\n<pre><code>$my_post = array(\n 'post_title' =&gt; 'My post',\n 'post_content' =&gt; 'This is my post.',\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_category' =&gt; array(8,39)\n);\n\n// Insert the post into the database\n$post_id = wp_insert_post( $my_post );\n\n// Check there was no errors\nif( $post_id &amp;&amp; ! is_wp_error( $post_id ) ) {\n\n wp_redirect( get_the_permalink( $post_id ) );\n exit;\n\n}\n</code></pre>\n" } ]
2015/06/09
[ "https://wordpress.stackexchange.com/questions/190906", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62148/" ]
How can i create unique slug while inserting a new post.. I know i can query posts and compare the records to create unique slug but I want to insert a post with unique slug at the same time. Lets say i have post title and needed data for the post and want to insert it with wpquery Does wordpress have a function to handle all by itself.. When i insert a post with st. like ``` $my_post = array( 'post_title' => 'My post', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(8,39) ); // Insert the post into the database wp_insert_post( $my_post ); ``` Doest it handle the slug automatically.. I want to insert this post and open it with php redirect after insert..
You don't have to think about it - WordPress will take care of this. Let's take a look at [`wp_insert_post` source code](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3094)... On line [3203](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3203) you'll find: ``` if ( empty($post_name) ) { if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) { $post_name = sanitize_title($post_title); } else { $post_name = ''; } } else { // On updates, we need to check to see if it's using the old, fixed sanitization context. $check_name = sanitize_title( $post_name, '', 'old-save' ); if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) { $post_name = $check_name; } else { // new post, or slug has changed. $post_name = sanitize_title($post_name); } } ``` So if no `post_name` is set, WP will generate it from `post_title`. And then on line [3325](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3325): ``` $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent ); ``` So WP will take care of uniqueness of `post_name`.
190,915
<p>I have this custom form inside a Wordpress page template</p> <pre><code>&lt;?php if(!is_user_logged_in()) { if(get_option('users_can_register')) { if($_POST){ $username = $wpdb-&gt;escape($_REQUEST['user_login']); if(empty($username)) { echo "&lt;span style='color:#FF0000'&gt;&lt;strong&gt;Error..&lt;/strong&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;You have to fill in the username."; exit(); } $email = $wpdb-&gt;escape($_REQUEST['user_email']); if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)) { echo "&lt;span style='color:#FF0000'&gt;&lt;strong&gt;Error..&lt;/strong&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;please use a calid e-mailadress."; exit(); } //$random_password = wp_generate_password( 12, false ); $pass1 = $wpdb-&gt;escape($_REQUEST['pass1']); $pass2 = $wpdb-&gt;escape($_REQUEST['pass2']); if ($pass1 != $pass2){ echo "&lt;span style='color:#FF0000'&gt;&lt;strong&gt;Error..&lt;/strong&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;please use a passwords don't match."; exit(); } $random_password = $pass1; $status = wp_create_user( $username, $random_password, $email ); if ( is_wp_error($status) ) echo "&lt;span style='color:#FF0000'&gt;&lt;strong&gt;Feil..&lt;/strong&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Username allready exist. please try another one."; else { $from = get_option('admin_email'); $headers = 'From: '.$from . "\r\n"; $subject = "Registration ok!"; $msg = "Welcome, you are now registered. Here is your username and password.\Info:\Username: $username\Password: $random_password"; wp_mail( $email, $subject, $msg, $headers ); echo "&lt;strong&gt;You are now registered. An e-mail is now sent to you with your username and password.."; } exit(); } else { ?&gt; &lt;form method="post" action="&lt;?php echo site_url('wp-login.php?action=register', 'login_post') ?&gt;" id="registerform" class="col-xs-12" name="registerform"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 col-md-6"&gt; &lt;p&gt; &lt;label for="user_login"&gt;Username&lt;/label&gt; &lt;input id="user_login" class="input" type="text" size="20" value="" name="user_login"&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="user_email"&gt;Email&lt;/label&gt; &lt;input id="user_email" class="input" type="email" size="25" value="" name="user_email"&gt; &lt;/p&gt; &lt;p&gt; Password &lt;input type="password" name="pass1" size="25" value=""&gt; Repeat Password &lt;input type="password" name="pass2" size="25" value=""&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="submit"&gt; &lt;input id="wp-register" class="button-primary pull-right col-xs-12 col-md-3" type="submit" value="Register" name="wp-submit" tabindex="103"&gt; &lt;input type="hidden" value="/login-area/?action=register&amp;success=1" name="redirect_to"&gt; &lt;input type="hidden" name="user-cookie" value="1" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; jQuery("#wp-register").click(function() { var input_data = jQuery('#registerform').serialize(); jQuery.ajax({ type: "POST", url: "&lt;?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?&gt;", data: input_data, success: function(data){ alert('Success'); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.status); // I would like to get what the error is } }); return false; }); &lt;/script&gt; &lt;?php } } else ?&gt; Already registered? Login to your account with the form in the sidebar. &lt;?php } else { ?&gt; You are already logged in... &lt;?php } ?&gt; </code></pre> <p>The PHP seems to work fine as when I console log it I get the right message when there is an error.</p> <p>How can I show these errors inside the Ajax success or error functions?</p> <p>The code I'm using always seems to always get to the success function even if there are some errors.</p> <p>I would like to know what errors there are and print a message with the type of error somewhere on the page and if it's successful I'd like to print a successful message.</p>
[ { "answer_id": 190908, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": false, "text": "<p>You don't have to think about it - WordPress will take care of this.</p>\n\n<p>Let's take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3094\" rel=\"nofollow\"><code>wp_insert_post</code> source code</a>...</p>\n\n<p>On line <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3203\" rel=\"nofollow\">3203</a> you'll find:</p>\n\n<pre><code>if ( empty($post_name) ) {\n if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {\n $post_name = sanitize_title($post_title);\n } else {\n $post_name = '';\n }\n} else {\n // On updates, we need to check to see if it's using the old, fixed sanitization context.\n $check_name = sanitize_title( $post_name, '', 'old-save' );\n if ( $update &amp;&amp; strtolower( urlencode( $post_name ) ) == $check_name &amp;&amp; get_post_field( 'post_name', $post_ID ) == $check_name ) {\n $post_name = $check_name;\n } else { // new post, or slug has changed.\n $post_name = sanitize_title($post_name);\n }\n}\n</code></pre>\n\n<p>So if no <code>post_name</code> is set, WP will generate it from <code>post_title</code>.</p>\n\n<p>And then on line <a href=\"https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3325\" rel=\"nofollow\">3325</a>:</p>\n\n<pre><code> $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );\n</code></pre>\n\n<p>So WP will take care of uniqueness of <code>post_name</code>.</p>\n" }, { "answer_id": 190909, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>WordPress will take care about unique slug. If you want to redirect to the post after it has been created, you can get the permalink using the post ID which is returned by <code>wp_insert_poost()</code> if it was successfull:</p>\n\n<pre><code>$my_post = array(\n 'post_title' =&gt; 'My post',\n 'post_content' =&gt; 'This is my post.',\n 'post_status' =&gt; 'publish',\n 'post_author' =&gt; 1,\n 'post_category' =&gt; array(8,39)\n);\n\n// Insert the post into the database\n$post_id = wp_insert_post( $my_post );\n\n// Check there was no errors\nif( $post_id &amp;&amp; ! is_wp_error( $post_id ) ) {\n\n wp_redirect( get_the_permalink( $post_id ) );\n exit;\n\n}\n</code></pre>\n" } ]
2015/06/09
[ "https://wordpress.stackexchange.com/questions/190915", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74398/" ]
I have this custom form inside a Wordpress page template ``` <?php if(!is_user_logged_in()) { if(get_option('users_can_register')) { if($_POST){ $username = $wpdb->escape($_REQUEST['user_login']); if(empty($username)) { echo "<span style='color:#FF0000'><strong>Error..</strong></span><br /><br />You have to fill in the username."; exit(); } $email = $wpdb->escape($_REQUEST['user_email']); if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $email)) { echo "<span style='color:#FF0000'><strong>Error..</strong></span><br /><br />please use a calid e-mailadress."; exit(); } //$random_password = wp_generate_password( 12, false ); $pass1 = $wpdb->escape($_REQUEST['pass1']); $pass2 = $wpdb->escape($_REQUEST['pass2']); if ($pass1 != $pass2){ echo "<span style='color:#FF0000'><strong>Error..</strong></span><br /><br />please use a passwords don't match."; exit(); } $random_password = $pass1; $status = wp_create_user( $username, $random_password, $email ); if ( is_wp_error($status) ) echo "<span style='color:#FF0000'><strong>Feil..</strong></span><br /><br />Username allready exist. please try another one."; else { $from = get_option('admin_email'); $headers = 'From: '.$from . "\r\n"; $subject = "Registration ok!"; $msg = "Welcome, you are now registered. Here is your username and password.\Info:\Username: $username\Password: $random_password"; wp_mail( $email, $subject, $msg, $headers ); echo "<strong>You are now registered. An e-mail is now sent to you with your username and password.."; } exit(); } else { ?> <form method="post" action="<?php echo site_url('wp-login.php?action=register', 'login_post') ?>" id="registerform" class="col-xs-12" name="registerform"> <div class="row"> <div class="col-xs-12 col-md-6"> <p> <label for="user_login">Username</label> <input id="user_login" class="input" type="text" size="20" value="" name="user_login"> </p> <p> <label for="user_email">Email</label> <input id="user_email" class="input" type="email" size="25" value="" name="user_email"> </p> <p> Password <input type="password" name="pass1" size="25" value=""> Repeat Password <input type="password" name="pass2" size="25" value=""> </p> </div> <div class="submit"> <input id="wp-register" class="button-primary pull-right col-xs-12 col-md-3" type="submit" value="Register" name="wp-submit" tabindex="103"> <input type="hidden" value="/login-area/?action=register&success=1" name="redirect_to"> <input type="hidden" name="user-cookie" value="1" /> </div> </div> </form> <script type="text/javascript"> jQuery("#wp-register").click(function() { var input_data = jQuery('#registerform').serialize(); jQuery.ajax({ type: "POST", url: "<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>", data: input_data, success: function(data){ alert('Success'); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.status); // I would like to get what the error is } }); return false; }); </script> <?php } } else ?> Already registered? Login to your account with the form in the sidebar. <?php } else { ?> You are already logged in... <?php } ?> ``` The PHP seems to work fine as when I console log it I get the right message when there is an error. How can I show these errors inside the Ajax success or error functions? The code I'm using always seems to always get to the success function even if there are some errors. I would like to know what errors there are and print a message with the type of error somewhere on the page and if it's successful I'd like to print a successful message.
You don't have to think about it - WordPress will take care of this. Let's take a look at [`wp_insert_post` source code](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3094)... On line [3203](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3203) you'll find: ``` if ( empty($post_name) ) { if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) { $post_name = sanitize_title($post_title); } else { $post_name = ''; } } else { // On updates, we need to check to see if it's using the old, fixed sanitization context. $check_name = sanitize_title( $post_name, '', 'old-save' ); if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) { $post_name = $check_name; } else { // new post, or slug has changed. $post_name = sanitize_title($post_name); } } ``` So if no `post_name` is set, WP will generate it from `post_title`. And then on line [3325](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3325): ``` $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent ); ``` So WP will take care of uniqueness of `post_name`.